MemotivaLeetCode Patterns Flashcards: Graphs, BFS, DFS, Topological Sort, Union Find

How does breadth-first search work on a graph?

LeetCode Patterns Flashcards: Graphs, BFS, DFS, Topological Sort, Union Find

Аудио-карточка · 0:26

Nortren·

How does breadth-first search work on a graph?

0:26

BFS explores all neighbors at the current distance before moving to the next distance level, using a queue. Start by enqueuing the source node and marking it visited. While the queue is not empty, dequeue a node, process it, and enqueue all unvisited neighbors, marking them visited. BFS guarantees finding the shortest path in unweighted graphs because it discovers nodes in order of their distance from the source. Track distance by processing the queue level by level, counting levels. Time complexity is O of V plus E.
neetcode.io