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

前端 未结 13 1812
情话喂你
情话喂你 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:18

    A DFS without recursion is basically the same as BFS - but use a stack instead of a queue as the data structure.

    The thread Iterative DFS vs Recursive DFS and different elements order handles with both approaches and the difference between them (and there is! you will not traverse the nodes in the same order!)

    The algorithm for the iterative approach is basically:

    DFS(source):
      s <- new stack
      visited <- {} // empty set
      s.push(source)
      while (s is not empty):
        current <- s.pop()
        if (current is in visited):
            continue
        visited.add(current)
        // do something with current
        for each node v such that (current,v) is an edge:
            s.push(v)
    

提交回复
热议问题