N-Queens - Complete Solution Guide
N-Queens is LeetCode problem 51, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n , return all distinct solutions to the n-queens puzzle . You may return the answer in any order . Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. Example 1: Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation:
Detailed Explanation
The N-Queens puzzle asks us to place 'n' queens on an 'n x n' chessboard such that no two queens threaten each other. This means no two queens can be in the same row, column, or diagonal. The goal is to find all distinct arrangements (solutions) of placing the queens on the board. The input is a single integer 'n' representing the size of the board. The output is a list of lists of strings, where each inner list represents a solution. Each string in the inner list represents a row of the chessboard, with 'Q' denoting a queen and '.' denoting an empty space. The constraint is that 'n' will be between 1 and 9.
Solution Approach
The provided code utilizes a backtracking algorithm to systematically explore all possible queen placements. It maintains sets to track columns, positive diagonals, and negative diagonals that are already occupied by queens. The algorithm recursively attempts to place a queen in each column of each row. If a placement is valid (doesn't conflict with existing queens), it adds the queen to the board and recursively calls itself for the next row. If the current row is the last row, a valid solution has been found and added to the results. After exploring a branch of placements, the algorithm 'backtracks' by removing the queen from the current position to explore other possibilities.
Step-by-Step Algorithm
- Step 1: Initialize an empty board (list of lists of strings) filled with '.' representing empty spaces.
- Step 2: Initialize three sets: 'cols', 'pos_diagonals', and 'neg_diagonals' to track occupied columns and diagonals.
- Step 3: Define a recursive 'backtrack' function that takes the current row 'r' as input.
- Step 4: Base Case: If 'r' equals 'n', it means all 'n' queens have been placed successfully. Convert the current board configuration to a list of strings and append it to the 'results' list.
- Step 5: Iterate through each column 'c' in the current row 'r'.
- Step 6: Check if placing a queen at board[r][c] is valid. This is done by checking if 'c' is in 'cols', 'r - c' is in 'pos_diagonals', or 'r + c' is in 'neg_diagonals'. If any of these conditions are true, the placement is invalid, and we continue to the next column.
- Step 7: If the placement is valid, add 'c' to 'cols', 'r - c' to 'pos_diagonals', and 'r + c' to 'neg_diagonals'. Also, place a queen 'Q' at board[r][c].
- Step 8: Recursively call 'backtrack(r + 1)' to attempt to place a queen in the next row.
- Step 9: After the recursive call returns, 'backtrack'. This means remove 'c' from 'cols', 'r - c' from 'pos_diagonals', and 'r + c' from 'neg_diagonals'. Also, remove the queen 'Q' from board[r][c] by setting it back to '.'. This allows exploring other possible placements in the current row.
- Step 10: Start the backtracking process by calling 'backtrack(0)' to place the first queen in row 0.
- Step 11: Return the 'results' list, which contains all valid N-Queens solutions.
Key Insights
- Insight 1: Backtracking is the most suitable approach as it explores different placement possibilities systematically and abandons branches that lead to invalid solutions.
- Insight 2: Using sets to track occupied columns and diagonals allows for efficient checking of whether a placement is valid (O(1) lookup).
- Insight 3: The two types of diagonals can be represented by r - c (positive slope) and r + c (negative slope), which simplifies conflict detection.
Complexity Analysis
Time Complexity: O(N!)
Space Complexity: O(N^2)
Topics
This problem involves: Array, Backtracking.
Companies
Asked at: Adobe, Amazon, Apple, Bloomberg, Citadel, Goldman Sachs, IBM, Meta, Microsoft, Salesforce, Samsung, Snowflake, TikTok, Uber, Yahoo, Zoho.