Graphs

Palistha
2 min readJun 13, 2022

--

One way to create a graph is with the help of the Adjacent list.

An adjacent list is just the list of vertices the vertex is connected to.

We will create a Graph with adjacent lists.

For this, we will create an object

Where vertex will be keys

And its vertices it is connected to will be its values.

class Graph { 
constructor() {
this.numberOfNodes = 0;
this.adjacentList = {};
}
}

Add vertices to the Graph

Now, we will create a method to add vertices to the graph. Vertices will be stored as keys of objects.

addVertex(node) {
this.adjacentList[node] = [];
this.numberOfNodes++;
}

Initially, the value of the object will be an empty array. An array because we need to store more than one value.

Adding adjacent list

addEdge(node1, node2) {
this.adjacentList[node1].push(node2);
this.adjacentList[node2].push(node1);
}

We will just push a value to key. As it is undirected graph, we will do it both ways.

For example,

addEdge(0, 1)will connect the vertices 0 and 1.

Where 0 is the key and 1 is value. And also vice-versa.

Complete Code

class Graph { 
constructor() {
this.numberOfNodes = 0;
this.adjacentList = {};
}
addVertex(node) {
this.adjacentList[node] = [];
this.numberOfNodes++;
}
addEdge(node1, node2) {
this.adjacentList[node1].push(node2);
this.adjacentList[node2].push(node1);
}

}
var myGraph = new Graph();
myGraph.addVertex(0);
myGraph.addVertex(1);
myGraph.addVertex(2);
myGraph.addVertex(3);
// add adjacent list
// creates connection from 0 to 2 and vice-versa
myGraph.addEdge(0, 2);
myGraph.addEdge(1, 2);
myGraph.addEdge(2, 3);
console.log(myGraph);

Output

Graph {numberOfNodes: 4,adjacentList: { ‘0’: [ 2 ], ‘1’: [ 2 ], ‘2’: [ 0, 1, 3 ], ‘3’: [ 2 ] }}

--

--

Palistha
Palistha

Written by Palistha

Learning and Sharing Everyday

No responses yet