Green University of Bangladesh
Department of Computer Science and Engineering (CSE)
Semester: (Spring, Year:2025), B.Sc. in CSE (Day)
Solve N-Queen Problem Using Backtracking
Algorithm. Solve N-Queen Problem Using
Backtracking Algorithm..
Lab Report 03
Course Code: CSE- 316
Section: 221-D9
Students Details
Name ID
Md. Mursaline Parvez 221902363
Submission Date: 27/04/25
Course Teacher’s Name: Md. Riad Hassan
[For teachers use only: Don’t write anything inside this box]
Lab Project Status
Marks: Signature:
Comments: Date:
Contents
0.1 OBJECTIVES/AIM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
0.2 PROCEDURE / ANALYSIS / DESIGN . . . . . . . . . . . . . . . . . 2
0.3 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
0.4 Test Result / Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
0.5 DISCUSSION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
0.6 CONCLUSION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1
0.1 OBJECTIVES/AIM
• To solve the classic N-Queens problem using the backtracking algorithm.
• To understand how constraint satisfaction problems work through the example of
N-Queens.
• To find all possible valid solutions for placing N queens on an N × N chessboard.
• To represent the solutions visually using a box format resembling a real chess-
board.
0.2 PROCEDURE / ANALYSIS / DESIGN
In the N-Queens puzzle, the objective is to place N queens on an N × N chessboard such
that no two queens threaten each other. Specifically:
• No two queens should be placed in the same row.
• No two queens should be placed in the same column.
• No two queens should be placed along the same diagonal.
To achieve this, the backtracking algorithm is used, which systematically searches
for a solution by exploring all possible placements and backtracks when a conflict is
encountered.
The implementation process is as follows:
• Maintain a list of tuples, where each tuple stores the column and row position of
each queen.
• Create a helper function is_safe() to check whether a queen can be safely
placed at a particular position without being attacked.
• Use a recursive function solve() to attempt placing queens row by row:
– For each row, try placing a queen in each column.
– If placing a queen at a position is safe, recursively attempt to place the next
queen.
– If placing a queen leads to a dead-end (no safe placement in the next row),
backtrack and try the next column.
• When a valid solution (placing N queens successfully) is found, add it to the list
of solutions.
• Implement a make_board() function to visualize the solutions as a list of strings
with ’Q’ indicating a queen and ’.’ indicating an empty space.
• Use a print_boxed() function to display each solution neatly in a box-style
format similar to an actual chessboard layout.
2
0.3 Implementation
def is_safe(queens, row, col):
for r, c in enumerate(queens):
if c == col or abs(c - col) == abs(r - row):
return False
return True
def solve_n_queens(n):
solutions = []
def backtrack(row, queens):
if row == n:
board = []
for q_col in queens:
row_str = "." * q_col + "Q" + "." * (n - q_col - 1)
board.append(row_str)
solutions.append(board)
return
for col in range(n):
if is_safe(queens, row, col):
backtrack(row + 1, queens + [col])
backtrack(0, [])
return solutions
def print_boxed_boards(solutions):
for idx, board in enumerate(solutions, start=1):
print(f"Solution {idx}:")
for row in board:
print("+---" * len(row) + "+")
for ch in row:
print(f"| {’Q’ if ch == ’Q’ else ’ ’} ", end="")
print("|")
print("+---" * len(board[0]) + "+\n")
# --- Main Program ---
n = int(input("Enter number of queens: "))
all_solutions = solve_n_queens(n)
print(f"\nTotal solutions for {n} queens: {len(all_solutions)}\n")
print_boxed_boards(all_solutions)
3
0.4 Test Result / Output
Figure 1: Low-Level Class Diagram for User Management Module
0.5 DISCUSSION
The N-Queens problem is a classic example of a constraint satisfaction problem (CSP),
where multiple conditions must be satisfied simultaneously. Backtracking is an effective
technique to solve such problems because it explores possible states in a systematic way
and abandons those paths that cannot lead to a valid solution.
During the experiment:
• It was observed that early pruning (checking for safety while placing queens)
drastically reduces the number of possibilities that need to be explored.
• By using recursion, the algorithm elegantly attempts all combinations without
manually handling complex nested loops.
• Representing the chessboard visually using the make_board() function helped
to better understand and verify the correctness of each solution.
• The complexity increases rapidly with the value of N. For instance, while N = 4
and N = 8 can be computed quickly, larger values of N (e.g., N = 14 or N = 16)
require significant computation time due to the exponential growth in possibili-
ties.
The recursive backtracking approach emphasizes the importance of checking con-
straints early (forward checking) and demonstrates how depth-first search (DFS) strate-
gies operate internally.
4
0.6 CONCLUSION
In this lab, the N-Queens problem was successfully solved using a backtracking ap-
proach in Python. By leveraging recursion and constraint checking, all valid configura-
tions for placing queens on the chessboard were found efficiently.
The experiment deepened the understanding of:
• How backtracking algorithms systematically explore solution spaces.
• How constraint satisfaction problems can be approached and solved.
• How early pruning techniques improve the performance of recursive search algo-
rithms.