Skip to content

Commit ecd489b

Browse files
committed
add performance about dfs_iterative.py
1 parent 861dc1a commit ecd489b

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

graph/dfs_iterative.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Depth-First Search (DFS) - Iterative Approach(深度優先搜尋-迭代法)
2+
# O(1)
23
def dfs_iterative(graph, start):
34
# Initialize an empty set to keep track of visited nodes to avoid infinite loops
45
visited = set()

graph/dfs_iterative_optimized.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
def dfs_iterative_optimized(graph, start_node):
2+
# Optimization 2: Check for empty graph
3+
if not graph or start_node not in graph:
4+
return []
5+
6+
visited = set()
7+
# Optimization 3: Use a local list for faster access than global scope
8+
stack = [start_node]
9+
result = []
10+
11+
# Avoid re-evaluating 'stack' length in every iteration
12+
# Use 'while stack' as it's the most "Pythonic" and fastest
13+
while stack:
14+
node = stack.pop()
15+
16+
if node not in visited:
17+
visited.add(node)
18+
result.append(node)
19+
20+
# Optimization 4: List comprehension/Reversed filtering
21+
# We push neighbors in reverse to maintain expected traversal order
22+
neighbors = [n for n in graph.get(node, []) if n not in visited]
23+
stack.extend(reversed(neighbors))
24+
25+
return result
26+
27+
# Define the graph using an adjacency list
28+
graph = {
29+
'A': ['B', 'C'],
30+
'B': ['A', 'D', 'E'],
31+
'C': ['A', 'F'],
32+
'D': ['B'],
33+
'E': ['B', 'F'],
34+
'F': ['C', 'E']
35+
}
36+
37+
38+
output = dfs_iterative_optimized(graph, 'A')
39+
print(f"DFS result: {output}")
40+
# output
41+
# DFS result: ['A', 'B', 'D', 'E', 'F', 'C']

0 commit comments

Comments
 (0)