以二阶矩阵存储
def graph_bfs(graph, s):
color = []
queue = [] # 记录访问过的顶点
count = 0
n = len(graph)
for v in range(n):
color.append(0)
queue.append(s)
count = count + 1
color[s] = 1
while queue:
temp = queue[0]
print(temp)
# 下面是把color不为1的graph[count - 1]里的item放进Q
if count - 1 < n:
for i in graph[count - 1]:
if color[i] == 0:
queue.append(i)
queue.remove(temp)
count = count + 1
# 放进Q里的item变颜色
for v in queue:
color[v] = 1
if __name__ == '__main__':
graph_test = [[1, 2, 3], [5], [], [4], [5], []]
graph1 = [[1], [2, 3, 4], [3, 4], [], []]
graph2 = [[1, 2], [3], [0, 4, 5], [], [2, 5, 7], [2, 4, 7, 6], [5, 7], [4, 5, 6]]
source = 0
graph_bfs(graph2, source)
以字典存储
import collections
def breadth_first_search(graph, root):
visited, queue = set(), collections.deque([root])
while queue:
vertex = queue.popleft()
print(vertex)
print(visited)
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
graph_test = {0: [2, 3], 2: [4, 5], 3: [1, 4], 1: [4], 4: [5], 5: []}
breadth_first_search(graph_test, 0)