Leetcode N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

典型的N皇后问题,对每行元素进行搜索即可
class Solution {
public:
    int n;
    vector<vector<string> > res;
    vector<int> queenIndex;
    bool judgePlaceQueen(int x,int y){
        for(int i = 0 ; i < x; ++ i){
            if(abs(i-x) == abs(queenIndex[i]-queenIndex[x]) || queenIndex[i] == y)  return false;
        }
        return true;
    }
    
    void dfs(int index){
        if(index == n){
            vector<string> board(n,string(n,'.'));
            for(int i = 0 ; i < n ; ++ i){
                board[i][queenIndex[i]] = 'Q';
            }
            res.push_back(board);
            return;
        }
        for(int i = 0 ; i < n; ++ i){
            queenIndex[index] = i;
            if(judgePlaceQueen(index,i)) dfs(index+1);
        }
    }
    
    vector<vector<string> > solveNQueens(int n) {
        this->n  = n;
        for(int i = 0 ;i < n; ++  i) queenIndex.push_back(0);
        dfs(0);
        return res;
    }
};

 下面用排列组合的方法解决。

N个皇后放置在NxN的棋盘上,必定每行一个皇后,将每行中的皇后的位置用0~N-1的数字来表示,总共N行,

这样就是0~N-1数字的排列。这样的排列只满足了任意两个皇后不能处在同一行或者一列上,并不能保证它们在一斜线上。

在加入数字排列前,判断该数字是否和排列里所有的数字在斜线上:

  如果两个数字在斜线上,那么两数之差的绝对值等于其下标差得绝对值。

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > res;
        vector<int> queen(n,0);
        for(int i = 0;  i < n ; ++ i) queen[i] = i;
        do{
            bool flag = false;
            for(int i = 1; i< n && !flag; ++ i){
                for(int j = 0 ; j < i && !flag; ++ j){
                    if(abs(j-i) == abs(queen[j]-queen[i]) || queen[j] == queen[i]) flag = true;
                }
            }
            if(!flag){
                vector<string> board(n,string(n,'.'));
                for(int i = 0 ; i < n; ++ i) board[i][queen[i]]='Q';
                res.push_back(board);
            }
        }while(next_permutation(queen.begin(),queen.end()));
        return res;
    }
};
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3826399.html