How to implement depth first search for graph with a non-recursive approach

前端 未结 13 1753
情话喂你
情话喂你 2020-11-28 22:00

I have spent lots of time on this issue. However, I can only find solutions with non-recursive methods for a tree: Non recursive for tree, or a recursive method for the grap

相关标签:
13条回答
  • 2020-11-28 22:27

    I think this is an optimized DFS regarding space-correct me if I am wrong.

    s = stack
    s.push(initial node)
    add initial node to visited
    while s is not empty:
        v = s.peek()
        if for all E(v,u) there is one unvisited u:
            mark u as visited
            s.push(u)
        else 
            s.pop
    
    0 讨论(0)
提交回复
热议问题