|
| 1 | +class Solution { |
| 2 | + List<List<String>> result; |
| 3 | + public List<List<String>> solveNQueens(int n) { |
| 4 | + result = new ArrayList<>(); |
| 5 | + //Take a board. .Q |
| 6 | + char[][] board = new char[n][n]; |
| 7 | + for(int i =0; i < n; i++) { |
| 8 | + for(int j = 0; j < n; j++) { |
| 9 | + board[i][j] = '.'; |
| 10 | + } |
| 11 | + } |
| 12 | + List<int[]> queenPos = new ArrayList<>(); |
| 13 | + dfs(board, 0, queenPos); |
| 14 | + return result; |
| 15 | + } |
| 16 | + |
| 17 | + private void dfs(char[][] board, int row, List<int[]> queenPos) { |
| 18 | + //Chaeck if we have placed all the queens |
| 19 | + if(queenPos.size() == board.length) { |
| 20 | + //Construct the result |
| 21 | + List<String> rowData = new ArrayList<>(); |
| 22 | + for(char[] c : board){ |
| 23 | + rowData.add(new String(c)); |
| 24 | + } |
| 25 | + result.add(rowData); |
| 26 | + } |
| 27 | + |
| 28 | + //Try adduing Queen at row, col |
| 29 | + for(int col = 0; col < board.length; col++) { |
| 30 | + if(canAddQueen(queenPos, row, col)) { |
| 31 | + board[row][col] = 'Q'; |
| 32 | + queenPos.add(new int[]{row, col}); |
| 33 | + dfs(board, row+1, queenPos); |
| 34 | + board[row][col] = '.'; |
| 35 | + queenPos.remove(queenPos.size()-1); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private boolean canAddQueen(List<int[]> queenPos, int row, int col) { |
| 41 | + for(int[] pair : queenPos) { |
| 42 | + int dx = Math.abs(pair[0]- row); |
| 43 | + int dy = Math.abs(pair[1]- col); |
| 44 | + if(dx==0 || dy == 0 || dx == dy) return false; |
| 45 | + } |
| 46 | + return true; |
| 47 | + } |
| 48 | +} |
0 commit comments