Skip to main content

Construct adjacency list by using adjacency matrix in kotlin

Kotlin program for Construct adjacency list by using adjacency matrix. Here more information.

/*
    Kotlin Program
    Construct adjacency list using adjacency matrix
*/
class Graph
{
    var vertices: Int;
    var adgeList: MutableList < MutableList < Int >>  ;
    constructor(matrix: Array < Array < Int >> )
    {
        this.vertices = matrix.count();
        this.adgeList = mutableListOf();
        var i: Int = 0;
        while (i < this.vertices)
        {
            this.adgeList.add(mutableListOf < Int > ());
            i += 1;
        }
        this.makeAdjacencyList(matrix);
    }
    fun addEdge(u: Int, v: Int): Unit
    {
        if (u < 0 || u >= this.vertices || 
            v < 0 || v >= this.vertices)
        {
            return;
        }
        // Add node edge
        this.adgeList[u].add(v);
    }
    fun makeAdjacencyList(matrix: Array < Array < Int >> ): Unit
    {
        var i: Int = 0;
        while (i < this.vertices)
        {
            var j: Int = 0;
            while (j < this.vertices)
            {
                if (matrix[i][j] == 1)
                {
                    this.addEdge(i, j);
                }
                j += 1;
            }
            i += 1;
        }
    }
    // Display graph nodes and edges
    fun printGraph(): Unit
    {
        print("\n Graph Adjacency List ");
        var i: Int = 0;
        while (i < this.vertices)
        {
            print(" \n [" + i + "] : ");
            var j: Int = 0;
            // iterate edges of i node
            while (j < this.adgeList[i].size)
            {
                if (j != 0)
                {
                    print(" → ");
                }
                print("" + this.adgeList[i][j]);
                j += 1;
            }
            i += 1;
        }
    }
}
fun main(args: Array < String > ): Unit
{
    val matrix: Array < Array < Int >> = arrayOf(
      arrayOf(0, 1, 1, 0, 1), 
      arrayOf(1, 0, 1, 0, 1), 
      arrayOf(1, 1, 0, 1, 0), 
      arrayOf(0, 1, 0, 0, 1), 
      arrayOf(1, 1, 0, 1, 0)
    );
    val g: Graph = Graph(matrix);
    // Display graph element
    g.printGraph();
}

Output

 Graph Adjacency List
 [0] : 1 → 2 → 4
 [1] : 0 → 2 → 4
 [2] : 0 → 1 → 3
 [3] : 1 → 4
 [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