"""pseudo-code""""""DFS(graph G, start vertex s):// all nodes initially unexploredmark s as exploredfor every edge (s, v):if v unexplored:DFS(G, v)"""def dfs(graph, start):"""The DFS function simply calls itself recursively for every unvisited child of its argument. We can emulate thatbehaviour precisely using a stack of iterators. Instead of recursively calling with a node, we'll push an iteratorto the node's children onto the iterator stack. When the iterator at the top of the stack terminates, we'll popit off the stack."""explored, stack = set(), [start]explored.add(start)while stack:v = stack.pop() # the only difference from BFS is to pop last element here instead of first onefor w in graph[v]:if w not in explored:explored.add(w)stack.append(w)return exploredG = {'A': ['B', 'C'],'B': ['A', 'D', 'E'],'C': ['A', 'F'],'D': ['B'],'E': ['B', 'F'],'F': ['C', 'E']}print(dfs(G, 'A'))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。