Explanation of N-Queens Problem:
The N-Queens Problem is a classic and well-known algorithmic challenge that involves placing N queens on an N x N chessboard in such a way that no two queens attack each other. In chess, a queen can move horizontally, vertically, or diagonally, and the objective is to find all distinct arrangements of queens on the board where no two queens share the same row, column, or diagonal.
Step-by-Step Approach:
- We are given the value N, which represents the size of the chessboard and the number of queens to be placed.
- The goal is to find all valid placements of N queens on the N x N chessboard.
- To solve this problem, we use a backtracking algorithm, which systematically explores all possible configurations of queens and prunes the search space when we detect that a solution is not possible.
- We start by placing the first queen in the first row of the chessboard, at column 0.
- Then, we try to place the next queen in the second row at a valid column position where it does not attack the previously placed queen(s).
- We repeat this process, placing queens in subsequent rows, and backtrack when there is no valid position for the current queen.
- The backtracking algorithm allows us to explore different possibilities while avoiding duplicate configurations and unnecessary computations.
- We continue this process until we have placed N queens, and whenever we reach a valid solution, we add it to the list of solutions.
- After exploring all possible configurations, the list of solutions will contain all the distinct arrangements of N queens on the chessboard, where no two queens attack each other.
Java Solution:
import java.util.ArrayList;
import java.util.List;
public class NQueens {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
char[][] board = new char[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = '.';
}
}
backtrack(result, board, 0);
return result;
}
private void backtrack(List<List<String>> result, char[][] board, int row) {
if (row == board.length) {
result.add(constructSolution(board));
return;
}
for (int col = 0; col < board.length; col++) {
if (isValidPlacement(board, row, col)) {
board[row][col] = 'Q';
backtrack(result, board, row + 1);
board[row][col] = '.';
}
}
}
private boolean isValidPlacement(char[][] board, int row, int col) {
int n = board.length;
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') {
return false;
}
if (col - (row - i) >= 0 && board[i][col - (row - i)] == 'Q') {
return false;
}
if (col + (row - i) < n && board[i][col + (row - i)] == 'Q') {
return false;
}
}
return true;
}
private List<String> constructSolution(char[][] board) {
List<String> solution = new ArrayList<>();
for (char[] row : board) {
solution.add(new String(row));
}
return solution;
}
public static void main(String[] args) {
int n = 4;
NQueens nQueens = new NQueens();
List<List<String>> solutions = nQueens.solveNQueens(n);
for (List<String> solution : solutions) {
for (String row : solution) {
System.out.println(row);
}
System.out.println();
}
}
}
Python Solution:
class NQueens:
def solveNQueens(self, n: int) -> List[List[str]]:
result = []
board = [['.' for _ in range(n)] for _ in range(n)]
self.backtrack(result, board, 0)
return result
def backtrack(self, result, board, row):
if row == len(board):
result.append([''.join(row) for row in board])
return
for col in range(len(board)):
if self.is_valid_placement(board, row, col):
board[row][col] = 'Q'
self.backtrack(result, board, row + 1)
board[row][col] = '.'
def is_valid_placement(self, board, row, col):
n = len(board)
for i in range(row):
if board[i][col] == 'Q':
return False
if col - (row - i) >= 0 and board[i][col - (row - i)] == 'Q':
return False
if col + (row - i) < n and board[i][col + (row - i)] == 'Q':
return False
return True
if __name__ == "__main__":
n = 4
n_queens = NQueens()
solutions = n_queens.solveNQueens(n)
for solution in solutions:
for row in solution:
print(row)
print()
Explanation of Java/Python Solution:
The Java and Python solutions use a backtracking algorithm to find all distinct arrangements of N queens on an N x N chessboard.
The solveNQueens method in Java and Python takes the value n as input and returns a list of lists containing all the solutions to the N-Queens problem. Each inner list represents a valid arrangement of queens on the chessboard.
The backtrack method is the heart of the backtracking algorithm. It explores different possibilities of placing queens on the chessboard while ensuring that no two queens attack each other. The algorithm prunes the search space whenever an invalid placement is encountered, which greatly improves efficiency.
The isValidPlacement method checks whether it is safe to place a queen at a specific row and column on the chessboard, considering the previously placed queens’ positions.
The provided example with n = 4 demonstrates how the backtracking algorithm finds the distinct solutions to the N-Queens problem for an N x N chessboard. Each solution is represented by placing ‘Q’ characters in different rows and columns of the chessboard.