|
| 1 | +classSolution { |
| 2 | +publicList<List<String>>solveNQueens(intn) { |
| 3 | +List<List<String>>ans =newArrayList<List<String>>(); |
| 4 | +boolean[][]board =newboolean[n][n]; |
| 5 | +queens(board,0,ans); |
| 6 | +returnans; |
| 7 | + |
| 8 | + } |
| 9 | + |
| 10 | +publicvoidqueens(boolean[][]board,introw ,List<List<String>>ans2) { |
| 11 | +//base case |
| 12 | +if (row ==board.length) { |
| 13 | +ArrayList<String>ans =newArrayList<String>(); |
| 14 | +createAnswer(board,ans); |
| 15 | +ans2.add(ans); |
| 16 | +return; |
| 17 | + } |
| 18 | +for (intcol =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 | +publicvoidcreateAnswer(boolean[][]board,ArrayList<String>ans) { |
| 28 | +for (inti =0;i<board.length;i++) { |
| 29 | +StringBuilderstr =newStringBuilder(); |
| 30 | +for (intj =0;j<board[0].length;j++) { |
| 31 | +if (board[i][j]) { |
| 32 | +str.append("Q"); |
| 33 | + }elsestr.append("."); |
| 34 | + } |
| 35 | +ans.add(str.toString()); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | +publicbooleanisSafe(boolean[][]board,introw,intcol) { |
| 40 | +for (inti =0;i<row;i++) { |
| 41 | +if (board[i][col]) { |
| 42 | +returnfalse; |
| 43 | + } |
| 44 | + } |
| 45 | +intmaxLeft =Math.min(row,col); |
| 46 | +for (inti =1;i<=maxLeft;i++) { |
| 47 | +if (board[row-i][col-i]) { |
| 48 | +returnfalse; |
| 49 | + } |
| 50 | + } |
| 51 | +intmaxRight =Math.min(row,board.length-1-col); |
| 52 | +for (inti =1;i<=maxRight;i++) { |
| 53 | +if (board[row-i][col+i])returnfalse; |
| 54 | + } |
| 55 | +returntrue; |
| 56 | + } |
| 57 | +} |