Running DFS and BFS on a Oriented Graph

Suppose we have a graph such as:

graph

If you need a path from 0 to 5, in what order we will visit the nodes, if we will perform DFS and BFS on this graph (suppose that the lowest element is always clicked first). I had problems with the concept of how the algorithms would work for a graph with loops, and I was hoping that someone could describe the procedure, each of which accepts such a graph.

+4
source share
1 answer

The common technique used to process loops has a set of peaks already visited. Before you push the vertex into the queue / stack, check if it has been visited. If this did not take any action, otherwise start by adding it to the visited set, and then continue the movement schedule.

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 

Similarly for BFS.

+3
source

All Articles