Construct adjacency list by using adjacency matrix in vb.net
Vb program for Construct adjacency list by using adjacency matrix. Here more information.
' Include namespace system
Imports System
Imports System.Collections.Generic
' Vb.net program for
' Construct adjacency list using adjacency matrix
public Class Graph
Public vertices As Integer
Public adgeList As List(Of List(Of Integer))
Public Sub New(ByVal matrix As Integer(,))
' Set number of nodes
Me.vertices = matrix.GetLength(0)
Me.adgeList = New List(Of List(Of Integer))(matrix.Length)
' Create memory of adgeList of each vertice
Dim i As Integer = 0
While i < Me.vertices
Me.adgeList.Add(New List(Of Integer)())
i += 1
End While
Me.makeAdjacencyList(matrix)
End Sub
' Convert into adjacency list
Public Sub makeAdjacencyList(ByVal matrix As Integer(,))
Dim i As Integer = 0
While i < Me.vertices
Dim j As Integer = 0
While j < Me.vertices
if (matrix(i,j) = 1) Then
Me.addEdge(i, j)
End If
j += 1
End While
i += 1
End While
End Sub
Public Sub addEdge(ByVal u As Integer, ByVal v As Integer)
if (u < 0 OrElse u >= Me.vertices OrElse
v < 0 OrElse v >= Me.vertices) Then
Return
End If
' Add node edge
Me.adgeList(u).Add(v)
End Sub
' Display graph nodes and edges
Public Sub printGraph()
Console.Write( vbLf &" Graph Adjacency List ")
Dim i As Integer = 0
While i < Me.vertices
Console.Write(" "& vbLf &" [" + i.ToString() + "] :")
' iterate edges of i node
Dim j As Integer = 0
While j < Me.adgeList(i).Count
if (j <> 0) Then
Console.Write(" → ")
End If
Console.Write(" {0}",Me.adgeList(i)(j))
j += 1
End While
i += 1
End While
End Sub
Public Shared Sub Main(ByVal args As String())
Dim matrix As Integer(,) =
{
{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}}
Dim g As Graph = New Graph(matrix)
' Display graph element
g.printGraph()
End Sub
End Class
Output
Graph Adjacency List
[0] : 1 → 2 → 4
[1] : 0 → 2 → 4
[2] : 0 → 1 → 3
[3] : 1 → 4
[4] : 0 → 1 → 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