Skip to content

Commit

Permalink
Merge pull request #1076 from Riyachauhan11/main
Browse files Browse the repository at this point in the history
adding graph traversals
  • Loading branch information
UTSAVS26 authored Nov 5, 2024
2 parents 0b718ef + b7c09cc commit 39daf01
Show file tree
Hide file tree
Showing 3 changed files with 141 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
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) # For undirected graph

def bfs(self, start):
visited = set()
queue = deque([start])
traversal = []

visited.add(start)

while queue:
node = queue.popleft()
traversal.append(node)
for neighbor in self.graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

return traversal

def display(self):
for node, neighbors in self.graph.items():
print(f"{node}: {neighbors}")

def menu():
print("\n--- Graph BFS Menu ---")
print("1. Add Edge")
print("2. Perform BFS")
print("3. Display Graph")
print("4. Exit")

if __name__ == "__main__":
graph = Graph()

while True:
menu()
choice = input("Enter choice: ")

if choice == '1':
u = input("Enter first node: ")
v = input("Enter second node: ")
graph.add_edge(u, v)
print(f"Added edge between {u} and {v}.")

elif choice == '2':
start = input("Enter start node for BFS: ")
if start in graph.graph:
print("BFS Traversal:", graph.bfs(start))
else:
print(f"Node {start} does not exist in the graph.")

elif choice == '3':
print("Graph Adjacency List:")
graph.display()

elif choice == '4':
print("Exiting...")
break

else:
print("Invalid choice, try again.")
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
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) # For undirected graph

def dfs(self, start):
visited = set()
traversal = []

def dfs_util(v):
visited.add(v)
traversal.append(v)
for neighbor in self.graph.get(v, []):
if neighbor not in visited:
dfs_util(neighbor)

dfs_util(start)
return traversal

def display(self):
for node, neighbors in self.graph.items():
print(f"{node}: {neighbors}")

def menu():
print("\n--- Graph DFS Menu ---")
print("1. Add Edge")
print("2. Perform DFS")
print("3. Display Graph")
print("4. Exit")

if __name__ == "__main__":
graph = Graph()

while True:
menu()
choice = input("Enter choice: ")

if choice == '1':
u = input("Enter first node: ")
v = input("Enter second node: ")
graph.add_edge(u, v)
print(f"Added edge between {u} and {v}.")

elif choice == '2':
start = input("Enter start node for DFS: ")
if start in graph.graph:
print("DFS Traversal:", graph.dfs(start))
else:
print(f"Node {start} does not exist in the graph.")

elif choice == '3':
print("Graph Adjacency List:")
graph.display()

elif choice == '4':
print("Exiting...")
break

else:
print("Invalid choice, try again.")
2 changes: 2 additions & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@
* [Unique-Paths](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/unique-paths.py)
* Graph
* [Graph Cloning](Algorithms_and_Data_Structures/Graph/Graph_Cloning.py)
* [Menu Driven Code Bfs Traversal](Algorithms_and_Data_Structures/Graph/Menu_driven_code_BFS_Traversal.py)
* [Menu Driven Code Dfs Traversal](Algorithms_and_Data_Structures/Graph/Menu_driven_code_DFS_Traversal.py)
* Heapsort
* [Heapsortvisualizer](Algorithms_and_Data_Structures/HeapSort/heapsortvisualizer.py)
* [Timecomplexity1](Algorithms_and_Data_Structures/HeapSort/timecomplexity1.py)
Expand Down

0 comments on commit 39daf01

Please sign in to comment.