anris05's picture
bot
8a2dcce
Raw
History Blame Contribute Delete
2.02 kB
TOPIC: DFS
DEFINITION: Depth-First Search (DFS) is a traversal algorithm used to search and explore nodes in a graph or tree data structure. It works by visiting a node and then exploring as far as possible along each of its edges before backtracking, allowing it to efficiently search for a target node or perform other operations. This approach helps solve problems that require examining all possible paths from a given starting point.
TIME_COMPLEXITY: The time complexity of DFS is O(V + E), where V is the number of vertices (nodes) and E is the number of edges, because in the worst case, it visits each node and edge once.
SPACE_COMPLEXITY: The space complexity of DFS is O(h), where h is the height of the tree (or the maximum depth of the recursion call stack), because it needs to store the current path being explored.
USE_WHEN: DFS is the right tool when you need to search for a node in a graph or tree, or when you need to perform an operation that requires exploring all possible paths from a given starting point. It's particularly useful in scenarios where the graph is very deep but not very wide.
AVOID_WHEN: DFS is a poor choice when the graph is very wide and you're looking for the shortest path, as it can get stuck exploring a long branch before backtracking; in such cases, Breadth-First Search (BFS) is a better option.
EXAMPLE:
Suppose we have a tree with the following structure:
A
/ \
B C
/ \ \
D E F
We start a DFS from node A:
1. Visit A
2. Explore B:
- Visit B
- Explore D:
- Visit D
- Explore E:
- Visit E
3. Backtrack to A, then explore C:
- Visit C
- Explore F:
- Visit F
The final result is: A, B, D, E, C, F
Result:
REAL_WORLD_ANALOGY: DFS is like exploring a maze by always going as far as you can down a path before turning back, which allows you to systematically cover all areas without getting lost.
SOURCE_NOTE: Concepts referenced from general knowledge of graph traversal algorithms.