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 {PRIVATE: STD: vector <STD: String> res; public: STD: vector <STD :: string> solvenqueens (int n) {STD: vector <STD: String> cur (n, STD: string (n ,'. '); DFS (cur, 0); Return res;} void DFS (STD: vector <STD: String> & cur, int row) {If (ROW = cur. size () {res. push_back (cur); return;} For (INT Col = 0; Col <cur. size (); Col ++) if (isvalid (cur, row, col) {cur [row] [Col] = 'q'; DFS (cur, row + 1); cur [row] [col] = '. ';}} // determines whether the Queen is placed in the cur [row] [col] location. Bool isvalid (STD: vector <STD: String> & cur, int row, int col) {// column for (INT I = 0; I <row; I ++) if (cur [I] [col] = 'q') return false; // right diagonal line for (INT I = row-1, j = col-1; I >=0 & J> = 0; I --, j --) if (cur [I] [J] = 'q ') return false; // left diagonal line for (INT I = row-1, j = Col + 1; I >=0 & J <cur. size (); I --, J ++) if (cur [I] [J] = 'q') return false; return true ;}};
Leetcode-n-queens