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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
classSolution {publicList<List<String>> solveNQueens(int n) {List<List<String>> ans =newArrayList<>();backTrack(n, ans,newArrayList<String>(),0);return ans; }publicvoidbackTrack(int n,List<List<String>> ans,ArrayList<String> temp,int row) {if (row == n) {ans.add(newArrayList<>(temp));return; }StringBuilder str =newStringBuilder();for (int i =0; i < n; i++)str.append(".");for (int i =0; i < n; i++) {if (isPossible(temp, row, i, n)) {str.setCharAt(i,'Q');temp.add(str.toString());backTrack(n, ans, temp, row +1);str.setCharAt(i,'.');temp.remove(temp.size() -1); } } }publicbooleanisPossible(ArrayList<String> temp,int row,int col,int n) {for (int i =0; i < row; i++) {if (temp.get(i).charAt(col) =='Q')returnfalse;int colValue1 = col - (row - i), colValue2 = col + (row - i);//checking diagonalsif (colValue1 >=0&& colValue1 < n &&temp.get(i).charAt(colValue1) =='Q')returnfalse;if (colValue2 >=0&& colValue2 < n &&temp.get(i).charAt(colValue2) =='Q')returnfalse; }returntrue; }}