-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathNQueens.java
More file actions
41 lines (34 loc) · 969 Bytes
/
NQueens.java
File metadata and controls
41 lines (34 loc) · 969 Bytes
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
package nqueens;
public class NQueens
{
private static final int N = 4;
private static boolean isInvalid(boolean[][] board, int col, int row)
{
//row and col
for (int i = 0; i < N; i++)
{
if (i != col && board[i][row] || i != row && board[col][i])
{
return true;
}
}
//check diagonals
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
{
if (board[j][i]) { return true; }
}
for (int i = row - 1, j = col + 1; i >= 0 && j < N; i--, j++)
{
if (board[j][i]) { return true; }
}
for (int i = row + 1, j = col - 1; i < N && j >= 0; i++, j--)
{
if (board[j][i]) { return true; }
}
for (int i = row + 1, j = col + 1; i < N && j < N; i++, j++)
{
if (board[j][i]) { return true; }
}
return false;
}
}