-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.py
More file actions
50 lines (40 loc) · 1.34 KB
/
Copy pathbfs.py
File metadata and controls
50 lines (40 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
result = []
while queue:
vertex = queue.popleft()
if vertex not in visited:
visited.add(vertex)
result.append(vertex)
queue.extend(neighbor for neighbor in graph[vertex] if neighbor not in visited)
return result
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
result = [start]
for neighbor in graph[start]:
if neighbor not in visited:
result.extend(dfs(graph, neighbor, visited))
return result
def read_graph():
graph = {}
num_nodes = int(input("Enter the number of nodes: "))
num_edges = int(input("Enter the number of edges: "))
for _ in range(num_edges):
u, v = input("Enter an edge (u v): ").split()
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
graph[v].append(u)
return graph
graph = read_graph()
start_node = input("Enter the starting node for traversal: ")
bfs_result = bfs(graph, start_node)
dfs_result = dfs(graph, start_node)
print("BFS Traversal:", bfs_result)
print("DFS Traversal:", dfs_result)