-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueens.java
More file actions
44 lines (41 loc) · 1.39 KB
/
NQueens.java
File metadata and controls
44 lines (41 loc) · 1.39 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
import java.util.Arrays;
// Solution to N Queens problem. Video is on the YouTube channel.
public class NQueens{
static char board[][];
static int n = 15;
static boolean colUsed[];
static int whichCol[]; // whichCol[row]: Which column the queen at row is located in.
public static boolean diagonalFine(int row, int col){
for(int previousRow = 0; previousRow < row; previousRow++){
int previousCol = whichCol[previousRow];
if(Math.abs(previousRow - row) == Math.abs(previousCol - col)) return false;
}
return true;
}
public static void recurse(int row){
if(row == n){
for(char[] rows : board)
System.out.println(Arrays.toString(rows));
System.out.println("-----");
return;
}
for(int col = 0; col < n; col++){
if(colUsed[col] == false && diagonalFine(row, col)){
board[row][col] = 'Q';
colUsed[col] = true;
whichCol[row] = col;
recurse(row + 1);
board[row][col] = '.';
colUsed[col] = false;
}
}
}
public static void main(String[] args) {
board = new char[n][n];
colUsed = new boolean[n];
whichCol = new int[n];
for(char[] row : board)
Arrays.fill(row, '.');
recurse(0);
}
}