标签:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution { public: vector<vector<string>> solveNQueens(int n) { result.clear(); string str=""; for(int i = 0; i<n;i++) str+= "."; vector<string> answer(n,str); vector<bool> columnFlag(n,false); dfs(answer,columnFlag, n, 0); return result; } void dfs(vector<string> &answer, vector<bool> &columnFlag, int n, int depth){ if(depth == n) { result.push_back(answer); return; } bool haveAnswer = true; for(int i = 0; i < n; i++) { if(columnFlag[i]) continue; //check column for (int j = 1; depth-j >= 0 && i-j >= 0; j++) //check upper left diagonal { if(answer[depth-j][i-j]==‘Q‘) { haveAnswer = false; break; } } if(!haveAnswer) { haveAnswer = true; continue; } for (int j = 1; depth-j >= 0 && i+j <= n-1; j++) //check upper right diagonal { if(answer[depth-j][i+j]==‘Q‘) { haveAnswer = false; break; } } if(!haveAnswer) { haveAnswer = true; continue; } answer[depth][i] = ‘Q‘; columnFlag[i] = true; dfs(answer, columnFlag, n, depth+1); answer[depth][i] = ‘.‘; columnFlag[i] = false; } } private: vector<vector<string>> result; };
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4856959.html