|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class NQueen { |
| 4 | + final int N; |
| 5 | + |
| 6 | + public NQueen(int N) { |
| 7 | + this.N = N; |
| 8 | + } |
| 9 | + |
| 10 | + /* This is the function to print the solution for the problem*/ |
| 11 | + void printSolution(int board[][]) { |
| 12 | + for (int i = 0; i < N; i++) { |
| 13 | + for (int j = 0; j < N; j++) { |
| 14 | + System.out.print(board[i][j] == 1 ? "Q " : ". "); |
| 15 | + } |
| 16 | + System.out.println(); |
| 17 | + } |
| 18 | + System.out.println(); |
| 19 | + } |
| 20 | + |
| 21 | + /*It checks if a queen can be placed on board[row][col] */ |
| 22 | + boolean isSafe(int board[][], int row, int col) { |
| 23 | + // Check this row on left side |
| 24 | + for (int i = 0; i < col; i++) { |
| 25 | + if (board[row][i] == 1) { |
| 26 | + return false; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + // It checks upper diagonal on left side |
| 31 | + for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) { |
| 32 | + if (board[i][j] == 1) { |
| 33 | + return false; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + //It checks lower diagonal on left side |
| 38 | + for (int i = row, j = col; j >= 0 && i < N; i++, j--) { |
| 39 | + if (board[i][j] == 1) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + /*It is used to solve the N-Queen problem using backtracking */ |
| 48 | + boolean solveNQUtil(int board[][], int col) { |
| 49 | + if (col >= N) { |
| 50 | + printSolution(board); |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + boolean res = false; |
| 55 | + for (int i = 0; i < N; i++) { |
| 56 | + if (isSafe(board, i, col)) { |
| 57 | + board[i][col] = 1; |
| 58 | + |
| 59 | + //It is recursively placing rest of the queens |
| 60 | + res = solveNQUtil(board, col + 1) || res; |
| 61 | + |
| 62 | + //It is used for backtracking and removing queen |
| 63 | + board[i][col] = 0; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return res; |
| 68 | + } |
| 69 | + |
| 70 | + /* This function will solve the N-Queen problem and prints all solutions */ |
| 71 | + void solveNQ() { |
| 72 | + int board[][] = new int[N][N]; |
| 73 | + |
| 74 | + if (!solveNQUtil(board, 0)) { |
| 75 | + System.out.println("Solution does not exist"); |
| 76 | + } |
| 77 | + } |
| 78 | + public static void main(String[] args) { |
| 79 | + Scanner sc=new Scanner(System.in); |
| 80 | + System.out.println("Enter the value of N"); |
| 81 | + int N = sc.nextInt(); //Here the input is taken from the user |
| 82 | + NQueen Queen = new NQueen(N); |
| 83 | + Queen.solveNQ(); |
| 84 | + } |
| 85 | +} |
0 commit comments