forked from 14visheshjain/DataStructure-Algorithm-in-java
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqueen.java
More file actions
63 lines (56 loc) · 1.15 KB
/
queen.java
File metadata and controls
63 lines (56 loc) · 1.15 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
/*
* @author Vishesh Jain
* @date 28-March-2019
*/
package lecture9a10;
import java.util.Scanner;
public class queen {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
int row = a.nextInt();
int col = a.nextInt();
boolean[][] arr = new boolean[row][col];
Nqueen(arr, 0, "");
}
public static void Nqueen(boolean[][] board, int row, String ans) {
if (row == board.length) {
System.out.println(ans);
return;
}
for (int col = 0; col < board[0].length; col++) {
if (isItSafe(board, row, col)) {
board[row][col] = true;
Nqueen(board, row + 1, ans + "{" + row + "-" + col + "}");
board[row][col] = false;
}
}
}
public static boolean isItSafe(boolean[][] board, int row, int col) {
int r = row - 1;
int c = col;
// check vertical
for (; r >= 0; r--) {
if (board[r][c])
return false;
}
r = row - 1;
c=col+1;
// diagonal right
while (r >= 0 && c < board[0].length) {
if (board[r][c])
return false;
r--;
c++;
}
// diagonal left
r=row-1;
c= col-1;
while (r >= 0 && c >= 0) {
if (board[r][c])
return false;
r--;
c--;
}
return true;
}
}