procedure explore(G,v)
Input: G=(V,E) is a graph; v ∈ V
Output: visited(u) is set to true for all nodes u reachable from v
visited(v) = true;
previsit(v)
for each edge (v,u) ∈ E:
if not visited(u): explore(u)
postvisit(v)
重写探索过程(上面),使其不是递归的(即显式使用堆栈)。调用previsit和postvisit的调用应该与递归过程具有相同的效果。
溶液:
procedure explore(G; u)
S = (empty stack)
push(S, u)
while S is not empty:
v = top(S)
if not visited[v]:
visited[v] = true
previsit(v)
if there is an edge (v; w) ∈ E with visited[w] = false:
push(S, w)
else: (we're done with v, the node at the top of the stack)
pop(S)
postvisit(v)
有人可以帮我理解这个伪代码,我不确定Stack在这种情况下是如何工作的。有人可以告诉我这段代码,所以我理解它是如何工作的