Graph Functions (8)

Graph theory algorithms — shortest path, spanning trees, connectivity

adjacencyMatrix
Convert an edge list to an adjacency matrix.
Syntax
adjacencyMatrix(edges) | adjacencyMatrix(edges | n)
Type Signatures
Array, number, Array, number, Object, Array, Object
Parameters
NameTypeDescription
edgesArrayArray of edges: [[from, to], ...] or [[from, to, weight], ...]
nnumberNumber of nodes. Auto-detected from max node index if omitted.
optionsObjectOptions object. Supports `undirected` (boolean, default false).
Returns
Array — 2D array (n x n adjacency matrix)
Examples
adjacencyMatrix([[0
1
connectedComponents
Find all connected components of an undirected graph using BFS.
Syntax
connectedComponents(graph)
Parameters
NameTypeDescription
graphObjectUndirected adjacency list: { node: [neighbors], ... }
Returns
Array — Array of components, each component is an array of nodes
graphDistance
Find the shortest path distance between two nodes in a weighted directed graph.
Syntax
graphDistance(graph | start | end)
Type Signatures
Object, number, number, Object, string, string
Parameters
NameTypeDescription
graphObjectWeighted adjacency list: { node: [[neighbor, weight], ...], ... }
startstring|numberStart node
endstring|numberEnd node
Returns
number — Shortest distance, or Infinity if unreachable
isConnected
Check whether an undirected graph is connected.
Syntax
isConnected(graph)
Parameters
NameTypeDescription
graphObjectUndirected adjacency list: { node: [neighbors], ... }
Returns
boolean — True if the graph is connected, false otherwise
minimumSpanningTree
Find the minimum spanning tree of a weighted undirected graph using
Syntax
minimumSpanningTree(edges | n)
Type Signatures
Array, number
Parameters
NameTypeDescription
edgesArrayEdge list: [[from, to, weight], ...]
nnumberNumber of nodes
Returns
Array — Array of edges [[from, to, weight], ...] forming the MST
Examples
minimumSpanningTree([[0
1
1
shortestPath
Find the shortest path between two nodes in a weighted directed graph
Syntax
shortestPath(graph | start | end)
Type Signatures
Object, number, number, Object, string, string
Parameters
NameTypeDescription
graphObjectWeighted adjacency list: { node: [[neighbor, weight], ...], ... }
startstring|numberStart node
endstring|numberEnd node
Returns
Object — Object with `distance` (number) and `path` (Array of nodes)
stronglyConnectedComponents
Syntax
stronglyConnectedComponents(graph)
Parameters
NameTypeDescription
graphObjectDirected adjacency list: { node: [neighbors], ... }
Returns
Array — Array of SCCs, each SCC is an array of nodes
topologicalSort
Perform a topological sort on a directed acyclic graph (DAG) using
Syntax
topologicalSort(graph)
Parameters
NameTypeDescription
graphObjectDirected adjacency list: { node: [neighbors], ... }
Returns
Array — Nodes in topological order