Graph algorithms
Reachability examples use adjacency lists indexed 0 through V−1 and a valid starting vertex s. Mark before enqueuing.
| BFS or DFS | O(V + E) | Adjacency lists; start additional searches for other components |
| Dijkstra | Nonnegative edge weights | Use a min-priority queue |
| Bellman–Ford | O(VE) | Can detect reachable negative cycles |
| Kruskal | O(E log E) | Sort edges and skip edges joining the same component |
Python
from collections import deque
def reachable(adj, s):
seen, q = {s}, deque([s])
while q:
for v in adj[q.popleft()]:
if v not in seen:
seen.add(v)
q.append(v)
return seenC++
std::vector<bool> reachable(const std::vector<std::vector<int>>& adj, int s) {
std::vector<bool> seen(adj.size()); std::queue<int> q;
q.push(s); seen[s] = true;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) if (!seen[v]) { seen[v] = true; q.push(v); }
}
return seen;
}Java
static boolean[] reachable(int[][] adj, int s) {
boolean[] seen = new boolean[adj.length];
java.util.ArrayDeque<Integer> q = new java.util.ArrayDeque<>();
q.add(s); seen[s] = true;
while (!q.isEmpty()) {
for (int v : adj[q.remove()]) if (!seen[v]) { seen[v] = true; q.add(v); }
}
return seen;
}