1
BFS and DFS ★★★★★
Algorithm
BFS (Breadth First Search) visits level by level with a queue; it finds the shortest path in an unweighted graph. DFS (Depth First Search) goes as deep as possible with a stack / recursion; used for cycle detection, topological sort, connected components. Both are O(V + E).
BFS spreads out, DFS dives down one branch first
void bfs(int start, vector<vector<int>> &adj) {
vector<bool> visited(adj.size(), false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int u = q.front(); q.pop();
cout << u << " ";
for (int v : adj[u])
if (!visited[v]) { visited[v] = true; q.push(v); }
}
}
void dfs(int u, vector<vector<int>> &adj, vector<bool> &visited) {
visited[u] = true;
cout << u << " ";
for (int v : adj[u])
if (!visited[v]) dfs(v, adj, visited);
}