How does depth-first search work on a graph and how does it differ from trees?
LeetCode Patterns Flashcards: Graphs, BFS, DFS, Topological Sort, Union Find
Аудио-карточка · 0:25Nortren·
How does depth-first search work on a graph and how does it differ from trees?
0:25
DFS on a graph works the same as on trees, exploring as far as possible along each branch before backtracking. The critical difference is that graphs can have cycles, so you must track visited nodes to avoid infinite loops. Use a hash set of visited nodes and check before processing each neighbor. Mark a node as visited when you first encounter it, not when you finish processing it. DFS can be implemented recursively or iteratively with a stack. Time complexity is O of V plus E where V is vertices and E is edges.
neetcode.io