edgeTo[] 存储从起点到一个顶点的已知路径上的最后一个顶点。s: 起点。 e: 终点。
dfs: 递归调用。
def dfs(G: Graph, v: int) -> int:
visited[v] = True
for w in G.adj(v):
if not visited[w]:
edgeTo[w] = v
dfs(G, w)
def pathTo(e: int) -> list:
path = list()
x = e
while x != s:
path.append(x)
x = edgeTo[x]
path.append(s)
return path
bfs:可以找到最短路径。 不是递归调用,不隐式的调用栈,显式的使用队列。
def bfs(G: graph, s: int):
visited[s] = True
q = collections.deque()
q.append(s)
while q:
v = q.popleft()
for w in G.adj(v):
if not visited[w]:
edgeTo[w] = v
visited[w] = True
q.append(w)
def pathTo(e: int) -> list:
path = list()
x = e
while x != s:
path.append(x)
x = edgeTo[x]