Challenge - 5 Problems
N Queens Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of N Queens Solution Count
What is the output of the following code that counts the number of solutions for the 4-Queens problem?
DSA Python
def is_safe(board, row, col, n): for i in range(col): if board[row][i] == 1: return False i, j = row, col while i >= 0 and j >= 0: if board[i][j] == 1: return False i -= 1 j -= 1 i, j = row, col while i < n and j >= 0: if board[i][j] == 1: return False i += 1 j -= 1 return True def solve_n_queens(board, col, n): if col == n: return 1 count = 0 for i in range(n): if is_safe(board, i, col, n): board[i][col] = 1 count += solve_n_queens(board, col + 1, n) board[i][col] = 0 return count n = 4 board = [[0]*n for _ in range(n)] print(solve_n_queens(board, 0, n))
Attempts:
2 left
💡 Hint
Recall the known number of solutions for 4 queens on a 4x4 board.
✗ Incorrect
The 4-Queens problem has exactly 2 distinct solutions. The code counts all valid placements recursively.
🧠 Conceptual
intermediateUnderstanding Diagonal Attacks in N Queens
In the N Queens problem, why do we check diagonals when placing a queen?
Attempts:
2 left
💡 Hint
Think about how a queen moves in chess.
✗ Incorrect
Queens attack horizontally, vertically, and diagonally. Checking diagonals ensures no queen can attack another diagonally.
🔧 Debug
advancedIdentify the Error in N Queens Safety Check
What error will this code produce when checking if a queen can be placed safely?
DSA Python
def is_safe(board, row, col, n): for i in range(col): if board[row][i] == 1: return False i, j = row, col while i >= 0 and j >= 0: if board[i][j] == 1: return False i -= 1 j -= 1 i, j = row, col while i < n and j >= 0: if board[i][j] == 1: return False i += 1 j -= 1 return True board = [[0]*4 for _ in range(4)] print(is_safe(board, 4, 2, 4))
Attempts:
2 left
💡 Hint
Check the row index passed to is_safe.
✗ Incorrect
Row index 4 is outside the 0-3 range for a 4x4 board, causing IndexError.
🚀 Application
advancedNumber of Solutions for 5 Queens
How many distinct solutions does the 5-Queens problem have?
Attempts:
2 left
💡 Hint
Try to recall or research the known solution count for 5 queens.
✗ Incorrect
The 5-Queens problem has exactly 10 distinct solutions.
❓ Predict Output
expertOutput of N Queens Board Representation
What is the printed board after placing queens for n=4 in this code?
DSA Python
def print_board(board): for row in board: print(' '.join('Q' if x == 1 else '.' for x in row)) board = [ [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0] ] print_board(board)
Attempts:
2 left
💡 Hint
Look carefully at the positions of 1s in the board list.
✗ Incorrect
The code prints 'Q' where the board has 1 and '.' where it has 0, row by row.
