52. N-Queens II
Posted 蓝色地中海
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章