首页 > 代码库 > N-Queens
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.."]]
思路:使用DFS求解即可。在某行放置皇后时,检查所在列、对角线、反对角线是否已经放置了皇后。
1 class Solution { 2 public: 3 vector<vector<string>> solveNQueens( int n ) { 4 vector<string> solution( n, string( n, ‘.‘ ) ); 5 SolveSub( solution, 0, n ); 6 return solutions; 7 } 8 private: 9 void SolveSub( vector<string>& solution, int step, const int &n ) {10 if( step == n ) { solutions.push_back( solution ); return; }11 for( int i = 0; i < n; ++i ) {12 bool used = false;13 for( int k = step-1; k >= 0; --k ) {14 if( solution[k][i] == ‘Q‘ ) { used = true; break; }15 }16 if( used ) { continue; }17 for( int k = 1; k <= min( i, step ); ++k ) {18 if( solution[step-k][i-k] == ‘Q‘ ) { used = true; break; }19 }20 if( used ) { continue; }21 for( int k = 1; k <= min( n-i, step ); ++k ) {22 if( solution[step-k][i+k] == ‘Q‘ ) { used = true; break; }23 }24 if( used ) { continue; }25 solution[step][i] = ‘Q‘;26 SolveSub( solution, step+1, n );27 solution[step][i] = ‘.‘;28 }29 return;30 }31 vector<vector<string>> solutions;32 };
N-Queens
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。