Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing DFS and BFS on a directed graph

Suppose we have a graph such as:

graph

If you wanted a path from 0 to 5, in what order will we visit the nodes if we perform DFS and BFS on this graph (assume the lowest element is always pushed first). I'm having trouble conceptualizing how the algorithms will work for a graph with cycles, and I was hoping someone could outline the procedure each takes on such a graph.

like image 961
Bob John Avatar asked Apr 28 '13 08:04

Bob John


People also ask

Do BFS and DFS work for directed graphs?

BFS and DFS work on both directed and undirected graphs, as shown in the figures above. If the underlying graph is disconnected, BFS and DFS can only traverse the connected component that the given starting node belongs to. BFS cannot be used to find shortest paths on weighted graphs. See Dijkstra's algorithm for that!

Can you do DFS on a directed graph?

Depth First Search (DFS) is a systematic way of visiting the nodes of either a directed or an undirected graph. As with breadth first search, DFS has a lot of applications in many problems in Graph Theory. It comprises the main part of many graph algorithms. DFS visits the vertices of a graph in the following manner.


1 Answers

Common technique which is used to deal with cycles is having set of already visited vertices. Before you push vertex to the queue/stack check if it was visited. If it was don't do any action, otherwise start from adding it to visited set and then continue traversing graph.

Stack from top to bottom.

DFS:

empty stack
visiting 0: stack: 2, 1, visited: 0
visiting 2: stack: 5, 3, 1 visited: 0, 2
visiting 5: stack: 4, 3, 1 visited: 0, 2, 5
visiting 4: stack: 3, 2, 3, 1 visited: 0, 2, 4, 5
visiting 3: stack: 4, 2, 3, 1 visited: 0, 2, 3, 4, 5
visiting 4: (nothing to do) - stack: 2, 3, 1 visited: 0, 2, 3, 4, 5
visiting 2: (nothing to do) - stack: 3, 1 visited: 0, 2, 3, 4, 5
visiting 3: (nothing to do) - stack: 3, 1 visited: 0, 2, 3, 4, 5
visiting 1: stack: 3, 0 visited: 0, 1, 2, 3, 4, 5
visiting 3: (nothing to do) - stack: 1 visited: 0, 1, 2, 3, 4, 5
visiting 1: (nothing to do) - stack empty visited: 0, 1, 2, 3, 4, 5
DONE

In similar fashion do for BFS.

like image 95
Adrian Avatar answered Sep 20 '22 15:09

Adrian