File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 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 )))
You can’t perform that action at this time.
0 commit comments