首页 > 代码库 > 52. N-Queens II

52. N-Queens II

Problem statement:

Follow up for N-Queens problem.

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

技术分享

Solution:

Compare with 51. N-Queens, this problem wants the number of  possible solutions. It also belongs to DFS, however, it belongs to another DFS template.

The return value of DFS function should be an integer instead of void. In each level DFS, the return value should be the sum of lower level result. The return value of final result is the DFS result from 0.

class Solution {public:    int totalNQueens(int n) {        vector<string> solu(n, string(n, 0));        return NQueens(solu, 0, n, n);    }private:    int NQueens(vector<string>& solu, int row, int col, int n){        if(row == n){            return 1;        }        int cnt = 0;        for(int i = 0; i < col; i++){            if(isvalid(solu, row, i, n)){                solu[row][i] = Q;                cnt += NQueens(solu, row + 1, col, n);                solu[row][i] = .;            }        }        return cnt;    }    bool isvalid(vector<string>& solu, int row, int col, int n){        for(int i = row - 1, left = col - 1, right = col + 1; i >= 0; i--, left--, right++){            if(solu[i][col] == Q || (left >= 0 && solu[i][left] == Q) || (right < n && solu[i][right] == Q)){                return false;            }        }        return true;    }};        

 

52. N-Queens II