One of the most common and efficient ways to represent graphs is through an adjacency list.
An adjacency list is a way to represent graph data structures where each vertex (or node) stores a list of vertices it is connected to. It's often implemented as a dictionary or a Map
in JavaScript, where each key represents a vertex, and its value is an array of connected vertices. Thinking back to the concept of neighbors, we'll store each node's outgoing neighbors in its value array.
We can use a Map
or an object to create our adjacency list in JavaScript. Just note that if we decide to use an object, the keys would have to be strings. Since we are working with integers, a Map
is a better choice.
const adjList = new Map();
adjList.set(1, [2, 3]);
adjList.set(2, [4]);
adjList.set(3, [5]);
adjList.set(4, []);
adjList.set(5, [6]);
adjList.set(6, []);
Note that graphs can also be represented as an adjacency matrix, which is beyond the scope of this book.