0% found this document useful (0 votes)
91 views7 pages

Programming Assignments by Shivam Kumar

The document describes implementations of depth first search (DFS) and breadth first search (BFS) algorithms on graphs. For DFS, it defines a graph as a dictionary and performs a recursive DFS function that prints each visited node. For BFS, it defines a Graph class with edge addition and performs a BFS function using a queue that prints visited nodes level-by-level. Both algorithms are demonstrated on sample graph data with output showing the traversal order.

Uploaded by

Arpit Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views7 pages

Programming Assignments by Shivam Kumar

The document describes implementations of depth first search (DFS) and breadth first search (BFS) algorithms on graphs. For DFS, it defines a graph as a dictionary and performs a recursive DFS function that prints each visited node. For BFS, it defines a Graph class with edge addition and performs a BFS function using a queue that prints visited nodes level-by-level. Both algorithms are demonstrated on sample graph data with output showing the traversal order.

Uploaded by

Arpit Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Assignment 5(a)

NAME – Shivam Kumar GROUP NO. –G2


ROLL NO. - 2100270140052
5(a). Solve two jug Problem.
from collections import deque
def BFS(a, b, target):
m = {}
isSolvable = False
path = []
q = deque()
[Link]((0, 0))
while (len(q) > 0):
u = [Link]()
if ((u[0], u[1]) in m):
continue
if ((u[0] > a or u[1] > b or
u[0] < 0 or u[1] < 0)):
continue
[Link]([u[0], u[1]])
m[(u[0], u[1])] = 1
if (u[0] == target or u[1] == target):
isSolvable = True
if (u[0] == target):
if (u[1] != 0):
[Link]([u[0], 0])
else:
if (u[0] != 0):
[Link]([0, u[1]])
sz = len(path)
for i in range(sz):
print("(", path[i][0], ",",
path[i][1], ")")
break
[Link]([u[0], b])
[Link]([a, u[1]])
for ap in range(max(a, b) + 1):
c = u[0] + ap
d = u[1] - ap
if (c == a or (d == 0 and d >= 0)):
[Link]([c, d])
c = u[0] - ap
d = u[1] + ap
if ((c == 0 and c >= 0) or d == b):
[Link]([c, d])
[Link]([a, 0])
[Link]([0, b])
if (not isSolvable):
print("No solution");
if __name__ == '__main__':
Jug1=int(input("Enter the cpacity of jug1 : "));
Jug2=int(input("Enter the capacity of jug2 : "));
target=int(input("Enter the target you want to achive : "));
BFS(Jug1, Jug2, target)

OUTPUT
Enter the cpacity of jug1 : 4
Enter the capacity of jug2 : 6
Enter the target you want to achive : 2
(0,0)
(0,6)
(4,0)
(4,6)
(4,2)
(0,2)
Assignment 5(b)

NAME – Shivam Kumar GROUP NO. – G2


ROLL NO. - 2100270140052
5(b). Implement Tic- Tac-Toe.
import random
class TicTacToe:
def __init__(self):
[Link] = []
def create_board(self):
for i in range(3):
row = []
for j in range(3):
[Link]('-')
[Link](row)
def get_random_first_player(self):
return [Link](0, 1)
def fix_spot(self, row, col, player):
[Link][row][col] = player
def is_player_win(self, player):
win = None
n = len([Link])
for i in range(n):
win = True
for j in range(n):
if [Link][i][j] != player:
win = False
break
if win:
return win
for i in range(n):
win = True
for j in range(n):
if [Link][j][i] != player:
win = False
break
if win:
return win
win = True
for i in range(n):
if [Link][i][i] != player:
win = False
break
if win:
return win
win = True
for i in range(n):
if [Link][i][n - 1 - i] != player:
win = False
break
if win:
return win
return False
for row in [Link]:
for item in row:
if item == '-':
return False
return True
def is_board_filled(self):
for row in [Link]:
for item in row:
if item == '-':
return False
return True
def swap_player_turn(self, player):
return 'X' if player == 'O' else 'O'
def show_board(self):
for row in [Link]:
for item in row:
print(item, end=" ")
print()
def start(self):
self.create_board()
player = 'X' if self.get_random_first_player() == 1 else 'O'
while True:
print(f"Player {player} turn")
self.show_board()
row, col = list(
map(int, input("Enter row and column numbers to fix spot: ").split()))
print()
self.fix_spot(row - 1, col - 1, player)
if self.is_player_win(player):
print(f"Player {player} wins the game!")
break
if self.is_board_filled():
print("Match Draw!")
break
player = self.swap_player_turn(player)
print()
self.show_board()
tic_tac_toe = TicTacToe()
tic_tac_toe.start()

OUTPUT
Player X turn
---
---
---
Enter row and column numbers to fix spot: 3 3

Player O turn
---
---
--X
Enter row and column numbers to fix spot: 1 1

Player X turn
O--
---
--X
Enter row and column numbers to fix spot: 1 3

Player O turn
O-X
---
--X
Enter row and column numbers to fix spot: 2 3

Player X turn
O-X
--O
--X
Enter row and column numbers to fix spot: 3 1

Player O turn
O-X
--O
X-X
Enter row and column numbers to fix spot: 2 2

Player X turn
O-X
-OO
X-X
Enter row and column numbers to fix spot: 3 2

Player X wins the game!

O-X
-OO
XXX
Assignment 6(a)

NAME – Shivam Kumar GROUP NO. – G2


