N Queens Problem Program Explanation
N Queens Problem Program Explanation
Explanation
N-Queens Problem
Imagine you have a chessboard of size `n x n`. Your task is to place `n` queens on this board
such that no two queens can attack each other. In chess, a queen can move any number of
squares:
- Vertically (up and down)
- Horizontally (left and right)
- Diagonally
If two queens are in the same row, column, or diagonal, they can attack each other. Our goal
is to place the queens in a way that none of them can attack the others.
```java
char[][] board = new char[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
board[i][j] = '.';
```
If all columns have queens placed safely, this is a valid solution, and the board configuration
is saved.
```java
void dfs(int col, char[][] board, List<List<String>> res) {
if (col == board.length) {
res.add(construct(board));
return;
}
```java
boolean validate(char[][] board, int row, int col) {
int duprow = row;
int dupcol = col;
row = duprow;
col = dupcol;
row = duprow;
col = dupcol;
return true;
}
```
```java
List<String> construct(char[][] board) {
List<String> res = new LinkedList<String>();
for (int i = 0; i < board.length; i++) {
String s = new String(board[i]);
res.add(s);
}
return res;
}
```
```java
public static void main(String args[]) {
int N = 4;
List<List<String>> queen = solveNQueens(N);
int i = 1;
for (List<String> it: queen) {
System.out.println("Arrangement " + i);
for (String s: it) {
System.out.println(s);
}
System.out.println();
i += 1;
}
}
```
Step 2: Place a queen in the first column (Column 0) in the first row:
Q...
....
....
....
Step 3: Move to the next column (Column 1) and try to place another queen.
The only safe place is row 2.
Q...
....
.Q..
....
Conclusion
The N-Queens problem is solved by systematically trying different arrangements on the
board, backtracking when a conflict is found, and saving valid configurations. The Java
program handles this using simple loops, condition checks, and recursion.