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.."] ] 深搜可行解,对于每个皇后,它所在的行、列、两条斜方向都必须没有其他的皇后,这样才不会引起冲突,那么我们就对棋盘每行进行搜索,对每一行可以放皇后的的格子均深搜,如果能搜到n行,那么说明目前棋盘的布局是N皇后解的一种
1 class Solution { 2 public: 3 vector<vector<string> > solveNQueens(int n) { 4 ans.clear(); 5 board.resize(n); //初始化棋盘 6 for(int i=0; i<n; ++i) 7 board[i].resize(n, false); 8 dfs(0, n); 9 return ans; 10 } 11 12 void dfs(int k, int n) { 13 if( k==n ) { 14 vector<string> vstr = board2str(); 15 ans.push_back(vstr); 16 return ; 17 } 18 for(int i=0; i<n; ++i) 19 if( canPut(k, i, n) ) { 20 board[k][i] = true; 21 dfs(k+1, n); 22 board[k][i] = false; 23 } 24 } 25 26 bool canPut(int x, int y, int n) { 27 for(int i=0; i<n; ++i) //横向 28 if( board[x][i] ) return false; 29 for(int i=0; i<n; ++i) //纵向 30 if( board[i][y] ) return false; 31 int i = x; 32 int j = y; 33 //斜左向上 34 while( i>=0 && j>=0 ) { 35 if( board[i][j] ) return false; 36 --i,--j; 37 } 38 //斜右向下 39 i=x, j=y; 40 while( i<n && j<n ) { 41 if( board[i][j] ) return false; 42 ++i,++j; 43 } 44 //斜右向上 45 i=x, j=y; 46 while( i>=0 && j<n ) { 47 if( board[i][j] ) return false; 48 --i,++j; 49 } 50 //斜左向下 51 i=x, j=y; 52 while( i<n && j>=0 ) { 53 if( board[i][j] ) return false; 54 ++i,--j; 55 } 56 return true; 57 } 58 59 vector<string> board2str() { //将棋盘转为string 60 vector<string> ans; 61 for(int i=0; i<board.size(); ++i) { 62 string str; 63 for(int j=0; j<board[i].size(); ++j) 64 str.push_back( board[i][j] ? ‘Q‘ : ‘.‘ ); 65 ans.push_back(str); 66 } 67 return ans; 68 } 69 70 private: 71 vector< vector<bool> > board; 72 vector< vector<string> > ans; 73 };
N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
改动I中所用的方法,直接获取解的个数。
时间: 2024-10-12 17:50:52