Leetcode Note: N-Queens
I. Description
The n-queens puzzle is the problem of placing n queens on an nn 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. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Placement = "brush: java;"> [[.Q.., // Solution 1 ...Q, Q..., ..Q.],[..Q., // Solution 2 Q..., ...Q, .Q..]]
Ii. Question Analysis
The famous question about Queen N isn×nIn the checker, each row is placed with a pawn, so that the column where the pawn is located and there are no other pawns on the two slashes. Print all possibilities.
Use Deep SearchdfsTraverse, consider all possibilities,rowMarking each row with the corresponding underlying element of the pawn,colRecord whether the current column has a pawn. The diagonal judgment is whether the difference between two rows is the same as that of the column.
WhendfsDeep reachnIt means that the minimum layer can be traversed and a solution that meets the conditions exists. The information of the elements in the matrix is converted'.'Or'Q'And save it to the result.
Iii. Sample Code
// Source: http://blog.csdn.net/havenoidea/article/details/12167399#include
# Include
Using namespace std; class Solution {public: vector
> SolveNQueens (int n) {this-> row = vector
(N, 0); // The row information this-> col = vector
(N, 0); // column information dfs (0, n, result); // Deep Search return result;} private: vector
> Result; // stores the printed result vector.
Row; // record which subscript of each row is Q vector
Col; // record whether each column has Q void dfs (int r, int n, vector
> & Result) // traverses row r, and there are n rows in total on the board {if (r = n) // You can traverse to the bottom of the board and fill in the result {vector
Temp; for (int I = 0; I <n; ++ I) {string s (n ,'. '); // each line is initialized '.'s [row [I] = 'q'; // The element marked as 1 in each row is marked as Q temp. push_back (s);} result. push_back (temp);} int I, j; for (I = 0; I <n; ++ I) {if (col [I] = 0) {for (j = 0; j <r; ++ j) if (abs (r-j) = abs (row [j]-I) break; if (j = r) {col [I] = 1; // mark column I, where Q row [j] = I already exists; // Add the I element of Row j to Q dfs (r + 1, n, result); // traverse the column r + 1 col [I] = 0; row [j] = 0 ;}}}}};
Iv. Summary
N-Queens II is much simpler than this question in the future, because only the number of solutions is required to be output and the specific conditions of all solutions are not required.