LeetCode 51: N-Queens Solution

Master LeetCode problem 51 (N-Queens), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

51. N-Queens

Problem Explanation

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:

  1. Initialize an empty result list to store all distinct solutions.
  2. Create a helper method to recursively explore all possible placements of queens on the board.
  3. In the helper method, we iterate through each row of the board and try placing a queen in each column of the current row.
  4. 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.
  5. If a valid position is found, we place the queen and recursively move on to the next row.
  6. 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.
  7. Backtrack by removing the queen from the current position and continue exploring other possibilities.
  8. 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.

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 51 (N-Queens)?

This page provides optimized solutions for LeetCode problem 51 (N-Queens) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 51 (N-Queens)?

The time complexity for LeetCode 51 (N-Queens) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 51 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 51 in Java, C++, or Python.

Back to LeetCode Solutions