-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnQueens.java
More file actions
54 lines (50 loc) · 1.61 KB
/
nQueens.java
File metadata and controls
54 lines (50 loc) · 1.61 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
import java.util.Scanner;
public class nQueens {
public static boolean isSafe(int board[][], int row, int column, int n) {
int i, j;
for (i = 0; i < row; i++) {
if (board[i][column] == 1)
return false;
}
for (i = row, j = column; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 1)
return false;
}
for (i = row, j = column; j < n && i >= 0; i--, j++) {
if (board[i][j] == 1)
return false;
}
return true;
}
public static void nQueen(int[][] board, int r, int n) {
if (r == board.length) {
for (int j = 0; j < board.length; j++) {
for (int i = 0; i < board.length; i++) {
System.out.print(board[j][i] + " ");
}
System.out.println();
}
System.out
.println(
"-------------------------------------------------------------------------------------------");
return;
}
for (int i = 0; i < n; i++) {
if (isSafe(board, r, i, n)) {
board[r][i] = 1;
nQueen(board, r + 1, n);
board[r][i] = 0;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int board[][] = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
board[i][j] = 0;
nQueen(board, 0, n);
sc.close();
}
}