logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
25. Reverse Nodes in k-Group26. Remove Duplicates from Sorted Array27. Remove Element42. Trapping Rain Water51. N-Queens55. Jump Game80. Remove Duplicates from Sorted Array II88. Merge Sorted Array121. Best Time to Buy and Sell Stock122. Best Time to Buy and Sell Stock II189. Rotate Array274. H-Index
Code Scratch/leetcode/hard

51. N-Queens

2 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

We need to place n queens such that none of them attack each other. A queen can attack any other queen in the same row, column, or diagonal. We solve this using backtracking — trying all possible placements row-by-row and undoing invalid ones. If we reach the last row with valid placements, we record the solution.

# Complexity

Space ComplexityTime Complexity
O(N2)\text{O}(N^2)O(N2)O(N!)\text{O}(N!)O(N!)

# Code

List&lt;List&lt;String&gt;&gt; allValidArrangements = new LinkedList<>();
 
// Check if a queen can be placed at (row, col)
public boolean isSafe(boolean[][] board, int row, int col, int n) {
    // Check the column
    for (int i = 0; i &lt; n; ++i) {
        if (board[i][col]) return false;
    }
 
    // Check top-left diagonal
    for (int i = col - 1, j = row - 1; i &gt;= 0 && j >= 0; --i, --j) {
        if (board[j][i]) return false;
    }
 
    // Check bottom-right diagonal
    for (int i = col + 1, j = row + 1; i &lt; n && j &lt; n; ++i, ++j) {
        if (board[j][i]) return false;
    }
 
    // Check top-right diagonal
    for (int i = col + 1, j = row - 1; i < n && j &gt;= 0; ++i, --j) {
        if (board[j][i]) return false;
    }
 
    // Check bottom-left diagonal
    for (int i = col - 1, j = row + 1; i &gt;= 0 && j &lt; n; --i, ++j) {
        if (board[j][i]) return false;
    }
 
    return true;
}
 
// Backtracking function to place queens row-by-row
public void solveQueens(boolean[][] board, int currentRow, int n) {
    // All queens placed successfully
    if (currentRow == n) {
        List&lt;String&gt; currentBoard = new ArrayList<&gt;();
        for (int i = 0; i &lt; n; ++i) {
            StringBuilder rowRepresentation = new StringBuilder();
            for (int j = 0; j &lt; n; ++j) {
                rowRepresentation.append(board[i][j] ? "Q" : ".");
            }
            currentBoard.add(rowRepresentation.toString());
        }
        allValidArrangements.add(currentBoard);
        return;
    }
 
    // Try placing a queen in each column of the current row
    for (int col = 0; col < n; ++col) {
        if (isSafe(board, currentRow, col, n)) {
            board[currentRow][col] = true;
            solveQueens(board, currentRow + 1, n);
            board[currentRow][col] = false; // Backtrack
        }
    }
}
 
// Entry function
public List<List<String&gt;&gt; solveNQueens(int n) {
    boolean[][] board = new boolean[n][n];
    solveQueens(board, 0, n);
    return allValidArrangements;
}
 
←Previous42. Trapping Rain WaterNext→55. Jump Game

On this page

IntuitionComplexityCode