forked from codehouseindia/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen
More file actions
64 lines (59 loc) · 1.69 KB
/
NQueen
File metadata and controls
64 lines (59 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package Arrayss;
import java.util.Scanner;
public class NQueens {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[][] board = new int[n][n];
NQueens(board,0);
}
private static void NQueens(int[][] board, int row) {
if(row==board.length){
printb(board);
return;
}
for (int col = 0; col <board.length ; col++) {
if(isSafePlace(board,row,col)==true) {
board[row][col] = 1;
NQueens(board, row + 1);
board[row][col] = 0;
}
}
}
// printing the board
private static void printb(int[][] board) {
for (int i = 0; i <board.length ; i++) {
for (int j = 0; j <board.length ; j++) {
if(board[i][j]==1){
System.out.print("Q ");
}
else{
System.out.print("X ");
}
}
System.out.println();
}
System.out.println();
}
private static boolean isSafePlace(int[][] board, int row, int col) {
// checking vertically
for(int i = row-1,j=col; i>=0;i--){
if(board[i][j]==1){
return false;
}
}
// checking left diagonal
for(int i=row-1, j=col-1;i>=0&&j>=0;i--,j--){
if(board[i][j]==1){
return false;
}
}
// checking right diagonal
for(int i=row-1,j=col+1;i>=0&&j<board.length;i--,j++){
if(board[i][j]==1){
return false;
}
}
return true;
}
}