Breadth-First Search
Breadth-First Search
1. BFS in Graph
(1) Summary
Create adjacent list or adjacent matrix (prefer adjacent list since it is more space efficient) to build the graph mode given the relations
If each node can only be visited once, we should use an boolean array to check if the node has been visited
Pop a node from queue, and iterate over the node's neighbors and put them to the queue
(2) Template
2. BFS in Matrix
(1) Summary
Every cell in the matrix will be visited only once using BFS
Can calculate the distance to a given cell: Shortest Distance from All Buildings
If every cell can be visited only once, we can use either a boolean array to check if a cell has been visited or change the current value in the cell to avoid visiting it again: Surrounded Regions, (Here, we can flip the character 'O' to a special character '#' so that we won't visit the same cell again)
(2) Template
3. Time & Space Complexity
Time: O(V) , where V is the number of nodes in the graph
Space: O(V)
4. Questions Category
Graph: Graph Valid Tree
Last updated