简体   繁体   中英

Performing DFS and BFS on a directed graph

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM