Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
解N皇后问题,N-Queens要求返回所有的解,而本题只需要返回可行解的数目
class Solution { public: bool isValid(vector<string>matrix, int x, int y, int n){ //所在列 int i=0, j=y; for(;i<n;i++){ if(i!=x&&matrix[i][j]=='Q')return false; } //指向左上角的斜线 i=x-1; j=y-1; while(i>=0&&j>=0){ if(matrix[i][j]=='Q')return false; i--;j--; } //指向右上角的斜线 i=x-1; j=y+1; while(i>=0&&j<n){ if(matrix[i][j]=='Q')return false; i--;j++; } return true; } void dfs(int&result, vector<string>matrix, int lineNo, int n){ if(lineNo>n){ result++; return; } for(int i=0; i<n; i++){ matrix[lineNo-1][i]='Q'; if(isValid(matrix, lineNo-1, i, n)){ dfs(result, matrix, lineNo+1, n); } matrix[lineNo-1][i]='.'; } } int totalNQueens(int n) { int result=0; vector<string>matrix(n, string(n,'.')); dfs(result, matrix, 1, n); return result; } };
LeetCode: N-Queens II [051],布布扣,bubuko.com
原文地址:http://blog.csdn.net/harryhuang1990/article/details/26689051