BFS explores level by level and finds the shortest path in an unweighted graph. DFS goes deep first and is handy for traversals, cycle detection, and topological-style problems.
function bfs(start: number, graph: number[][]) {
const q: number[] = [start];
const seen = new Set<number>([start]);
while (q.length) {
const v = q.shift()!;
for (const n of graph[v]) {
if (!seen.has(n)) {
seen.add(n);
q.push(n);
}
}
}
}