diff --git a/lib/alg/prim.ts b/lib/alg/prim.ts index 8c3f1720..c57c3f17 100644 --- a/lib/alg/prim.ts +++ b/lib/alg/prim.ts @@ -14,7 +14,7 @@ import type {Edge, WeightFunction} from '../types.js'; * @returns minimum spanning tree of graph. */ export function prim(graph: Graph, weightFn: WeightFunction): Graph { - const result = new Graph(); + const result = new Graph({directed: false}); const parents: Record = {}; const pq = new PriorityQueue(); let v: string; diff --git a/test/alg/prim-undirected-test.ts b/test/alg/prim-undirected-test.ts new file mode 100644 index 00000000..7b7c5dc5 --- /dev/null +++ b/test/alg/prim-undirected-test.ts @@ -0,0 +1,24 @@ +import {Graph} from '../../lib'; +import {dijkstra, prim} from '../../lib/alg'; + +describe('Prim spanning tree orientation', () => { + it('returns a tree that can be traversed from either endpoint', () => { + const graph = new Graph({directed: false}); + graph.setEdge('a', 'b', 1).setEdge('b', 'c', 2).setEdge('a', 'c', 10); + + const tree = prim(graph, edge => graph.edge(edge) as number); + + expect(tree.isDirected()).toBe(false); + expect(tree.edgeCount()).toBe(2); + expect(dijkstra(tree, 'a').c?.distance).toBe(2); + expect(dijkstra(tree, 'c').a?.distance).toBe(2); + }); + + it('returns undirected graphs for empty and single-node inputs', () => { + for (const graph of [new Graph(), new Graph().setNode('only')]) { + const tree = prim(graph, () => 1); + expect(tree.isDirected()).toBe(false); + expect(tree.nodes()).toEqual(graph.nodes()); + } + }); +});