Topological sort using DFS without recursion

后端 未结 7 1535
悲哀的现实
悲哀的现实 2020-12-24 14:37

I know the common way to do a topological sort is using DFS with recursion. But how would you do it using stack instead of recursion? I need to obtai

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-24 15:20

    The node is 1st visited and is still in process, it's added to stack as false. These nodes are then processed from stack as LIFO, and changed to true (processed means children visited). After all children processed, while tracing path back, this node dropped from stack.

    For those trying to implement this code, visited[node.second]=true; should be moved to the 2 places where node is 1st added to stack as false. This, so that back edges leading to already traced vertices not revisited.

提交回复
热议问题