Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/alg/prim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {};
const pq = new PriorityQueue();
let v: string;
Expand Down
24 changes: 24 additions & 0 deletions test/alg/prim-undirected-test.ts
Original file line number Diff line number Diff line change
@@ -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());
}
});
});
Loading