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.."] ]
Solution
publicclassSolution {publicList<List<String>> solveNQueens(int n) {List<List<Integer>> result =newArrayList<>();solve(newArrayList<>(), n, result);List<List<String>> finalResult =result.stream().map(item ->draw(item, n)).collect(Collectors.toList());return finalResult; }privateList<String> draw(List<Integer> one,int n) {List<String> result =newArrayList<>();for(Integer i: one) {StringBuffer sb =newStringBuffer();for(int x =0; x < n; x ++) {if (i == x) {sb.append("Q"); } else {sb.append("."); } }result.add(sb.toString()); }return result; }privatevoidsolve(List<Integer> columns,int n,List<List<Integer>> result) {if (columns.size() == n) {result.add(newArrayList<>(columns));return; }for(int i =0; i < n; i ++) {if (checkValid(columns, i)) {columns.add(i);solve(columns, n, result);columns.remove(columns.size()-1); } } }privatebooleancheckValid(List<Integer> columns,int nextColumn) {int currentRow =columns.size();for(int i =0; i <columns.size(); i ++) {if (columns.get(i) == nextColumn) {returnfalse; }int left =Math.abs(currentRow - i);int right =Math.abs(nextColumn -columns.get(i));if (left == right) {returnfalse; } }returntrue; }}