DSA_lab_2
DSA_lab_2
LAB EXPERIMENT 1
OBJECTIVE:
Write a Program to Implement Breadth First Search using Python.
BRIEF DESCRIPTION:
Breadth-First Search uses a queue data structure to store the node and mark it as "visited" until it
marks all the neighboring vertices directly related to it. The queue operates on the First in First out
(FIFO) principle, so the node's neighbors will be viewed in the order in which it inserts them in the
node, starting with the node that was inserted first.
PRE-EXPERIMENT QUESTIONS:
1. What is searching?
2. What is QUEUE data structure?
Explanation:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
} visited = [] # List for visited
nodes. queue = [] #Initialize a
queue
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling Output:
POST EXPERIMENT QUESTIONS:
1 .What do you understand by BFS?
2. What is the time and space complexity of BFS?
LAB EXPERIMENT 2
OBJECTIVE:
Write a Program to Implement Depth First Search using Python.
BRIEF DESCRIPTION:
DFS is a recursive algorithm to search all the vertices of a tree data structure or a graph. The depthfirst
search (DFS) algorithm starts with the initial node of graph G and goes deeper until we find the goal
node or the node with no children.
Because of the recursive nature, stack data structure can be used to implement the DFS algorithm.
The process of implementing the DFS is similar to the BFS algorithm.
The step by step process to implement the DFS traversal is given as follows -
• First, create a stack with the total number of vertices in the graph.
• Now, choose any vertex as the starting point of traversal, and push that vertex into the stack.
• After that, push a non-visited vertex (adjacent to the vertex on the top of the stack) to the top
of the stack.
• Now, repeat steps 3 and 4 until no vertices are left to visit from the vertex on the stack's top.
• If no vertex is left, go back and pop a vertex from the stack.
• Repeat steps 2, 3, and 4 until the stack is empty.
Explanation:
# Using a Python dictionary to act as an adjacency list graph
={
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Depth-First Search") dfs(visited,
graph, '5')
Output:
POST EXPERIMENT QUESTIONS:
1. What do you understand by DFS?
LAB EXPERIMENT 3
OBJECTIVE:
Write a Program to Implement Tic-Tac-Toe game using Python.
BRIEF DESCRIPTION:
The game Tic Tac Toe is also known as Noughts and Crosses or Xs and Os ,the player needs to take turns
marking the spaces in a 3x3 grid with their own marks,if 3 consecutive marks (Horizontal,
Vertical,Diagonal) are formed then the player who owns these moves get won.
Assume ,
Player 1 - X
Player 2 - O
So,a player who gets 3 consecutive marks first, they will win the game .
Explanation:
# Function to print Tic Tac Toe def
print_tic_tac_toe(values): print("\
n")
values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
_____')
print("\t | |")
n")
print_scoreboard(score_board):
print("\t--------------------------------")
print("\t--------------------------------")
players = list(score_board.keys()) print("\t ",
print("\t--------------------------------\n")
check_win(player_pos, cur_player):
# All possible winning combinations soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4,
in x):
return True
return False
check_draw(player_pos): if len(player_pos['X']) +
len(player_pos['O']) == 9:
return True
return False
# Function for a single game of Tic Tac Toe def
single_game(cur_player):
while True:
print_tic_tac_toe(values)
try:
continue
continue
continue
values[move-1] = cur_player #
player_pos[cur_player].append(move)
if check_win(player_pos, cur_player):
print("\n")
return cur_player
if check_draw(player_pos):
print_tic_tac_toe(values) print("Game
Drawn")
print("\n")
return 'D'
if cur_player == 'X':
cur_player = 'X'
if _name_ == "_main_":
n")
cur_player = player1
print_scoreboard(score_board)
while True:
# Player choice Menu print("Turn
try:
Try Again\n")
continue
if choice == 1:
player_choice['X'] = cur_player
if cur_player == player1:
player_choice['O'] = player2
else:
player_choice['O'] = player1
elif choice == 2:
player_choice['O'] = cur_player
if cur_player == player1:
player_choice['X'] = player2
else:
player_choice['X'] = player1
elif choice == 3:
print("Final Scores")
print_scoreboard(score_board)
break
else:
winner = single_game(options[choice-1]) #
if winner != 'D' :
player_won = player_choice[winner]
score_board[player_won] = score_board[player_won] + 1
player2
else:
cur_player = player1
Output:
POST EXPERIMENT QUESTIONS:
1. How to implement tic-tac-toe using BFS?
LAB EXPERIMENT 4
OBJECTIVE:
Write a Program to implement 8-Puzzle problem using Python.
BRIEF DESCRIPTION:
The 8 puzzle consists of eight numbered, movable tiles set in a 3x3 frame. One cell of the frame is always
empty thus making it possible to move an adjacent numbered tile into the empty cell. Such a puzzle is
illustrated in following diagram.
The program is to change the initial configuration into the goal configuration.
A solution to the problem is an appropriate sequence of moves, such as “move tile 5 to the right, move tile 7
to the left, move tile 6 to the down” etc…
To solve a problem, we must specify the global database, the rules, and the control strategy.
The set of all possible configuration in the problem space, consists of 3,62,880 different configurations of the
8 tiles and blank space.
For the 8-puzzle, a straight forward description is a 3X3 array of matrix of numbers. Initial global database is
this description of the initial problem state. Virtually any kind of data structure can be used to describe
states.
n = 3 row = [ 1, 0, -
1, 0 ] col = [ 0, -1, 0,
1 ] class
priorityQueue:
def _init_(self):
self.heap = []
self.heap:
return True
else: return
False
class node:
cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
nxt):
count = 0
for i in range(n):
for j in range(n): if
final[i][j])):
count += 1
return count
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0] y1 = empty_tile_pos[1] x2 = new_empty_tile_pos[0]
cost, level)
return new_node
def printMatrix(mat):
for i in range(n):
for j in range(n):
print()
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
pq = priorityQueue()
empty_tile_pos, cost, 0)
pq.push(root)
minimum.cost == 0:
printPath(minimum)
return
for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ] if
isSafe(new_tile_pos[0], new_tile_pos[1]):
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]
empty_tile_pos = [ 1, 2 ]
Output:
POST EXPERIMENT QUESTIONS:
1. Which algorithm is used in 8-Puzzle problem?
LAB EXPERIMENT 6
OBJECTIVE:
Write a Program to Implement Travelling Salesman Problem using Python.
BRIEF DESCRIPTION:
The travelling salesman problem is a graph computational problem where the salesman needs to visit all
cities (represented using nodes in a graph) in a list just once and the distances (represented using edges in
the graph) between all these cities are known. The solution that is needed to be found for this problem is
the shortest possible route in which the salesman visits all the cities and returns to the origin city.
If you look at the graph below, considering that the salesman starts from the vertex ‘a’, they need to travel
through all the remaining vertices b, c, d, e, f and get back to ‘a’ while making sure that the cost taken is
minimum.
PRE EXPERIMENT QUESTIONS:
1. What is Brute –Force Searching?
Explanation:
from sys import maxsize from itertools
travellingSalesmanProblem(graph, s):
vertex = []
for i in range(V):
if i != s:
vertex.append(i)
min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:
current_pathweight = 0
k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]
return min_path
if _name_ == "_main_":
s=0
print(travellingSalesmanProblem(graph, s))
Output:
LAB EXPERIMENT 7
OBJECTIVE:
Write a Program to Implement Tower of Hanoi using Python.
BRIEF DESCRIPTION:
Tower of Hanoi is mathematical game puzzle where we have three pile (pillars) and n numbers of
disk.
This game has some rules (Rules of game)
• Only one disk will move at a time.
• The larger disk should always be on the bottom and the smaller disk on top of it.(Even
during intermediate move)
• Move only the uppermost disk.
• All disk move to destination pile from source pile.
So, here we are trying to solve that how many moves are required to solve a problem (It depends on
number of disk).
In the above diagram, following the rule of the game our target is move the disks from source pile (pillar) to
the destination pillar. (Let’s take a look how many steps/ moves are required to make this happen).
Step1: Move small disk to the auxiliary pillar (A).
Step2: Move large disk to the Destination pillar (B).
Step3: Move small disk to the Destination pillar (B).4
So, basically when we have 2 disks we required 3 move to reach the destination.
What if we have 3, 4, 5...n disks?
Eventually, you figure out that there is some pattern to the puzzle and with each increment in disks; the pattern
could be followed recursively.
Total move required to reach destination pillar is formula of moves means if we have 3 disks we required (4
moves to reach destination pillar), if 4 disks 8 moves required and so on...
2. What is Backtracking?
Explanation: class
Tower:
def __init__(self): self.terminate = 1
def printMove(self, source, destination):
print("{} -> {}".format(source, destination)) def
move(self, disc, source, destination, auxiliary):
if disc == self.terminate:
self.printMove(source, destination)
else:
self.move(disc - 1, source, auxiliary, destination)
self.move(1, source, destination, auxiliary) self.move(disc - 1,
auxiliary, destination, source) t = Tower();
t.move(3, 'A', 'B', 'C')
Output:
POST EXPERIMENT QUESTIONS:
1. What is the practical use of Tower of Hanoi?
2. Which data structure is used in the Tower of Hanoi?
3. Can we solve Tower of Hanoi problem without recursion?
4. Which algorithm approach is used to solve the Tower of Hanoi problem?
LAB EXPERIMENT 8
OBJECTIVE:
Write a Program to Implement Monkey Banana Problem using Python.
BRIEF DESCRIPTION:
The monkey and banana problem is a famous toy problem in artificial intelligence, particularly in
logic programming and planning. A monkey is in a room. Suspended from the ceiling is a bunch of
bananas, beyond the monkey's reach. However, in the room there are also a chair and a stick. The
ceiling is just the right height so that a monkey standing on a chair could knock the bananas down
with the stick. The monkey knows how to move around, carry other things around, reach for the
bananas, and wave a stick in the air. What is the best sequence of actions for the monkey? The
problem seeks to answer the question of whether monkeys are intelligent. Both humans and
monkeys have the ability to use mental maps to remember things like where to go to find shelter, or
how to avoid danger. They can also remember where to go to gather food and water, as well as how
to communicate with each other. Monkeys have the ability not only to remember how to hunt and
gather but to learn new things, as is the case with the monkey and the bananas: despite the fact that
the monkey may never have been in an identical situation, with the same artifacts at hand, a monkey
is capable of concluding that it needs to make a ladder, position it below the bananas, and climb up
to reach for them.
Output:
$ pip install poodle
$ python ./monkey.py
Monkey moved to Position B
Remembered that if banana is on the tree, its height equals tree's height
Remembered that if banana is on palm tree, its location is where palm tree is
Monkey moved box to Position C
Monkey climbs the box
Monkey takes the banana
LAB EXPERIMENT 10
OBJECTIVE:
Write a Program to implement 8-Queens Problem using Python.
BRIEF DESCRIPTION:
The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that
no two queens threaten each other; thus, a solution requires that no two queens share the same row,
column, or diagonal. There are 92 solutions. We have 8 queens and an 8x8 Chess board having al
ternate black and white squares. The queens are placed on the chessboard. Any queen can attack any
other queen placed on same row, or column or diagonal. We have to find the proper placement of
queens on the Chess board in such a way that no queen attacks other queen”.
In figure, the possible board configuration for 8-queen problem has been shown. The board has
alternative black and white positions on it. The different positions on the board hold the queens.
The production rule for this game is you cannot put the same queens in a same row or same column
or in same diagonal. After shifting a single queen from its position on the board, the user have to
shift other queens according to the production rule.
Starting from the first row on the board the queen of their corresponding row and column are to be
moved from their original positions to another position. Finally the player has to be ensured that no
rows or columns or diagonals of on the table are same.
Explanation:
# Python program to solve N Queen problem
global N N = 4 def printSolution(board): for
i in range(N): for j in range(N): print
board[i][j], print def isSafe(board, row, col):
# Check this row on left side for i in
range(col): if board[row][i] == 1:
return False
# Check upper diagonal on left side for i, j in
zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1: return
False
# Check lower diagonal on left side for i, j in
zip(range(row, N, 1), range(col, -1, -1)): if
board[i][j] == 1: return False return True def
solveNQUtil(board, col):
# base case: If all queens are placed #
then return true if col >= N: return True
for i in range(N): if isSafe(board, i,
col): # Place this queen in board[i][col]
board[i][col] = 1 # recur to place rest of
the queens if solveNQUtil(board, col +
1) == True:
return True board[i]
[col] = 0 return
False def
solveNQ(): board =
[ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) == False:
print "Solution does not exist"
return False printSolution(board)
return True
# driver program to test above function solveNQ()
Output:
0010
1000
0001
0100