Chapter 40: Depth-First Search

前言

DFS利用了backtrack (move a step back)的技巧,也是因為這個技巧,需要用到stack這個資料結構。

There are a lot of applications for DFS:

  • Topological sorting.

  • Detecting a cycle.

  • Path finding, such as in maze puzzles.

  • Finding connected components in a sparse graph.

大綱

  • Example

  • Implementation

  • Performance

Example

Stack, Pushed, Visted 這三個等會在code中被使用到

As long as the stack is not empty, you visit the top vertex on the stack and push the first neighboring vertex that has yet to be

The next vertex to visit is C. It has neighbors [A, F, G], but all of these have been visited. You have reached a dead end, so it’s time to backtrack by popping C off the stack.

Implementation

Performance

  • Overall, the time complexity for depth-first search is O(V + E).

    • DFS will visit every single vertex at least once. This has a time complexity of O(V).

    • you have to check all neighboring vertices to find one available to visit. The time complexity of this is O(E)

  • The space complexity of depth-first search is O(V) since you have to store vertices in three separate data structures: stack, pushed and visited

Last updated