-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueens.java
66 lines (56 loc) · 1.87 KB
/
NQueens.java
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
/** The Problem
* The N-Queens puzzle is the problem of placing N queens on an N×N chessboard so that
* no two queens attack each other.
*
* Examples:
* Input: N = 4
* Output: [[1,0,0,0], [0,0,1,0], [0,1,0,0], [0,0,0,1]]
**/
import java.util.*;
public class NQueens {
public static void main(String[] args) {
List<List<String>> result = solveNQueens(4);
for (List<String> solution : result) {
System.out.println(solution);
}
}
public static List<List<String>> solveNQueens(int n) {
List<List<String>> results = new ArrayList<>();
char[][] board = new char[n][n];
for (char[] row : board) Arrays.fill(row, '.');
solve(0, board, results);
return results;
}
private static void solve(int row, char[][] board, List<List<String>> results) {
if (row == board.length) {
results.add(construct(board));
return;
}
for (int col = 0; col < board.length; col++) {
if (isSafe(row, col, board)) {
board[row][col] = 'Q';
solve(row + 1, board, results);
board[row][col] = '.';
}
}
}
private static boolean isSafe(int row, int col, char[][] board) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') return false;
}
for (int i = 1; row - i >= 0 && col - i >= 0; i++) {
if (board[row - i][col - i] == 'Q') return false;
}
for (int i = 1; row - i >= 0 && col + i < board.length; i++) {
if (board[row - i][col + i] == 'Q') return false;
}
return true;
}
private static List<String> construct(char[][] board) {
List<String> result = new ArrayList<>();
for (char[] row : board) {
result.add(new String(row));
}
return result;
}
}