top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Program for traversing a directed graph through DFS, visiting only vertices reachable from start vertex.

+2 votes
330 views
Program for traversing a directed graph through DFS, visiting only vertices reachable from start vertex.
posted Apr 20, 2016 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Input: A graph G and a vertex v of G
Output: All vertices reachable from v labeled as discovered

A recursive implementation of DFS:

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

A non-recursive implementation of DFS:

1  procedure DFS-iterative(G,v):
2      let S be a stack
3      S.push(v)
4      while S is not empty
5            v = S.pop()
6            if v is not labeled as discovered:
7                label v as discovered
8                for all edges from v to w in G.adjacentEdges(v) do
9                    S.push(w)

Source: https://en.wikipedia.org/wiki/Depth-first_search

answer Apr 20, 2016 by Salil Agrawal
Similar Questions
0 votes

Given a graph and a source node and destination node, find the number of shortest paths present between source and destination?

+2 votes

Can someone explain in simple terms with example what is the BFS and what is DFS. In what situation BFS would be more useful then DFS or vice-versa.

...