-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbfs.py
More file actions
224 lines (185 loc) · 5.92 KB
/
bfs.py
File metadata and controls
224 lines (185 loc) · 5.92 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# 广度优先搜索 (BFS) - Python 实现
"""
广度优先搜索(Breadth First Search)
时间复杂度: O(V + E)
空间复杂度: O(V)
"""
from collections import deque
def bfs_traversal(graph, start):
"""
BFS 遍历:从起点开始逐层访问所有节点
graph: 邻接表 {node: [neighbors]}
返回: 遍历顺序列表
"""
visited = set()
queue = deque([start])
visited.add(start)
result = []
while queue:
node = queue.popleft()
result.append(node)
# 添加所有未访问的邻接点
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return result
def bfs_shortest_path(graph, start, end):
"""
BFS 查找最短路径(无权图)
返回: 最短路径列表,如果不存在返回 None
"""
if start == end:
return [start]
visited = {start: None} # {node: parent}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited[neighbor] = node
if neighbor == end:
# 重构路径
path = []
current = end
while current is not None:
path.append(current)
current = visited[current]
return path[::-1]
queue.append(neighbor)
return None # 无路径
def bfs_level_order(graph, start):
"""
BFS 按层级遍历(树专用)
返回: [[第0层节点], [第1层节点], ...]
"""
levels = []
visited = {start}
current_level = [start]
while current_level:
levels.append(current_level)
next_level = []
for node in current_level:
for neighbor in graph.get(node, []):
if neighbor not in visited:
visited.add(neighbor)
next_level.append(neighbor)
current_level = next_level
return levels
def bfs_all_shortest_paths(graph, start):
"""
BFS 计算从起点到所有节点的最短距离和路径
返回: {node: (distance, path)}
"""
distances = {start: 0}
parents = {start: []} # 可能有多个父节点
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph.get(node, []):
if neighbor not in distances:
distances[neighbor] = distances[node] + 1
parents[neighbor] = [node]
queue.append(neighbor)
elif distances[neighbor] == distances[node] + 1:
# 找到另一条等长最短路径
parents[neighbor].append(node)
# 重构所有最短路径
def reconstruct_paths(node):
if not parents[node]:
return [[node]]
paths = []
for parent in parents[node]:
for path in reconstruct_paths(parent):
paths.append(path + [node])
return paths
result = {}
for node in distances:
paths = reconstruct_paths(node)
result[node] = (distances[node], paths)
return result
def bfs_connected_components(graph):
"""
BFS 查找无向图的所有连通分量
返回: [分量1节点集, 分量2节点集, ...]
"""
visited = set()
components = []
for node in graph:
if node not in visited:
component = set()
queue = deque([node])
visited.add(node)
while queue:
current = queue.popleft()
component.add(current)
for neighbor in graph.get(current, []):
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
components.append(component)
return components
if __name__ == "__main__":
print("=" * 50)
print("广度优先搜索 (BFS) - Python 实现")
print("=" * 50)
# 无向图
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
# 测试 1:BFS 遍历
print("\n测试 1: BFS 遍历")
print(f"图: {graph}")
result = bfs_traversal(graph, 'A')
print(f"从 A 开始的 BFS: {result}")
# 测试 2:最短路径
print("\n测试 2: 最短路径")
path = bfs_shortest_path(graph, 'A', 'F')
if path:
print(f"A 到 F 的最短路径: {' -> '.join(path)}")
else:
print("无路径")
# 测试 3:层级遍历
print("\n测试 3: 层级遍历")
tree = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
levels = bfs_level_order(tree, 'A')
for i, level in enumerate(levels):
print(f" 第 {i} 层: {level}")
# 测试 4:所有最短路径
print("\n测试 4: 所有最短路径")
simple_graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D'],
'D': []
}
all_paths = bfs_all_shortest_paths(simple_graph, 'A')
print(f"从 A 出发的最短路径:")
for node, (dist, paths) in all_paths.items():
print(f" 到 {node} (距离 {dist}): {paths}")
# 测试 5:连通分量
print("\n测试 5: 连通分量")
disconnected_graph = {
'A': ['B'],
'B': ['A'],
'C': ['D'],
'D': ['C'],
'E': []
}
components = bfs_connected_components(disconnected_graph)
print(f"图: {disconnected_graph}")
for i, comp in enumerate(components, 1):
print(f" 分量 {i}: {comp}")
print("\n" + "=" * 50)