leetcode上有两个关于n皇后的问题,两个题目基本是一样的,只是第二个是把所有的排法求出来。n皇后最简单的就是用递归,每次判断一行的一个位置,如果合法,就判断下一行,不合法再判断下一个位置
N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
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; } };
N-Queens
The n-queens puzzle is the problem of placing n queens
on an n×n chessboard such that no two queens
attack each other.
Given an integer n, return all distinct solutions to the n-queens
puzzle.
Each solution contains a distinct board configuration of the n-queens‘ placement, where ‘Q‘
and ‘.‘
both
indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".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; };
leetcode之n皇后问题
时间: 2024-11-06 13:41:10