-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.py
More file actions
30 lines (24 loc) · 764 Bytes
/
Copy pathBFS.py
File metadata and controls
30 lines (24 loc) · 764 Bytes
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
def bfs(graph, start, goal):
queue = [start]
visited = []
while queue:
node = queue.pop(0)
if node not in visited:
visited.append(node)
if node == goal:
print("Goal found:", node)
break
for neighbor in graph.get(node, []):
if neighbor not in visited:
queue.append(neighbor)
print("BFS Traversal:", visited)
# Input
graph = {}
n = int(input("Enter number of nodes: "))
for _ in range(n):
node = input("Enter node: ")
neighbors = input(f"Enter neighbors of {node} (space-separated): ").split()
graph[node] = neighbors
start = input("Enter start node: ")
goal = input("Enter goal node: ")
bfs(graph, start, goal)