Deep-First Search

Iterative

procedure DFS-iterative(G,v):
      let S be a stack
      S.push(v)
      while S is not empty
          v = S.pop()
          if v is not labeled as visited:
              label v as visited
              for all edges from v to w in G.adjacentEdges(v) do 
                  S.push(w)

Recursive

procedure DFS(G,v):
      label v as visited
      for all edges from v to w in G.adjacentEdges(v) do
          if vertex w is not labeled as visited then
              recursively call DFS(G,w)

Code

Last updated