Authored by Tony Feng
Created on April 5th, 2022
Last Modified on April 5th, 2022
Understanding DFS
Intro
- Depth-first search is an algorithm for traversing or searching tree or graph data structures.
- The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking.
- The time complexity of DFS if the entire tree is traversed is O(V), where V is the number of nodes; In the case of a graph, the time complexity is O(V + E), where V is the number of vertexes and E is the number of edges.
Steps of DFS
- Create a recursive function that takes the index of the node and a visited array.
- Mark the current node as visited and print the node.
- Traverse all the adjacent and unmarked nodes and call the recursive function with the index of the adjacent node.
Template
|
|
Examples
Leetcode 78 Subsets
|
|
Leetcode 200 Number of Islands
|
|
Leetcode 102 Binary Tree Level Order Traversal
|
|
Reference
- 手把手带你刷Leetcode力扣 - 深度优先搜索 DFS
- 手把手带你刷Leetcode力扣 - Leetcode 938
- 手把手带你刷Leetcode力扣 - Leetcode 200
- Depth First Search or DFS for a Graph
- Depth First Search (DFS)
- What is Depth First Search?