Skip to content

Commit 481f7f4

Browse files
committed
I haved added traversal algorithms
1 parent d6f8a0e commit 481f7f4

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# A program to implement traversal algorithms (BFS and DFS) in the Graph.
2+
class Graph:
3+
def __init__(self):
4+
self.graph = {}
5+
def addEdge(self, u, v):
6+
if u not in self.graph:
7+
self.graph[u] = []
8+
self.graph[u].append(v)
9+
def BFS(self, start):
10+
visited = set()
11+
queue = [start]
12+
bfs_output = []
13+
while queue:
14+
vertex = queue.pop(0)
15+
if vertex not in visited:
16+
bfs_output.append(vertex)
17+
visited.add(vertex)
18+
queue.extend(self.graph.get(vertex, []))
19+
return bfs_output
20+
def DFS(self, start, visited=None):
21+
if visited is None:
22+
visited = set()
23+
if start not in visited:
24+
visited.add(start)
25+
for neighbor in self.graph.get(start, []):
26+
self.DFS(neighbor, visited)
27+
return visited
28+
if __name__ == '__main__':
29+
g = Graph()
30+
n = int(input("Enter number of edges: "))
31+
for i in range(n):
32+
u, v = map(str, input("Enter edge (u v): ").split())
33+
g.addEdge(u, v)
34+
print("1. BFS")
35+
print("2. DFS")
36+
choice = int(input("Choose traversal algorithm: "))
37+
start_node = input("Enter starting node: ")
38+
if choice == 1:
39+
print("BFS Traversal:", g.BFS(start_node))
40+
else:
41+
print("DFS Traversal:", list(g.DFS(start_node)))

0 commit comments

Comments
 (0)