51. N-Queens
Explanation
The N-Queens problem is a classic backtracking problem where we need to place N queens on an N x N chessboard such that no two queens attack each other. We can solve this problem using a recursive backtracking approach.
Algorithm:
- Initialize an empty result list to store all distinct solutions.
- Create a helper method to recursively explore all possible placements of queens on the board.
- In the helper method, we iterate through each row of the board and try placing a queen in each column of the current row.
- At each position, we check if placing a queen is valid by ensuring it does not attack any other queen diagonally or in the same row.
- If a valid position is found, we place the queen and recursively move on to the next row.
- If all queens are successfully placed (i.e., we reach the end of the board), we add the current board configuration to the result list.
- Backtrack by removing the queen from the current position and continue exploring other possibilities.
- Repeat this process for all rows and columns to find all distinct solutions.
Time Complexity: The time complexity of this approach is O(N!), where N is the size of the board.
Space Complexity: The space complexity is O(N) to store the board configuration and the result list.
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> result = new ArrayList<>();
char[][] board = new char[n][n];
for (char[] row : board) {
Arrays.fill(row, '.');
}
solveNQueensHelper(result, board, 0, n);
return result;
}
private void solveNQueensHelper(List<List<String>> result, char[][] board, int row, int n) {
if (row == n) {
List<String> solution = new ArrayList<>();
for (char[] r : board) {
solution.add(String.valueOf(r));
}
result.add(solution);
return;
}
for (int col = 0; col < n; col++) {
if (isValid(board, row, col, n)) {
board[row][col] = 'Q';
solveNQueensHelper(result, board, row + 1, n);
board[row][col] = '.';
}
}
}
private boolean isValid(char[][] board, int row, int col, int n) {
for (int i = 0; i < row; i++) {
if (board[i][col] == 'Q') return false;
int colDiff = Math.abs(col - i);
if (board[i][col - colDiff] == 'Q' || board[i][col + colDiff] == 'Q') return false;
}
return true;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.