N-Queens [Leetcode解题报告]

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.."]
]

解题思路:典型的八皇后问题,我用的DFS做的,代码如下:

 void bfs(vector<vector<string>> &res,vector<int> &temp,int k,int n){
        if(k==n){
            vector<string> v(n,string(n,'.'));
            for(int i=0;i<temp.size();i++){
                v[i][temp[i]]='Q';
            }
            res.push_back(v);
            return;
        }
        int j;
        for(int i=0;i<n;i++){
            for(j=0;j<k;j++){
                if(i==temp[j]||(k-j)==(temp[j]-i)||(k-j)==(i-temp[j]))
                break;
            }
            if(j==k){
                temp[k]=i;
                bfs(res,temp,k+1,n);
            }
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> res;
        if(n<1)return res;
        vector<int> temp(n);
        bfs(res,temp,0,n);
        return res;
    }

还有一个利用行标记、对角线标记的方法,速度比上面的方法快一些,感兴趣的可以看看这里

你可能感兴趣的:(LeetCode)