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

``````import Foundation;
/*
Swift 4 Program
*/
class Graph
{
var vertices: Int;
init(_ matrix: [[Int]])
{
self.vertices = matrix.count;
var i: Int = 0;
while (i < self.vertices)
{
i += 1;
}
}
func addEdge(_ u: Int, _ v: Int)
{
if (u < 0 || u >= self.vertices || v < 0 || v >= self.vertices)
{
return;
}
}
[Int]
])
{
var i: Int = 0;
while (i < self.vertices)
{
var j: Int = 0;
while (j < self.vertices)
{
if (matrix[i][j] == 1)
{
}
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
{
if (j  != 0)
{
print(" → ",separator :"", 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.