首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。