N Queens Problem in DSA C - Time & Space Complexity
We want to understand how the time needed to solve the N Queens problem grows as the board size increases.
Specifically, how does the number of steps change when we try to place queens on larger boards?
Analyze the time complexity of the following code snippet.
bool isSafe(int board[][N], int row, int col) {
for (int i = 0; i < col; i++)
if (board[row][i])
return false;
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (int i = row, j = col; i < N && j >= 0; i++, j--)
if (board[i][j])
return false;
return true;
}
bool solveNQUtil(int board[][N], int col) {
if (col >= N) return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true;
board[i][col] = 0;
}
}
return false;
}
This code tries to place queens column by column, checking if each position is safe before placing a queen.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive backtracking tries placing queens in each row of a column.
- How many times: For each column, it tries up to N rows, and for each try, it checks safety by scanning rows and diagonals.
As the board size N grows, the number of ways to place queens grows very fast because each queen placement depends on previous ones.
| Input Size (n) | Approx. Operations |
|---|---|
| 4 | Hundreds of checks |
| 8 | Thousands to tens of thousands of checks |
| 12 | Millions of checks |
Pattern observation: The operations grow very quickly, much faster than just doubling or squaring; it grows exponentially.
Time Complexity: O(N!)
This means the time needed grows roughly like the factorial of N, which is very fast growth making large boards hard to solve quickly.
[X] Wrong: "The time complexity is just O(N^2) because we check rows and diagonals for each queen."
[OK] Correct: The main cost is the huge number of recursive calls trying different queen placements, not just the safety checks. The total tries grow factorially, not quadratically.
Understanding this problem's time complexity helps you explain why some problems are hard to solve quickly and shows your grasp of recursion and backtracking growth.
"What if we used extra memory to remember safe positions instead of checking each time? How would the time complexity change?"
Practice
N Queens Problem?Solution
Step 1: Understand the problem statement
The N Queens Problem requires placing N queens on an NxN chessboard so that no two queens threaten each other.Step 2: Identify the correct goal
This means no two queens share the same row, column, or diagonal.Final Answer:
Place N queens on an NxN chessboard so that no two queens attack each other -> Option DQuick Check:
Goal = Place queens safely [OK]
- Thinking queens can attack each other
- Confusing the problem with counting queens
- Ignoring diagonal attacks
Solution
Step 1: Recall C syntax for 2D arrays
In C, a 2D array is declared astype name[size1][size2];where both sizes are specified.Step 2: Match the correct declaration
int board[N][N]; usesint board[N][N];which correctly declares a 2D array for the chessboard.Final Answer:
int board[N][N]; -> Option BQuick Check:
2D array syntax = int board[N][N]; [OK]
- Using 1D array for 2D board
- Incorrect syntax like int board(N,N);
- Not specifying both dimensions
int board[4][4] = {0};
board[0][1] = 1;
board[1][3] = 1;
board[2][0] = 1;
board[3][2] = 1;
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
printf("%d ", board[i][j]);
}
printf("\n");
}Solution
Step 1: Place queens on the board as per given positions
Set board[0][1], board[1][3], board[2][0], board[3][2] to 1; others remain 0.Step 2: Print the board row-wise
Row 0: 0 1 0 0 Row 1: 0 0 0 1 Row 2: 1 0 0 0 Row 3: 0 0 1 0Final Answer:
0 1 0 0 0 0 0 1 1 0 0 0 0 0 1 0 -> Option CQuick Check:
Positions match output [OK]
- Mixing row and column indices
- Printing without spaces or newlines
- Incorrect initialization of board
board[row][col]:
int isSafe(int board[][N], int row, int col) {
for(int i=0; i=0 && j>=0; i--, j--) {
if(board[i][j] == 1) return 0;
}
for(int i=row, j=col; i>=0 && jSolution
Step 1: Analyze the use of N in function parameter
The function usesint board[][N]but N is not passed as a parameter or defined locally.Step 2: Understand C array parameter rules
In C, array sizes must be known or passed explicitly; assuming N as global can cause errors if not defined.Final Answer:
The function assumes N is a global constant but it may not be -> Option AQuick Check:
Array size N must be known [OK]
- Ignoring array size requirements in C
- Assuming N is always global
- Missing checks for diagonals
Solution
Step 1: Understand backtracking in N Queens
Backtracking uses recursion to place queens one row at a time, checking safety.Step 2: Identify recursion behavior
If no safe position is found in a row, recursion backtracks to previous row to try other positions.Final Answer:
Recursion tries to place queens row by row and backtracks when no safe position is found -> Option AQuick Check:
Backtracking = recursive trial and error [OK]
- Thinking recursion places queens randomly
- Confusing recursion with counting
- Ignoring backtracking step
Ready to prove it?
Pass the test and this pattern moves unknown
