0% found this document useful (0 votes)
12 views

Python (Back Traking Algorithms)

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python (Back Traking Algorithms)

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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

1.Decision Problem – In this, we search for a feasible solution.


2.Optimization Problem – In this, we search for the best solution.
3.Enumeration 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
chessboard.append(row)

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


PlaceNQueens(chessboard, 0)

if __name__ == "__main__" :
main()

You might also like