Skip to main content

Construct adjacency list by using adjacency matrix in swift

Swift program for Construct adjacency list by using adjacency matrix. Here problem description and other solutions.

import Foundation;
/*
    Swift 4 Program
    Construct adjacency list using adjacency matrix
*/
class Graph
{
    var vertices: Int;
    var adgeList: [[Int]];
    init(_ matrix: [[Int]])
    {
        self.vertices = matrix.count;
        self.adgeList = [[Int]]()
        var i: Int = 0;
        while (i < self.vertices)
        {
            self.adgeList.append([Int]());
            i += 1;
        }
        self.makeAdjacencyList(matrix);
    }
    func addEdge(_ u: Int, _ v: Int)
    {
        if (u < 0 || u >= self.vertices || v < 0 || v >= self.vertices)
        {
            return;
        }
        // Add node edge
        self.adgeList[u].append(v);
    }
    func makeAdjacencyList(_ matrix: [
        [Int]
    ])
    {
        var i: Int = 0;
        while (i < self.vertices)
        {
            var j: Int = 0;
            while (j < self.vertices)
            {
                if (matrix[i][j] == 1)
                {
                    self.addEdge(i, j);
                }
                j += 1;
            }
            i += 1;
        }
    }
    // Display graph nodes and edges
    func printGraph()
    {
        print("\n Graph Adjacency List ", terminator: "");
        var i: Int = 0;
        while (i < self.vertices)
        {
            print(" \n [", i ,"] : ",separator :"", terminator: "");
            var j: Int = 0;
            // iterate edges of i node
            while (j < self.adgeList[i].count)
            {
                if (j  != 0)
                {
                    print(" → ",separator :"", terminator: "");
                }
                print("", self.adgeList[i][j], terminator: "");
                j += 1;
            }
            i += 1;
        }
    }
}
func main()
{
    let matrix: [
        [Int]
    ] = [
        [0, 1, 1, 0, 1],
        [1, 0, 1, 0, 1],
        [1, 1, 0, 1, 0],
        [0, 1, 0, 0, 1],
        [1, 1, 0, 1, 0]
    ];
    let g: Graph = Graph(matrix);
    // Display graph element
    g.printGraph();
}
main();

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