You are on page 1of 28

GROUP 10

BACKTRACKING
ALGORITHM
INTRODUCTION TO BACTRACKING
ALGORITHM

CPET5 LECTURE
Presented By:
Sarceno,Angeline V.
Romero, Marielle
Leonida, Joseph
De Jose, Jm
TABLE OF CONTENT

01 BACKTRACKING ALGRORITHM

02 BACTRACKING ALGORITHM

APPLICATION TO SOME SPECIFIC

04 PROBLEMS

05 TYPES OF BACKTRACKING ALGORITHM

APPLICATION OF BACTRACKING

06 ALGORITHM

SAMPLE CODES

USER INTERFACE
BACKTRACKING ALGORITHM

WHAT IS BACKTRACKING?

• defined as general algorithmic technique


that considers searching every possible
combination in order to solve a
computational problem

• it is a technique based on algorithm to


solve a problem
WHAT IS BACKTRACKING?
BACKTRACKING ALGORITHM

• it uses recursive calling to find the solution


by building a solution step by step
increasing values with time

• it removes the solutions that doesn't give


rise to the solution of the problem based on
the constraints given to solve the probleme
based on algorithm to solve a problem
WHAT IS BACKTRACKING
ALGORITHM?

It is use brute force approach


tries out all the possible
solutions and chooses the
desired/best solutions. This
approach is used to solve
problems that have multiple
solutions.

BACKTRACKING ALGORITHM
BACKTRACKING PROBLEM

The algorithm tries to find a sequence


path to the solution which has some small
checkpoints from where the problem can
backtrack if no feasible solution is found
for the problem.
BACKTRACKING ALGORITHM IS APPLIED TO
SOME SPECIFIC TYPES OF PROBLEMS

DECISION PROBLEM OPTIMISATION ENUMERATION


PROBLEM PROBLEM

used to search or to find a used to find the best used to find the set of all
feasible solution of the solution that can be feasible solutions of the
problem applied problem
TYPES OF BACKTRACKING
ALGORITHM

Backtracking algorithm is classified into two types:

Algorithm for recursive backtracing

Non-recursive backtracking algorithm


APLICATION
P
APPLICATION

TO FIND ALL HAMILTONIAN PATHS PRESENT


IN A GRAPH

• A Hamiltonian path, also known as a A B


Hamilton path, is a graph path connecting
two graph vertices that visit each vertex
exactly once. If a Hamiltonian way exists
with ajacent points, the resulting graph cycle
is a Hamiltonian cycle. C D

E
APPLICATION

TO SOLVE THE N QUEEN PROBLEM

• The problem of placing n queens on the nxn chessboard so that


no two queens attack each other is known as the n-queen q
puzzle.
q
• Return all distinct solutions to the n-queens puzzle given an
integer n. You are free to return the answer in any order. q
• Each solution has a unique configuration for the placement of
q
the n-queens, where 'Q' and '' represent a queen and a space,
respectively.
q
APPLICATION

MAZE SOLVING PROBLEM

• which are automated


methods for solving mazes.

SOURCE

DESTINATION
APPLICATION

THE KNIGHT'S TOUR PROBLEM

• The Knight's tour problem is the mathematical


problem of determining a knight's tour. A common
problem assigned to computer science students is
to write a program to find a knight's tour.
Variations of the Knight's tour problem involve
chess boards of different sizes than the usual nxn
irregular (non-rectangular) boards.
EXAMPLE CODE # 1

Code:
Finding all possible order of
def permute(list, s):
arrangements of a given set
if list == 1:
of letters. When we choose a
return s
pair we apply backtracking
else:
to verify if that exact pair
return [
has already been created or
y+x
not. If not already created,
for y in permute(1, s)
the pair is added to the
for x in permute(list - 1, s)
answer list else it is ignored.
]
print(permute(1, ["a","b","c"]))
print(permute(2, ["a","b","c"]))

