0% found this document useful (0 votes)
25 views6 pages

Backtracking Algorithm in Python

Backtracking is an algorithmic technique used to solve problems by exploring all possible combinations and incrementally building solutions while discarding those that fail to meet constraints. It encompasses decision, optimization, and enumeration problems, with applications in constraint satisfaction problems (CSPs) and examples like the N queens problem. The document also includes a Python implementation for solving the N queens problem using backtracking.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views6 pages

Backtracking Algorithm in Python

Backtracking is an algorithmic technique used to solve problems by exploring all possible combinations and incrementally building solutions while discarding those that fail to meet constraints. It encompasses decision, optimization, and enumeration problems, with applications in constraint satisfaction problems (CSPs) and examples like the N queens problem. The document also includes a Python implementation for solving the N queens problem using backtracking.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Back Taking (Brute Force approach)

Backtracking can be defined as a general algorithmic technique that considers searching every
possible combination in order to solve a computational problem.
Backtracking is an algorithmic technique for solving problems recursively by trying to build a
solution incrementally, one piece at a time, removing those solutions that fail to satisfy the
constraints of the problem at any point of time (by time, here, is referred to the time elapsed till
reaching any level of the search tree).

Types of Backtracking Algorithm


There are three types of problems in backtracking

[Link] Problem – In this, we search for a feasible solution.


[Link] Problem – In this, we search for the best solution.
[Link] Problem – In this, we find all feasible solutions.

Constraint satisfaction problems (CSPs) are mathematical questions defined as a set of objects
whose state must satisfy a number of constraints or limitations. CSPs represent the entities in a
problem as a homogeneous collection of finite constraints over variables, which is solved
by constraint satisfaction methods. CSPs are the subject of research in both artificial
intelligence and operations research, since the regularity in their formulation provides a common
basis to analyze and solve problems of many seemingly unrelated families.

Example of students :
We have three students, two boys, and one girl {B1, B2, G1}. We want to place them in three
positions as shown below while respecting the constraint that the girl should not be placed in the
middle. You have to Provide possible solutions that satisfy this constraint.

B1 B2 G2

possible solution without constraint 3! = 6 solutions.

First you have to create a state space tree that contain all possible solutions then cheek for the
constraint :
By Using DFS algorithm we will cheek the constraint and get possible solutions :
So the possible solution that respect the constraint are (4 Solutions):
S1 {B1, B2 ,G1}
S2 {B2, B1 ,G1}
S3 {G1, B1 ,B2}
S4 {G1, B2 ,GB1}

Example N Queens
N queens problem is one of the most common examples of backtracking. Our goal is to arrange N
queens on an NxN chessboard such that no queen can strike down any other queen. A queen can
attack horizontally, vertically, or diagonally.

First you have to create a state space tree that contain all possible solutions then cheek for the
constraints (attack horizontally, vertically, or diagonally (we cheek this constraint)) :
Solutions 2 : S1 {Q1: C2 , Q2: C4 , Q3 :C1 , Q4:C3}
S2 {Q1: C3 , Q2: C1 , Q3 :C4 , Q4:C2}
Code Python of Backtracking Algorithm (N queen)
from typing import List # For annotations

boardcnt = 0

def IsBoardOk (chessboard : List, row : int, col : int) :

# Check if there is a queen 'Q' positioned to the left of column col on the same row.
for c in range(col) :
if (chessboard[row][c] == 'Q') :
return False

# Check if there is queen 'Q' positioned on the upper left diagonal


for r, c in zip(range(row-1, -1, -1), range(col-1, -1, -1)) :
if (chessboard[r][c] == 'Q') :
return False

# Check if there is queen 'Q' positioned on the lower left diagonal


for r, c in zip(range(row+1, len(chessboard), 1), range(col-1, -1, -1)) :
if (chessboard[r][c] == 'Q') :
return False

return True
# type hinting
def DisplayBoard (chessboard : List) :

for row in chessboard :


print(row)
# type hinting
def PlaceNQueens (chessboard : List, col : int) :

# If all the columns have a queen 'Q', a solution has been found.
global boardcnt

if (col >= len(chessboard)) :

boardcnt += 1
print("Board " + str(boardcnt))
print("==========================")
DisplayBoard(chessboard)
print("==========================\n")

else :

# Else try placing the queen on each row of the column and check if the chessboard remains
OK.
for row in range(len(chessboard)) :

chessboard[row][col] = 'Q'

if (IsBoardOk(chessboard, row, col) == True) :


# Chess board was OK, hence try placing the queen 'Q' in the next column.
PlaceNQueens(chessboard, col + 1)

