|
| 1 | +public class Solution { |
| 2 | + |
| 3 | + |
| 4 | +public static void placeNQueens(int n){ |
| 5 | + |
| 6 | + /* Your class should be named Solution. |
| 7 | + * Don't write main() function. |
| 8 | + * Don't read input, it is passed as function argument. |
| 9 | + * Print output as specified in the question |
| 10 | + */ |
| 11 | + int[][] board = new int[n][n]; |
| 12 | + solveNQueens(board, 0,n); |
| 13 | + |
| 14 | + } |
| 15 | + |
| 16 | + static void solveNQueens(int board[][], int row, int N) |
| 17 | + { |
| 18 | + /* base case: If all queens are placed |
| 19 | + then return true */ |
| 20 | + if (row == N) |
| 21 | + { |
| 22 | + printSolution(board,N); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + /* Consider this column and try placing |
| 27 | + this queen in all rows one by one */ |
| 28 | + for (int i = 0; i < N; i++) |
| 29 | + { |
| 30 | + /* Check if queen can be placed on |
| 31 | + board[row][i] */ |
| 32 | + if ( isSafe(board, row, i, N) ) |
| 33 | + { |
| 34 | + /* Place this queen in board[row][i] */ |
| 35 | + board[row][i] = 1; |
| 36 | + |
| 37 | + // Make result true if any placement |
| 38 | + // is possible |
| 39 | + solveNQueens(board, row + 1, N); |
| 40 | + |
| 41 | + /* If placing queen in board[row][i] |
| 42 | + doesn't lead to a solution, then backtrack and |
| 43 | + remove queen from board[row][i] */ |
| 44 | + board[row][i] = 0; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + } |
| 49 | + |
| 50 | + static boolean isSafe(int board[][], int row, int col, int N) |
| 51 | + { |
| 52 | + int i, j; |
| 53 | + |
| 54 | + //Check if all values in the given column and rows from 0 to row-1 are 0 |
| 55 | + for (i=0;i<row;i++) |
| 56 | + { |
| 57 | + if (board[i][col]==1) |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + // Check upper diagonal on left side |
| 62 | + for (i = row, j = col; i >= 0 && j >= 0; i--, j--) |
| 63 | + if (board[i][j] == 1) |
| 64 | + return false; |
| 65 | + |
| 66 | + //Check upper right diagonal |
| 67 | + for (i=row,j=col;i>=0 && j<N;i--,j++) |
| 68 | + if (board[i][j] == 1) |
| 69 | + return false; |
| 70 | + |
| 71 | + return true; |
| 72 | + } |
| 73 | + |
| 74 | + static void printSolution(int board[][], int N) |
| 75 | + { |
| 76 | + for (int i = 0; i < N; i++) |
| 77 | + { |
| 78 | + for (int j = 0; j < N; j++) |
| 79 | + System.out.print(board[i][j]+" "); |
| 80 | + } |
| 81 | + System.out.println(); |
| 82 | + } |
| 83 | +} |
0 commit comments