class Solution { public: //由于每次都是遍历下一行,所以两个皇后的行肯定不同;由于hasUse用于判断当前列是否已经占用,所以这里之需要判断对角线的位置 bool check(int row,int col,int n,vector<int> queue) { int i; for(i = 0; i < row;i++) { if(abs(i - row) == abs(queue[i]-col))return false; } return true; } //n表示皇后的个数 void totalNQueens(int row,int n,vector<int>& queue,vector<bool>& hasUse,int& count) { if(row == n) { count ++; return; } int col; for(col = 0;col < n;++col) { if(!hasUse[col] && check(row,col,n,queue)) { hasUse[col] = true;//表示第col列已经被使用 queue[row] = col;//表示第row行选择的是第col列作为皇后 totalNQueens(row+1,n,queue,hasUse,count); hasUse[col] = false; queue[row] = -1; } } } int totalNQueens(int n) { int count = 0; vector<int> queue(n,-1); vector<bool> hasUse(n,false); totalNQueens(0,n,queue,hasUse,count); return count; } };
‘Q‘
and ‘.‘
both
indicate a queen and an empty space respectively.[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
class Solution { public: bool check(int row,int col,int n,vector<int> queue) { int i; for(i = 0; i < row;i++) { if(abs(i - row) == abs(queue[i]-col))return false; } return true; } void solveNQueens(int row,int n,vector<int>& queue,vector<bool>& hasUse) { if(row == n)//只有此处和上面不同,这里是把每一个位置保存到结果中而不是记录个数 { vector<string> solve; int i,j; for(i = 0;i < row;++i) { string s; for(j = 0;j < queue[i];++j)s += '.'; s += 'Q'; for(++j;j < n;++j) s+= '.'; solve.push_back(s); } res.push_back(solve); return; } int col; for(col = 0;col < n;++col) { if(!hasUse[col] && check(row,col,n,queue)) { hasUse[col] = true; queue[row] = col; solveNQueens(row+1,n,queue,hasUse); hasUse[col] = false; queue[row] = -1; } } } vector<vector<string> > solveNQueens(int n) { vector<int> queue(n,-1); vector<bool> hasUse(n,false); solveNQueens(0,n,queue,hasUse); return res; } private: vector<vector<string> > res; };
原文:http://blog.csdn.net/fangjian1204/article/details/38491837