ROLL NO. - 2100270140052
6(a). Implement Depth First Search.
graph = {
'6' : ['5','4'],
'4' : ['3', '5'],
'5' : ['7'],
'3' : [],
'7' : ['6'],
'2' : ['5'],
'1' : ['2','3']
}

visited = set()

def dfs(visited, graph, node):


if node not in visited:
print (node)
[Link](node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

print("The Depth-First Search traversal is: ")


dfs(visited, graph, '1')

OUTPUT

The Depth-First Search traversal is:


1
2
5
7
6
4
3
Assignment 6(b)

NAME – Shivam Kumar GROUP NO. – G2


ROLL NO. - 2100270140052

6(b). Implement Breadth First Search.


from collections import defaultdict as dd
class Graph:
def __init__(self):
[Link] = dd(list)
def addEdgetoGraph(self, x, y):
[Link][x].append(y)
def BFSearch(self, n):
visited_vertices = ( len([Link] ))*[False]
queue = []
visited_vertices[n] = True
[Link](n)
while queue:
n = [Link](0)
print (n)
for v in [Link][ n ]:
if visited_vertices[v] == False:
[Link](v)
visited_vertices[v] = True
graph = Graph()
[Link](0, 1)
[Link](1, 3)
[Link](4, 5)
[Link](2, 4)
[Link](3, 2)
[Link](5, 4)
[Link](6, 5)
print ( " The Breadth First Search Traversal is : " )
[Link](1)

OUTPUT
The Breadth First Search Traversal is :
1
3
2
4
5

Common questions

Powered by AI

The 'random' module is used in the Tic-Tac-Toe implementation to decide which player makes the first move. The function `get_random_first_player()` utilizes `random.randint(0, 1)` to return either 0 or 1, corresponding to one of the players ('X' or 'O'). This introduces an element of randomness to the game, ensuring that the starting player is not predetermined .

Both BFS and DFS are graph traversal techniques but differ in their approach. BFS, as used in the two jug problem, explores nodes level by level using a queue. This makes it suitable for finding the shortest path to the solution but can lead to high memory usage as it holds all nodes at the current level. DFS, in contrast, uses recursion to explore each path fully before backtracking, which can result in lower memory usage but does not guarantee the shortest path. DFS can also lead to stack overflows for large graphs, while BFS can become inefficient with high branching factors due to queue size growth .

In the DFS implementation, recursion is used to explore each branch of the graph as deep as possible before backtracking. The recursive function `dfs` checks if a node has been visited, adds it to the `visited` set, and recursively calls itself for each neighbor. This pattern allows the algorithm to traverse each connected node before moving on to adjacent branches, effectively achieving a depth-first traversal where nodes are visited in the order they appear along a branch .

In the BFS implementation, visited nodes are tracked using a boolean array that corresponds to each node's index. When a node is visited, its corresponding index in the array is set to true. The queue is used to explore nodes level by level, enqueuing unvisited neighbor nodes and dequeuing nodes for exploration in FIFO order. This ensures each node is fully processed before moving to the next level, crucial for BFS's functionality in finding the shortest path in unweighted graphs .

In BFS, capacity constraints are managed using a queue to store nodes at the current level, which can grow significantly with broad graphs. Efficient memory management involves quickly dequeuing and processing nodes to prevent excessive memory use. In DFS, recursion effectively reduces the data storage overhead since it employs a call stack, which tends to use less memory for deep, narrow trees. However, for expansive graphs, this can risk stack overflow, necessitating iterative DFS approaches or limiting recursion depth .

The Tic-Tac-Toe implementation determines the winning condition by checking if any row, column, or diagonal is filled with the same player's symbol ('X' or 'O'). It uses loops to verify each row and column, and separate checks for both diagonals. If all positions in any of these lines contain the same symbol, the function `is_player_win` returns true, indicating a win for the current player .

The two jug problem algorithm determines solvability by using a breadth-first search (BFS) approach. It attempts to find a sequence of operations to reach the desired water level in one of the jugs by exploring all possible states. The algorithm maintains a queue to track states, where each state is a tuple representing the water levels in both jugs. The significance of the path is that it represents the sequence of states visited, ultimately showing the steps needed to achieve the target volume in one of the jugs. The path is printed only if the target is achievable, otherwise it concludes with "No solution" .

The BFS implementation uses a queue to systematically explore all configurations of the jugs. Starting from the initial state (0, 0), it enqueues each new state resulting from possible operations: filling either jug to full, emptying either jug, or pouring from one jug to the other until one of the jugs is either full or empty. This approach ensures that all transitions are explored in breadth-first order, covering all potential configurations and confirming if the target configuration is achievable .

In both BFS and DFS, checking for already visited nodes is crucial to avoid re-processing the same node multiple times, which prevents infinite loops and reduces unnecessary computation. Re-visiting nodes can lead to inefficient searches and significantly increase the time complexity of the algorithms. By maintaining a list or set of visited nodes, both algorithms ensure each node is processed only once, optimizing the traversal and yielding performance improvements .

To modify the Tic-Tac-Toe implementation for a larger board, the `create_board` method should initialize a board with a different size, using nested loops. Checking for wins in larger dimensions may require adjusting `is_player_win` to verify more lines, which can be managed by generalizing win checks using variable loop lengths. Alternative win conditions such as requiring a sequence of four or more in any direction would involve altering the win check logic to dynamically adapt to different row or column lengths sufficient to claim victory .

You might also like