Suppose we have a graph such as:
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With