The n-queens Puzzle is the problem of placing N Queens on a nxn chessboard such that No, Queens attack.
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 Indi Cate a queen and an empty space respectively.
For example,
There exist-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::vector<std::string> > RES;PUBLIC:STD::VECTOR<STD::VECTOR&L t;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)) {CU R[row][col] = ' Q '; DFS (cur, row+1); Cur[row][col] = '. '; }}//inferred Cur[row][col] position to place the Queen. is legal. 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 for (int i = row-1, j=col-1; I >= 0 && J >= 0; I--, j--) if (cur[i][j] = = ' Q ') return FAlse; Left diagonal for (int i = row-1, j=col+1; I >= 0 && J < cur.size (); I--, j + +) if (cur[i][j] = = ' Q ') return false; return true; }};
Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.
Leetcode-n-queens