๐ Today I Solved the N-Queens Problem Using Backtracking

Today, I dived into the N-Queens problem, a classic example of how backtracking can be used to solve constraint-based problems.
โ What I Learned:
The goal is to place
N
queens on anN x N
chessboard so that no two queens threaten each other.I used backtracking to explore all possible placements, row by row, and only kept safe configurations.
I learned how to represent each solution as a list where the index is the row and the value is the column (e.g.,
[1, 3, 0, 2]
).I also wrote a helper function to visualize the chessboard, making it easier to understand and debug.
๐ก Key Concepts Practiced:
Recursive function design
Backtracking logic
Diagonal and vertical threat detection
Clean board state management
Visualization of board configurations
Below is the full working Python code I used:
def solve_n_queens(n):
solutions = []
board = []
def is_safe(row, col):
for r in range(row):
c = board[r]
if c == col or abs(c - col) == abs(r - row):
return False
return True
def backtrack(row):
if row == n:
solutions.append(board[:])
return
for col in range(n):
if is_safe(row, col):
board.append(col)
backtrack(row + 1)
board.pop()
backtrack(0)
return solutions
# Example usage
n = 4
results = solve_n_queens(n)
def print_board(solution):
for row in solution:
line = ['.'] * n
line[row] = 'Q'
print(' '.join(line))
print()
for sol in results:
print_board(sol)
Subscribe to my newsletter
Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
