print graph
by thewolff
JavaScript
class Graph {
// defining vertex array and
// adjacent list
constructor(noOfVertices) {
this.noOfVertices = noOfVertices;
this.AdjList = new Map();
}
// functions to be implemented
// add vertex to the graph
addVertex(v) {
// initialize the adjacent list with a
// null array
this.AdjList.set(v, []);
}
addEdge(v, w) {
// get the list for vertex v and put the
// vertex w denoting edge betweeen v and w
this.AdjList.get(v).push(w);
// Since graph is undirected,
// add an edge from w to w also
this.AdjList.get(w).push(v);
}
// Prints the vertex and adjacency list
printGraph() {
// get all the vertices
var get_keys = this.AdjList.keys();
// iterate over the vertices
for (var i of get_keys) {
// great the corresponding adjacency list
// for the vertex
var get_values = this.AdjList.get(i);
var conc = "";
// iterate over the adjacency list
// concatenate the values into a string
for (var j of get_values)
conc += j + " ";
// print the vertex and its adjacency list
console.log(i + " -> " + conc);
}
}
// function to performs BFS
bfs(startingNode) {
// create a visited array
var visited = [];
for (var i = 0; i < this.noOfVertices; i++)
visited[i] = false;
// Create an object for queue
var q = new Queue();
// add the starting node to the queue
visited[startingNode] = true;
q.enqueue(startingNode);
// loop until queue is element
while (!q.isEmpty()) {
// get the element from the queue
var getQueueElement = q.dequeue();
// passing the current vertex to callback funtion
console.log(getQueueElement);
// get the adjacent...