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);
}
}
}
}Both algorithms visit each vertex/edge at most a constant number of times, so the baseline time is O(V+E). The difference is order and the data structure.