Skip to content

Commit e2c378a

Browse files
authored
Merge pull request #638 from Dipit12/main
feat: added NQueens solution in java
2 parents 5d5452b + 20ffcae commit e2c378a

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package Java.algorithms.matrix;
2+
3+
import java.util.*;
4+
5+
public class NQueens {
6+
static List<List<String>> res = new ArrayList<>();
7+
8+
public static List<List<String>> solveNQueens(int n) {
9+
char[][] board = new char[n][n];
10+
for (char[] row : board) Arrays.fill(row, '.');
11+
solve(board, 0);
12+
return res;
13+
}
14+
15+
static void solve(char[][] board, int row) {
16+
if (row == board.length) {
17+
List<String> temp = new ArrayList<>();
18+
for (char[] r : board) temp.add(new String(r));
19+
res.add(temp);
20+
return;
21+
}
22+
for (int col = 0; col < board.length; col++) {
23+
if (isSafe(board, row, col)) {
24+
board[row][col] = 'Q';
25+
solve(board, row + 1);
26+
board[row][col] = '.';
27+
}
28+
}
29+
}
30+
31+
static boolean isSafe(char[][] board, int row, int col) {
32+
for (int i = 0; i < row; i++)
33+
if (board[i][col] == 'Q') return false;
34+
35+
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
36+
if (board[i][j] == 'Q') return false;
37+
38+
for (int i = row - 1, j = col + 1; i >= 0 && j < board.length; i--, j++)
39+
if (board[i][j] == 'Q') return false;
40+
41+
return true;
42+
}
43+
44+
public static void main(String[] args) {
45+
List<List<String>> solutions = solveNQueens(4);
46+
for (List<String> s : solutions) {
47+
for (String row : s) System.out.println(row);
48+
System.out.println();
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)