Posted on by Kalkicode
Code Graph

Adjacency list representation of undirected graph in scala

Scala program for Adjacency list representation of undirected graph. Here problem description and explanation.

/*
    Scala Program for 
    Undirected graph representation by using adjacency list 
*/
class AjlistNode(
	// Vertices node key
	var id: Int,
		var next: AjlistNode)
{
	def this(id: Int)
	{
		// Set value of node key
		this(id, null);
	}
}
class Vertices(var data: Int,
	var next: AjlistNode,
		var last: AjlistNode)
{
	def this(data: Int)
	{
		this(data, null, null);
	}
}
class Graph(
	// Number of Vertices
	var size: Int,
		var node: Array[Vertices])
{
	def this(size: Int)
	{
		// Set value
		this(size, Array.fill[Vertices](size)(null));
        this.setData();
	}
	// Set initial node value
	def setData(): Unit = {
		if (size <= 0)
		{
			println("\nEmpty Graph");
		}
		else
		{
			var index: Int = 0;
			while (index < size)
			{
				node(index) = new Vertices(index);
				index += 1;
			}
		}
	}
	// Connect two nodes
	def connect(start: Int, last: Int): Unit = {
		var edge: AjlistNode = new AjlistNode(last);
		if (node(start).next == null)
		{
			node(start).next = edge;
		}
		else
		{
			// Add edge at the end
			node(start).last.next = edge;
		}
		// Get last edge 
		node(start).last = edge;
	}
	//  Handling the request of adding new edge
	def addEdge(start: Int, last: Int): Unit = {
		if (start >= 0 && start < size && 
             last >= 0 && last < size)
		{
			connect(start, last);
			if (start == last)
			{
				// When self loop
				return;
			}
			connect(last, start);
		}
		else
		{
			// When invalid nodes
			println("\nHere Something Wrong");
		}
	}
	def printGraph(): Unit = {
		if (size > 0)
		{
			var index: Int = 0;
			// Print graph ajlist Node value
			while (index < size)
			{
				print("\nAdjacency list of vertex " + index + " :");
				var temp: AjlistNode = node(index).next;
				while (temp != null)
				{
					// Display graph node 
					print("  " + node(temp.id).data);
					// Visit to next edge
					temp = temp.next;
				}
				index += 1;
			}
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		// 5 implies the number of nodes in graph
		var g: Graph = new Graph(5);
		// Connect node with an edge
		g.addEdge(0, 1);
		g.addEdge(0, 2);
		g.addEdge(0, 4);
		g.addEdge(1, 2);
		g.addEdge(1, 4);
		g.addEdge(2, 3);
		g.addEdge(3, 4);
		// print graph element
		g.printGraph();
	}
}

Output

Adjacency list of vertex 0 :  1  2  4
Adjacency list of vertex 1 :  0  2  4
Adjacency list of vertex 2 :  0  1  3
Adjacency list of vertex 3 :  2  4
Adjacency list of vertex 4 :  0  1  3

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