Skip to content

Conversation

@Lakshya182005
Copy link

@Lakshya182005 Lakshya182005 commented Oct 28, 2025

PR Title Format: 52. N-Queens II.cpp

Intuition

Row-by-Row Safe Placement

  • The N-Queens problem is fundamentally a constraint satisfaction problem.
  • Each queen attacks its column, main diagonal, and anti-diagonal.
  • By keeping track of these attacked positions, we can efficiently check if placing a queen is safe.
  • Backtracking allows us to explore all possible configurations row by row.
  • The key insight is that each queen placement depends only on columns and diagonals already occupied, so we don’t need to check the entire board each time.

Approach

Backtracking with Row-by-Row Placement

Initialization

  • Initialize a variable count to 0 to store the number of valid solutions.
  • Create three sets (or arrays) to keep track of attacks:
    1. cols – columns where a queen is already placed.
    2. diag – main diagonals under attack (row + col).
    3. anti_diag – anti-diagonals under attack (row - col).

Iteration (Row-by-Row Backtracking)

  1. Start from the first row (row = 0).
  2. For each column in the current row, check if placing a queen is valid (not in cols, diag, or anti_diag).
  3. If valid:
    • Add the column to cols.
    • Add row + col to diag.
    • Add row - col to anti_diag.
    • Recursively place a queen in the next row.
    • After recursion, backtrack by removing the queen from cols, diag, and anti_diag.
  4. If row == n, all queens are placed safely. Increment count.

Termination
Return the total count of valid N-Queens solutions.

Code Solution (C++)

class Solution {
public:
    int totalNQueens(int n) {
        int count = 0; 

        unordered_set<int> cols;      
        unordered_set<int> diag;      
        unordered_set<int> anti_diag; 

 
        function<void(int)> bckt = [&](int row) {
            if(row == n){ /
                count++;
                return;
            }

            
            for(int col = 0; col < n; col++){
                if(cols.count(col) || diag.count(row + col) || anti_diag.count(row - col))
                    continue; 

           
                cols.insert(col);
                diag.insert(row + col);
                anti_diag.insert(row - col);

                bckt(row + 1); 

       
                cols.erase(col);
                diag.erase(row + col);
                anti_diag.erase(row - col);
            }
        };

        bckt(0);
        return count; 
    }
};
    

Related Issues

Closes #242

By submitting this PR, I confirm that:

  • [ x] This is my original work not totally AI generated
  • [x ] I have tested the solution thoroughly on leetcode
  • [ x] I have maintained proper PR description format
  • [x ] This is a meaningful contribution, not spam

Summary by Sourcery

New Features:

  • Implement Solution::totalNQueens to count all valid N-Queens configurations using recursive backtracking and sets for columns, main diagonals, and anti-diagonals attacks.

@sourcery-ai
Copy link

sourcery-ai bot commented Oct 28, 2025

Reviewer's Guide

Implement N-Queens II solution using backtracking to explore row-by-row placements and track attacked columns and diagonals, supplemented with detailed approach and complexity comments.

Class diagram for the Solution class in N-Queens II

classDiagram
class Solution {
  +int totalNQueens(int n)
}
Solution : -int count
Solution : -unordered_set<int> cols
Solution : -unordered_set<int> diag
Solution : -unordered_set<int> anti_diag
Solution : -void backtrack(int row)
Loading

File-Level Changes

Change Details Files
Implement totalNQueens solution with backtracking
  • Define and manage cols, diag, anti_diag sets
  • Implement recursive backtracking lambda
  • Add safety checks before placing queens
  • Insert and remove set entries for placement and backtracking
  • Handle base case to increment solution count
52. N-Queens II.cpp
Document approach and complexity analysis
  • Add detailed approach description before the code
  • Include time and space complexity comments
52. N-Queens II.cpp

Assessment against linked issues

Issue Objective Addressed Explanation
#242 Provide a working C++ solution for LeetCode Problem 52 (N-Queens II) that counts the number of valid N-Queens arrangements using backtracking.
#242 Include an explanation of the approach and intuition for the solution, describing the use of sets to track attacks and the backtracking process.
#242 Ensure the filename follows the convention '[Number]. [Problem Title].cpp' (i.e., '52. N-Queens II.cpp').

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising the PR, the owner will be review it soon' keep patience, keep contributing>>>!!! make sure you have star ⭐ the repo

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@SjxSubham SjxSubham changed the title N-Queens II 52. N-Queens II Oct 29, 2025
@SjxSubham
Copy link
Owner

@Lakshya182005 Star the repo as well...⭐

@Lakshya182005
Copy link
Author

thank you!
could you please add hacktoberfest accepted to this pull request and merge it.

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

52. N-Queens II

2 participants