Output:
['a', 'b', 'c']
['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
EXAMPLE CODE # 2
Code:
Getting multiples of 2 from def multiple_of_2(nums, multiple_list):
set of numbers 1-10 if not nums:
return multiple_list
else:
num = nums.pop()
if num % 2 == 0:
multiple_list.append(num)
return multiple_of_2(nums, multiple_list)

nums = list(range(1, 11))


multiple_list = []
print(multiple_of_2(nums, multiple_list))

Output:
['10','8','6','4','2']
USER INTERFACE
n = int (input("enter the value of n:")) #Backtracking
def nqn(board,row):
board= [[0 for i in range(n)] for i in range(n)] if row==n:
return True
def check_column(board, row,column):
for i in range(row,-1,-1): for i in range(n):
if board[i][column]==1: if (check_column(board,row,i)==True and
return false cheack_diagonal(board,row,i)==True):
return True board[row][i]=1
if nqn(board, row=1):
return True
def cheack_diagonal(board, row, column):
board[row][i]=0
for i, j in zip(range(row,-1,-1), range(column,-1,-1)):
return False
return False
for i,j in zip(range(row, -1,-1),range(column,n)):
if board [i][j]==1:
nqn(board,0)
return Fase
return True
for row in board:
print(row)
USER INTERFACE

enter the value of n: 3

Output:

[0, 0, 0]
[0, 0, 0]
[0, 0, 0]
USER INTERFACE
zodiac_signs = { def get_zodiac_sign(day, month):
"capricorn": (12, 22, -1, 19), for sign, (start_month, start_day, end_month, end_day)
"aquarius": (1, 20, -2, 18), in zodiac_signs.items():
"pisces": (2, 19, -3, 20), if (month == start_month and day >= start_day) or
"aries": (3, 21, -4, 19), (month == end_month and day <= end_day) or
"taurus": (4, 20, -5, 20), (start_month < month < end_month):
"gemini": (5, 21, -6, 20), return sign
"cancer": (6, 21, -7, 22), return None
"leo": (7, 23, -8, 22),
"virgo": (8, 23, -9, 22), print("Enter your birthday (DD MM):")
day, month = map(int, input().split())
"libra": (9, 23, -10, 22),
"scorpio": (10, 23, -11, 21),
sign = get_zodiac_sign(day, month)
"sagittarius": (11, 22, -12, 21)
if sign:
}
print("Your zodiac sign is", sign)
else:
print("Invalid date")
USER INTERFACE

Enter your birthday (DD MM):25 09

Output:

Your zodiac sign is libra


QUIZ
QUIZ

1. Use to find the sets of all feasible solution of the problem.

2-4. Give three types of problem

5. It is tries out all the possible solutions and chooses the desired/best solutions.
This approach is used to solve problems that have multiple solutions.

6- 7. Application of Backtracking Algorithm

8-10. Debuging
Fill in the
USERblanks:
INTERFACE

8. n = ________________________
board= [[0 for i in range(n)] for i in range(n)]
#Backtracking
def nqn(board,row):
if row==n:
def check_column(board, row,column): return True
for i in range(row,-1,-1):
if board[i][column]==1: for i in range(n):
return false if (check_column(board,row,i)==True and
return True cheack_diagonal(board,row,i)==True):
board[row][i]=1
def cheack_diagonal(board, row, column): if nqn(board, row=1):
return True
for i, j in zip(range(row,-1,-1), range(column,-1,-1)):
board[row][i]=0
return False
for i,j in zip(range(row, -1,-1),range(column,n)):
return False
if board [i][j]==1:
return Fase
nqn(board,0)
return True

for row in board:


print(row)
9.
USER INTERFACE
zodiac_signs = { def get_zodiac_sign(day, month):
"capricorn": (12, 22, -1, 19), for sign, (start_month, start_day, end_month, end_day)
"aquarius": (1, 20, -2, 18), in zodiac_signs.items():
"pisces": (2, 19, -3, 20), if (month == start_month and day >= start_day) or
"aries": (3, 21, -4, 19), (month == end_month and day <= end_day) or
"taurus": (4, 20, -5, 20), (start_month < month < end_month):
"gemini": (5, 21, -6, 20), return sign
"cancer": (6, 21, -7, 22), return None
"leo": (7, 23, -8, 22),
"virgo": (8, 23, -9, 22), print("Enter your birthday (DD MM):")
day, month = map(int, input().split())
"libra": (9, 23, -10, 22),
"scorpio": (10, 23, -11, 21),
sign = get_zodiac_sign(day, month)
"sagittarius": (11, 22, -12, 21)
if sign:
}
print("Your zodiac sign is", sign)
else:
print("Invalid date")
Enter your birthday (DD MM):25 09

Output:

_______________
10. CGKBINACKTRA
Answers:
1. Enumeration Problem

2-4: 9. Your zodiac sign is libra


Decision Problem
10. BACKTRACKING
Optimisation Problem
Enumeration Problem

5. Brute Force Approach

6-7: N-queen problem, Maze problem, Hamiltonian


Problem, Knights Tour

8. int (input("enter the value of n:"))


THANK you

You might also like