-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_Depth_First_Search.py
More file actions
42 lines (38 loc) · 1.07 KB
/
02_Depth_First_Search.py
File metadata and controls
42 lines (38 loc) · 1.07 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
# File: practical2_dfs.py
# Iterative DFS implementation using adjacency list.
from collections import deque
def iterative_dfs(adj, start):
visited = set()
order = []
stack = [start]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
order.append(node)
# add neighbors in reversed sorted order for deterministic output
neighbors = list(adj.get(node, []))
try:
neighbors.sort(reverse=True)
except TypeError:
pass
for neigh in neighbors:
if neigh not in visited:
stack.append(neigh)
return order
def main():
# Example graph (adjacency list)
graph = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": ["F"],
"D": [],
"E": ["F"],
"F": []
}
start = "A"
order = iterative_dfs(graph, start)
print("Iterative DFS starting from node", start)
print("Traversal order:", " -> ".join(order))
if __name__ == "__main__":
main()