"""pseudo-code""""""BFS(graph G, start vertex s):// all nodes initially unexploredmark s as exploredlet Q = queue data structure, initialized with swhile Q is non-empty:remove the first node of Q, call it vfor each edge(v, w): // for w in graph[v]if w unexplored:mark w as exploredadd w to Q (at the end)"""import collectionsdef bfs(graph, start):explored, queue = set(), [start] # collections.deque([start])explored.add(start)while queue:v = queue.pop(0) # queue.popleft()for w in graph[v]:if w not in explored:explored.add(w)queue.append(w)return exploredG = {'A': ['B', 'C'],'B': ['A', 'D', 'E'],'C': ['A', 'F'],'D': ['B'],'E': ['B', 'F'],'F': ['C', 'E']}print(bfs(G, 'A'))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。