-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathN_Queen problem
71 lines (65 loc) · 1.33 KB
/
N_Queen problem
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
65
66
67
68
69
70
71
import java.util.Scanner;
public class nqueens {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
System.out.println(Nqueens(new boolean[n][n], 0, ""));
output(new boolean[n][n], 0, "");
}
public static int Nqueens(boolean[][] board, int row, String ans) {
int count=0;
if(row==board.length) {
return 1;
}
for(int col=0; col<board[0].length; col++) {
if(isItSafe(board, row, col)) {
board[row][col]=true;
count+=Nqueens(board, row+1, ans+ "{"+row+"-"+col+"} ");
}
board[row][col]=false;
}
return count;
}
public static void output(boolean[][] board, int row, String ans) {
if(row==board.length) {
System.out.print(ans+" ");
return ;
}
for(int col=0; col<board[0].length; col++) {
if(isItSafe(board, row, col)) {
board[row][col]=true;
output(board, row+1, ans+ "{"+(row+1)+"-"+(col+1)+"} ");
}
board[row][col]=false;
}
}
public static boolean isItSafe(boolean[][] board, int row, int col) {
int r=row-1;
int c=col;
while(r>=0) {
if(board[r][c]) {
return false;
}
r--;
}
r=row-1;
c=col-1;
while(r>=0 && c>=0) {
if(board[r][c]) {
return false;
}
r--;
c--;
}
r=row-1;
c=col+1;
while(r>=0 && c<board[0].length) {
if(board[r][c]) {
return false;
}
r--;
c++;
}
return true;
}
}