chessboard[row][col] = '.'; # As previously placed queen was not valid, restore '.'

def main() :

chessboard = []
N = int(input("Enter chessboard size : "))

for i in range(N) :
row = ["."] * N
[Link](row)

# Start placing the queen 'Q' from the 0'th column.


PlaceNQueens(chessboard, 0)

if __name__ == "__main__" :
main()

Common questions

Powered by AI

The state space tree in the N-Queens problem is a critical structure that represents all possible arrangements of queens on the board. It allows systematic exploration of possible solutions by organizing possibilities as nodes and edges representing decisions. Constraint checking is facilitated at each node as the algorithm progresses; for example, when placing a queen, constraints are checked to ensure no two queens threaten each other horizontally, vertically, or diagonally. This tree enables the algorithm to backtrack efficiently by pruning branches that violate constraints, thus reducing unnecessary computations .

When the N-Queens algorithm encounters a constraint violation, it triggers a backtrack mechanism where the algorithm returns to the last successful placement of a queen and tries a different position in the same column. This step involves reverting the current state of the board to a previous valid configuration. By systematically checking for constraint violations and employing backtracking, the algorithm ensures each solution is valid before progressing, thereby guaranteeing correctness in reaching a solution .

Pruning is essential in backtracking algorithms because it reduces the problem's computational complexity by eliminating paths early that cannot yield valid solutions. In the context of the N-Queens problem, pruning prevents unnecessary exploration of queen placements that would be immediately invalid due to threatening other queens. This reduces the search space the algorithm needs to explore, improving efficiency and speed by focusing only on promising solutions .

While the backtracking algorithm inherently seeks solutions by exploring all permutations like a brute force approach, it introduces optimizations by employing recursion and constraint checking to prune infeasible paths early. In the N-Queens problem, the algorithm doesn't evaluate all possible positions indiscriminately; instead, it systematically considers valid positions and backtracks on invalid ones, thereby optimizing the brute force search by reducing unnecessary computation and narrowing focus to viable solutions only .

Constraint satisfaction methods offer advantages like the ability to model complex problems with a set of constraints that can be systematically and efficiently checked and solved using algorithms like backtracking. These methods provide a uniform framework to tackle varied problems across domains, facilitating solutions to be derived efficiently and systematically. In AI and operations research, CSPs enable representing complex decision-making scenarios with clarity and precision, leveraging mathematical rigor to ensure optimal solutions that satisfy all constraints .

The constraint satisfaction problem (CSP) framework can be applied by first defining the variables, which are the positions that the students can occupy. The constraint is that the girl cannot be in the middle position. Using a CSP, we represent each potential arrangement as a combination of variables and check them against the constraint using methods like backtracking to eliminate infeasible solutions. Solutions like {B1, B2, G1}, {B2, B1, G1} all satisfy the constraint since G1 is never in the middle .

Backtracking algorithms aim to solve three types of problems: Decision Problems, Optimization Problems, and Enumeration Problems. Decision Problems seek a feasible solution from the possible options. Optimization Problems focus on finding the best solution among many, often concerning maximizing or minimizing some value. Enumeration Problems aim to list all feasible solutions. The fundamental difference lies in the goal of the search: finding one solution, the best solution, or all solutions .

The recursive process in the N-Queens problem code involves placing queens on the board column by column. For each placement in a column, the code checks constraints using the `IsBoardOk` function, ensuring no queens attack each other horizontally, vertically, or diagonally. If a placement is valid, the function recursively attempts to place queens in the subsequent columns. If a conflict arises (i.e., constraints are violated), the board is restored to its previous state and tries a new position. This process ensures adherence to constraints before committing to any placement .

Using constraint satisfaction problems (CSPs) in applications can significantly enhance scalability, as they provide a structured framework to define and manage complex constraint logic in problem-solving. CSPs facilitate efficient solving of large, complex problems by enabling systematic exploration and resolution of constraints without exhaustive enumeration. Their ability to be fine-tuned to handle various complexities and constraints simultaneously makes them particularly suitable for scaling real-world applications that demand robust decision-making processes .

The backtracking algorithm uses recursion to iteratively attempt placing queens on the board column by column. The recursive function places a queen in a column and advances to the next column, only if the current placement satisfies the constraints. This method effectively explores possible arrangements by pursuing valid placements (recursive calls) and retracting (backtracking) from invalid arrangements, thus simplifying the solution space exploration. This approach efficiently manages the complexity inherent in the problem by decomposing it into smaller, manageable sub-problems .

You might also like