Added code for assignment 1, dfs+bfs. Thanks to Vedang!

This commit is contained in:
K 2025-01-28 19:05:40 +05:30
parent 04e40e8623
commit 9ea6979a86
Signed by: notkshitij
GPG Key ID: C5B8BC7530F8F43F
2 changed files with 81 additions and 1 deletions

80
Codes/Assignment-A1.py Normal file
View File

@ -0,0 +1,80 @@
# ASSIGNMENT 1: DFS & BFS
#
# Implement depth first search algorithm and Breadth First Search algorithm, Use an undirected
# graph and develop a recursive algorithm for searching all the vertices of a graph or tree data
# structure
from collections import deque
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, u, v):
if u not in self.graph:
self.graph[u] = []
if v not in self.graph:
self.graph[v] = []
self.graph[u].append(v)
self.graph[v].append(u) # Since the graph is undirected
def dfs(self, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=' ')
for neighbor in self.graph.get(start, []):
if neighbor not in visited:
self.dfs(neighbor, visited)
def bfs_recursive_helper(self, queue, visited):
if not queue:
return
vertex = queue.popleft()
print(vertex, end=' ')
for neighbor in self.graph.get(vertex, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
self.bfs_recursive_helper(queue, visited)
def bfs_recursive(self, start):
visited = set()
queue = deque([start])
visited.add(start)
self.bfs_recursive_helper(queue, visited)
def menu():
g = Graph()
while True:
print("\nMenu")
print("1. Add edge")
print("2. Depth First Search (DFS)")
print("3. Breadth First Search (BFS)")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
u = int(input("Enter vertex u: "))
v = int(input("Enter vertex v: "))
g.add_edge(u, v)
elif choice == '2':
start = int(input("Enter starting vertex for DFS: "))
print("Depth First Search (DFS):")
g.dfs(start)
print()
elif choice == '3':
start = int(input("Enter starting vertex for BFS: "))
print("Breadth First Search (BFS):")
g.bfs_recursive(start)
print()
elif choice == '4':
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
menu()

View File

@ -10,7 +10,7 @@
### Notes
### Codes
1. [Assignment-A1 (DFS | BFS)]()
1. [Assignment-A1 (DFS | BFS)](Codes/Assignment-A1.py)
2. [Assignment-A2 (A star algorithm)]()
3. [Assignment-A3.I (Selection Sort)](Codes/Assignment-A3.I.py)