Posted on by Kalkicode
Code Graph

Implement adjacency list in directed graph using array in node js

Js program for Implement adjacency list in directed graph. Here problem description and other solutions.

/*
    Node JS Program
    Efficiently implementing adjacency list in directed graph
*/
class Graph
{
	constructor(vertices)
	{
		this.vertices = vertices;
		this.adgeList = [];
		for (var i = 0; i < this.vertices; ++i)
		{
			this.adgeList.push([]);
		}
	}
	addEdge(u, v)
	{
		if (u < 0 || u >= this.vertices || 
            v < 0 || v >= this.vertices)
		{
			return;
		}
		// add node edge
		this.adgeList[u].push(v);
	}
	// Display graph nodes and edges
	printGraph()
	{
		process.stdout.write("\n Graph Adjacency List ");
		for (var i = 0; i < this.vertices; ++i)
		{
			process.stdout.write(" \n [" + i + "] :");
			// iterate edges of i node
			for (var j = 0; j < this.adgeList[i].length; j++)
			{
				process.stdout.write("  " + this.adgeList[i][j]);
			}
		}
	}
}

function main()
{
	var g = new Graph(10);
	g.addEdge(0, 1);
	g.addEdge(0, 2);
	g.addEdge(0, 7);
	g.addEdge(1, 5);
	g.addEdge(1, 7);
	g.addEdge(2, 3);
	g.addEdge(2, 7);
	g.addEdge(3, 4);
	g.addEdge(3, 8);
	g.addEdge(4, 9);
	g.addEdge(5, 6);
	g.addEdge(5, 8);
	g.addEdge(6, 8);
	g.addEdge(6, 9);
	g.addEdge(7, 8);
	// Display graph element
	g.printGraph();
}
// Start program execution
main();

Output

 Graph Adjacency List
 [0] :  1  2  7
 [1] :  5  7
 [2] :  3  7
 [3] :  4  8
 [4] :  9
 [5] :  6  8
 [6] :  8  9
 [7] :  8
 [8] :
 [9] :

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment