-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.py
More file actions
34 lines (23 loc) · 814 Bytes
/
Copy pathDFS.py
File metadata and controls
34 lines (23 loc) · 814 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
31
32
33
34
def dfs(graph, start, goal):
stack = [start]
visited = []
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
if node == goal:
print("Goal found:", node)
break
for neighbor in reversed(graph.get(node, [])):
if neighbor not in visited:
stack.append(neighbor)
print("DFS Traversal:", visited)
graph = {}
nodes = int(input("Enter number of nodes: "))
for _ in range(nodes):
node = input("Enter node: ").strip()
neighbors = input(f"Enter neighbors of {node} (space-separated): ").split()
graph[node] = neighbors
start = input("Enter start node: ").strip()
goal = input("Enter goal node: ").strip()
dfs(graph, start, goal)