DSA · Intermediate · Pattern 8 of 10
Graphs: BFS & DFS
17 problems.
Your progress0%
- 1st Visit
- 0/17
- 2nd Visit
- 0/17
- Revise
- 0/17
About this pattern
A graph is a set of nodes joined by edges; grids, state spaces and number transformations are often graphs in disguise. Depth-first search explores as far as possible before backtracking and suits connectivity, counting components, flood fill and paths in trees. Breadth-first search explores in layers from one or several sources and gives shortest paths when every edge has the same cost.
Signals include connected regions in a grid, processes that spread step by step, and the fewest operations needed to reach a target. Store the graph as an adjacency list, mark a node visited when it is first discovered, and expect O(V + E) time.
// Multi-source BFS on a grid; dist = -1 means unvisited.
int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
vector<vector<int>> dist(R, vector<int>(C, -1));
queue<pair<int, int>> q;
for (auto [r, c] : sources) { dist[r][c] = 0; q.push({r, c}); }
while (!q.empty()) {
auto [r, c] = q.front(); q.pop();
for (int d = 0; d < 4; ++d) {
int nr = r + dr[d], nc = c + dc[d];
if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;
if (dist[nr][nc] != -1 || blocked(nr, nc)) continue;
dist[nr][nc] = dist[r][c] + 1;
q.push({nr, nc});
}
}