-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathshortest-path.ts
More file actions
40 lines (35 loc) · 1.06 KB
/
shortest-path.ts
File metadata and controls
40 lines (35 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import type { CodeGraph } from '../model.js';
/**
* BFS-based shortest path on a CodeGraph.
*
* @returns Path from fromId to toId (inclusive), or null if unreachable
*/
export function shortestPath(graph: CodeGraph, fromId: string, toId: string): string[] | null {
const from = String(fromId);
const to = String(toId);
if (!graph.hasNode(from) || !graph.hasNode(to)) return null;
if (from === to) return [from];
const parent = new Map<string, string | null>();
parent.set(from, null);
const queue = [from];
let head = 0;
while (head < queue.length) {
const current = queue[head++]!;
for (const neighbor of graph.successors(current)) {
if (parent.has(neighbor)) continue;
parent.set(neighbor, current);
if (neighbor === to) {
// Reconstruct path
const path: string[] = [];
let node: string | null = to;
while (node !== null) {
path.push(node);
node = parent.get(node) ?? null;
}
return path.reverse();
}
queue.push(neighbor);
}
}
return null;
}