-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueens.java
More file actions
63 lines (51 loc) · 1.57 KB
/
NQueens.java
File metadata and controls
63 lines (51 loc) · 1.57 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
import java.util.*;
public class NQueens {
public static void solve(int n) {
char[][] board = new char[n][n];
// Initialize board
for (int i = 0; i < n; i++) {
Arrays.fill(board[i], '.');
}
backtrack(board, 0);
}
private static void backtrack(char[][] board, int row) {
if (row == board.length) {
printBoard(board);
System.out.println();
return;
}
for (int col = 0; col < board.length; col++) {
if (isSafe(board, row, col)) {
board[row][col] = 'Q';
backtrack(board, row + 1);
board[row][col] = '.'; // backtrack
}
}
}
private static boolean isSafe(char[][] board, int row, int col) {
// vertical check
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') return false;
}
// left diagonal
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') return false;
}
// right diagonal
for (int i = row - 1, j = col + 1; i >= 0 && j < board.length; i--, j++) {
if (board[i][j] == 'Q') return false;
}
return true;
}
private static void printBoard(char[][] board) {
for (char[] row : board) {
for (char c : row) {
System.out.print(c + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
solve(4); // Example: 4 queens
}
}