graph: 7 nodes, 8 edgessource = "A"expected [0,1,1,2,2,3,4]

Loading 3D view…

7 nodes, 8 edges; start at A

step 1 / 132

Solution

TypeScript · line 1
function bfs(graph: Graph, source: string): (number | null)[] {
  const adj = new Map(graph.nodes.map((v): [string, string[]] => [v, []]));
  for (const [u, v] of graph.edges) {
    adj.get(u)!.push(v);
    adj.get(v)!.push(u);
  }
  const dist = graph.nodes.map((): number | null => null);
  const at = (v: string) => graph.nodes.indexOf(v);
  dist[at(source)] = 0;
  const queue = [source];
  while (queue.length > 0) {
    const u = queue.shift()!;
    for (const v of adj.get(u)!) {
      if (dist[at(v)] === null) {
        dist[at(v)] = dist[at(u)]! + 1;
        queue.push(v);
      }
    }
  }
  return dist;
}