Creating the Graph class
As usual, we will declare the basic structure of our class:
class Graph { constructor(isDirected = false) { this.isDirected = isDirected; // {1} this.vertices = []; // {2} this.adjList = new Dictionary(); // {3} } }
The Graph
constructor can receive a parameter to indicate if the graph is directed or not ({1}
), and by default, the graph will not be directed. We will use an array to store the names of all the vertices of the graph ({2}
), and we will use a dictionary (implemented in Chapter 8, Dictionaries and Hashes) to store the adjacent list ({3}
). The dictionary will use the name of the vertex as a key and the list of adjacent vertices as a value.
Next, we will implement two methods: one to add a new vertex to the graph (because when we instantiate the graph, it will create an empty graph with no vertices), and another method to add edges between the vertices. Let's implement the addVertex
method first, as follows:
addVertex(v) { if (!this.vertices...