Python (Back Traking Algorithms)
Python (Back Traking Algorithms)
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).
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
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
# 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
return True
# type hinting
def DisplayBoard (chessboard : List) :
# If all the columns have a queen 'Q', a solution has been found.
global boardcnt
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'
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)
if __name__ == "__main__" :
main()