首页 > 代码库 > 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