-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathNqueen.java
30 lines (25 loc) · 907 Bytes
/
Nqueen.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
import java.util.ArrayList;
import java.util.List;
// redad
public class NQueens {
// Function to solve the N-Queens problem
public static List<List<String>> solveNQueens(int n) {
List<List<String>> solutions = new ArrayList<>();
char[][] board = new char[n][n];
// Initialize the board with '.'
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = '.';
}
}
solve(0, board, solutions);
return solutions;
}
// Recursive function to place queens
private static void solve(int row, char[][] board, List<List<String>> solutions) {
if (row == board.length) {
// Convert the board to a list of strings and add to solutions
solutions.add(construct(board));
return;
}
for (int col = 0; col < board.length; col++)