Adjacency list representation of directed graph in typescript
Ts program for Adjacency list representation of directed graph. Here problem description and explanation.
/*
TypeScript Program for
Directed graph representation using adjacency list
*/
class AjlistNode
{
// Vertices node key
public id: number;
public next: AjlistNode;
constructor(id: number)
{
// Set value of node key
this.id = id;
this.next = null;
}
}
class Vertices
{
public data: number;
public next: AjlistNode;
public last: AjlistNode;
constructor(data: number)
{
this.data = data;
this.next = null;
this.last = null;
}
}
class Graph
{
// Number of Vertices
public size: number;
public node: Vertices[];
constructor(size: number)
{
// Set value
this.size = size;
this.node = Array(size).fill(null);
this.setData();
}
// Set initial node value
public setData()
{
if (this.size <= 0)
{
console.log("\nEmpty Graph");
}
else
{
for (var index = 0; index < this.size; index++)
{
// Set initial node value
this.node[index] = new Vertices(index);
}
}
}
// Connect two nodes
public connect(start: number, last: number)
{
var edge = new AjlistNode(last);
if (this.node[start].next == null)
{
this.node[start].next = edge;
}
else
{
// Add edge at the end
this.node[start].last.next = edge;
}
// Get last edge
this.node[start].last = edge;
}
// Handling the request of adding new edge
public addEdge(start: number, last: number)
{
if (start >= 0 && start < this.size && last >= 0 && last < this.size)
{
// Safe connection
this.connect(start, last);
}
else
{
// When invalid nodes
console.log("\nHere Something Wrong");
}
}
public printGraph()
{
if (this.size > 0)
{
// Print graph ajlist Node value
for (var index = 0; index < this.size; ++index)
{
console.log("\nAdjacency list of vertex " + index + " :");
var temp = this.node[index].next;
while (temp != null)
{
// Display graph node
console.log(" " + this.node[temp.id].data);
// visit to next edge
temp = temp.next;
}
}
}
}
public static main(args: string[])
{
// 5 implies the number of nodes in graph
var g = new Graph(5);
// Connect node with an edge
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(1, 4);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(4, 3);
// print graph element
g.printGraph();
}
}
Graph.main([]);
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/
Output
Adjacency list of vertex 0 :
1
Adjacency list of vertex 1 :
2
4
Adjacency list of vertex 2 :
0
3
Adjacency list of vertex 3 :
Adjacency list of vertex 4 :
3
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