N-Queens and N-Queens II

时间:2021-09-01 11:07:34
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

N-Queens and N-Queens II
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-Queens问题是回溯的典型题目了,跟数独的解法有点像。我们用path来存储可能出现的result的值,每次给新的一行中选择一个字符设为Q,然后检查其合法性。直到得到正确的解就放入result中。检查合法性的时候要检查列,左斜线和右斜线,代码如下:

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> result;
        vector<string> path(n, string(n,'.'));
        find(0, n, result, path);
        return result;
    }

    void find(int row, int n, vector<vector<string>>& result,vector<string>& path){
        if(row==n){
            result.push_back(path);
            return;
        }
        for(int col=0;col<n;col++){
            if(check(n,row,col,path)){
                path[row][col]='Q';
                find(row+1,n,result,path);
                path[row][col]='.';
            }
        }
    }

    bool check(int n, int row, int col, vector<string>& path){
        for(int i=0;i<row;i++){
            if(path[i][col]=='Q')
                return false;
        }
        for(int r=row-1, c=col-1;r>=0 && c>=0;r--,c--){
            if(path[r][c]=='Q')
                return false;
        }
        for(int r=row-1, c=col+1;r>=0 && c<n;r--,c++){
            if(path[r][c]=='Q')
                return false;
        }
        return true;
    }
};
Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

N-Queens and N-Queens II

与上个题相比,这个题只是要求输出结果的个数就可以了,不需要改太多的代码,设置一个全局的变量num,当找到一个解的时候,就把num++;其他的不需要修改,便可得到结果。

class Solution {
public:
    int num;
    int totalNQueens(int n) {
        num=0;
        vector<string> path(n,string(n,'.'));
        find(0,n,path);
        return num;
    }
    void find(int row, int n , vector<string>& path){
        if(row==n)
            num++;
        for(int col=0;col<n;col++){
            if(check(row,col,n,path)){
                path[row][col]='Q';
                find(row+1,n,path);
                path[row][col]='.';
            }
        }
    }

    bool check(int row, int col, int n, vector<string>& path){
        for(int i=0;i<row;i++){
            if(path[i][col]=='Q')
                return false;
        }
        for(int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
            if(path[i][j]=='Q')
                return false;
        }
        for(int i=row-1,j=col+1;i>=0 && j<n;i--,j++){
            if(path[i][j]=='Q')
                return false;
        }
        return true;
    }
};