graph & directed graph implementation in javascript
Package Exports
@datastructures-js/graph
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@datastructures-js/graph) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
adds an edge with a weight between two existings vertices. Default weight is 1 if not defined. The edge is a direction from source to destination when added in a directed graph, and a connecting two-way edge when added in a graph.
checks if the graph has an edge between two existing vertices. In directed graph, it returns true only if there is a direction from source to destination.
gets the edge's weight between two vertices in the graph. If there is no direct edge between the two vertices, it returns null. It also returns 0 if the source key is equal to destination key.
removes all connected edges to a vertex by its key.
params
name
type
description
key
number or string
the vertex key
return
description
number
number of removed edges
runtime
Graph
O(K) : K = number of connected edges to the vertex
Directed Graph
O(E) : E = number of edges in the graph
Example
const dg =newDirectedGraph();
dg.addVertex('v1');
dg.addVertex('v2');
dg.addVertex('v3');
dg.addEdge('v1','v2');
dg.addEdge('v2','v1');// this is counted as a direction in directed graph.
dg.addEdge('v1','v3');
dg.removeEdges('v1');// 3const g =newGraph();
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addEdge('v1','v2');
g.addEdge('v1','v3');
g.removeEdges('v1');// 2
.traverseDfs(srcKey, cb)
traverses the graph using the depth-first recursive search.