Skip to main content

Posts

Leetcode 52: N-Queens II

  1. Problem Statement (Simple Explanation): Same puzzle as N-Queens (problem 51): Place n queens on an n x n chessboard so that no two queens attack each other: Not in the same  row Not in the same  column Not on the same  diagonal But now: Instead of returning all boards, you must return the  number of distinct solutions . 2. Examples: Example 1: Input: n = 4 There are exactly 2 valid configurations (same as problem 51’s example). Output: 2 Example 2: Input: n = 1 Only one way to place a queen on 1x1 board. Output: 1 3. Approach – Backtracking with Column & Diagonal Constraints: This is almost identical to  N-Queens (51) , but we: Don’t need to build the actual board strings. Only need a  counter  of valid placements. We still: Place queens  row by row . Use three boolean arrays to track attacked lines: colUsed[c] – column c is under attack. diag1Used[row - col + n - 1] – main diagonal (...
Recent posts

Leetcode 51: N-Queens

1. Problem Statement (Simple Explanation): You must place n queens on an n x n chessboard such that: No two queens attack each other: Not in the same  row Not in the same  column Not on the same  diagonal You must return  all distinct solutions . Each solution is an n-element array of strings, where: 'Q' is a queen '.' is an empty cell Each string represents one row of the board. 2. Examples: Example 1: Input: n = 4 Output: [   [".Q..","...Q","Q...","..Q."],   ["..Q.","Q...","...Q",".Q.."] ] These represent the two valid 4-queens solutions. Example 2: Input: n = 1 Output: [["Q"]] One queen on a 1x1 board. 3. Approach – Backtracking with Column & Diagonal Constraints: We place queens  row by row : For each row r, we choose a column c where: No queen in the same  column . No queen in the same  diagonal . We track which columns and diagonals are already under attack to ens...