|
| 1 | +class Solution { |
| 2 | + public List<List<String>> solveNQueens(int n) { |
| 3 | + List<List<String>> ans = new ArrayList<List<String>>(); |
| 4 | + boolean[][] board = new boolean[n][n]; |
| 5 | + queens(board, 0, ans); |
| 6 | + return ans; |
| 7 | + |
| 8 | + } |
| 9 | + |
| 10 | + public void queens(boolean[][] board, int row , List<List<String>> ans2) { |
| 11 | + //base case |
| 12 | + if (row == board.length) { |
| 13 | + ArrayList<String> ans = new ArrayList<String>(); |
| 14 | + createAnswer(board, ans); |
| 15 | + ans2.add(ans); |
| 16 | + return; |
| 17 | + } |
| 18 | + for (int col = 0; col<board.length; col++) { |
| 19 | + if (isSafe(board,row, col)) { |
| 20 | + board[row][col] = true; |
| 21 | + queens(board, row+1, ans2); |
| 22 | + board[row][col] = false; |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public void createAnswer(boolean[][] board, ArrayList<String> ans) { |
| 28 | + for (int i = 0; i<board.length; i++) { |
| 29 | + StringBuilder str = new StringBuilder(); |
| 30 | + for (int j = 0; j<board[0].length; j++) { |
| 31 | + if (board[i][j]) { |
| 32 | + str.append("Q"); |
| 33 | + } else str.append("."); |
| 34 | + } |
| 35 | + ans.add(str.toString()); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public boolean isSafe(boolean[][] board, int row, int col) { |
| 40 | + for (int i = 0; i<row; i++) { |
| 41 | + if (board[i][col]) { |
| 42 | + return false; |
| 43 | + } |
| 44 | + } |
| 45 | + int maxLeft = Math.min(row,col); |
| 46 | + for (int i = 1; i<=maxLeft; i++) { |
| 47 | + if (board[row-i][col-i]) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + } |
| 51 | + int maxRight = Math.min(row,board.length-1-col); |
| 52 | + for (int i = 1; i<=maxRight; i++) { |
| 53 | + if (board[row-i][col+i]) return false; |
| 54 | + } |
| 55 | + return true; |
| 56 | + } |
| 57 | +} |
0 commit comments