Graph

graph~ Graph

The connection between two nodes in a graph is called an edge. Nodes are also referred to as vertices.

A graph can be directed or undirected. A directed graph has edges that allow traversing in one direction only. Whereas edges in an undirected graph are two-way and can be traversed freely.

Graphs can be cyclic or acyclic. A graph in which you can pass through a node more than once is called a cyclic graph. Those who don't share this characteristic are acyclic graphs.

Constructor

new Graph(directedopt)

Instantiates a graph.

Parameters:
Name Type Attributes Default Description
directed boolean <optional>
true

Edge direction. Set to false for an undirected graph.

Source:

Methods

addEdge(source, destination) → {Object}

Create a connection between source node and destination node. If the graph is undirected, it will also create the connection from destination to destination. If the nodes don't exist, they will be created anew with values set to source and destination respectively.

Return source/destination node pair as { source: GraphNode, destination: GraphNode }

Runtime: O(1)

Parameters:
Name Type Description
source any
destination any
Source:

addVertex(data) → {GraphNode}

Add a vertex to the graph. Returns the new vertex or the existing one if it already exists.

Runtime: O(1)

Parameters:
Name Type Description
data any
Source:

areNeighbours(source, destination) → {boolean}

Returns true if two nodes are adjacent to each other.

Parameters:
Name Type Description
source any

source node's value

destination any

destination node's value

Source:

removeEdge(source, destination)

Remove connection between source node and destination node. If the graph is undirected it will also remove the connection from destination to destination.

Returns true if deletion is successful, false if no such nodes exist.

Runtime: O(n) where n is the number of edges

Parameters:
Name Type Description
source any
destination any
Source:

removeVertex(data) → (nullable) {any}

Removes vertex with the given data from the graph. Returns the removed node's value or null if no such node was found.

Runtime: O(n) where n = number of vertices + number of edges

Parameters:
Name Type Description
data any
Source:

(generator) searchBreadthFirst(startValue)

Breadth-first search goes deep before going wide. Works the same as BinarySearchTree#searchBreadthFirst.

Parameters:
Name Type Description
startValue any

the value of the vertex to start the search from

Source:

(generator) searchDepthFirst(startValue)

Depth-first search goes deep before going wide. Works the same as BinarySearchTree#searchDepthFirst.

Parameters:
Name Type Description
startValue any

value of the vertex to start the search from

Source: