diff --git a/src/game/chase/hexGraph.ts b/src/game/chase/hexGraph.ts index 6361d78..e4011ca 100644 --- a/src/game/chase/hexGraph.ts +++ b/src/game/chase/hexGraph.ts @@ -16,19 +16,21 @@ export function shortestPathLength( from: NodeId, to: NodeId, ): number { - if (from === to) { - return 0; - } - if (!graph.nodes[from] || !graph.nodes[to]) { return Infinity; } + if (from === to) { + return 0; + } + const queue: Array<[NodeId, number]> = [[from, 0]]; + let head = 0; const visited = new Set([from]); - while (queue.length > 0) { - const [current, distance] = queue.shift()!; + while (head < queue.length) { + const [current, distance] = queue[head]; + head += 1; const node = graph.nodes[current]; for (const neighbor of node.neighbors) { @@ -54,9 +56,11 @@ export function isConnected(graph: GameGraph): boolean { const start = nodeIds[0]; const visited = new Set([start]); const queue: NodeId[] = [start]; + let head = 0; - while (queue.length > 0) { - const current = queue.shift()!; + while (head < queue.length) { + const current = queue[head]; + head += 1; const node = graph.nodes[current]; for (const neighbor of node.neighbors) { diff --git a/tests/chase/hexGraph.test.ts b/tests/chase/hexGraph.test.ts index d8fd6de..2ee9f4c 100644 --- a/tests/chase/hexGraph.test.ts +++ b/tests/chase/hexGraph.test.ts @@ -48,6 +48,17 @@ describe("hex graph utilities", () => { expect(shortestPathLength(graph, "A", "C")).toBe(Infinity); }); + it("returns Infinity for invalid from/to nodes", () => { + const graph = buildGraph({ + A: { id: "A", q: 0, r: 0, neighbors: ["B"] }, + B: { id: "B", q: 1, r: 0, neighbors: ["A"] }, + }); + + expect(shortestPathLength(graph, "X", "X")).toBe(Infinity); + expect(shortestPathLength(graph, "X", "A")).toBe(Infinity); + expect(shortestPathLength(graph, "A", "X")).toBe(Infinity); + }); + it("checks graph connectivity", () => { const connectedGraph = buildGraph({ A: { id: "A", q: 0, r: 0, neighbors: ["B"] }, @@ -64,4 +75,14 @@ describe("hex graph utilities", () => { expect(isConnected(connectedGraph)).toBe(true); expect(isConnected(disconnectedGraph)).toBe(false); }); + + it("treats empty and single-node graph as connected", () => { + const emptyGraph = buildGraph({}); + const singleNodeGraph = buildGraph({ + A: { id: "A", q: 0, r: 0, neighbors: [] }, + }); + + expect(isConnected(emptyGraph)).toBe(true); + expect(isConnected(singleNodeGraph)).toBe(true); + }); });