VB.net program to traverse a matrix in Spiral Form

Rajnilari2015
Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 216
Let's say we have a 4*4 matrix with the elements as

{1,2,3,4}
{5,6,7,8}
{9,10,11,12}
{13,14,15,16}


The objective is to visit this matrix in spiral manner such that the output will be

1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10


The below code will do so

Imports System.Collections.Generic
Imports System.Linq

Namespace ConsoleApplication2
Class Program
Shared res As New List(Of Integer)()

Private Shared Sub Main(args As String())
Dim row As Integer = 4
Dim col As Integer = 4
Dim matrix As Integer(,) = New Integer(3, 3) {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}

Dim lstStr As New List(Of String)()

RowConstantColVary(0, 3, matrix)
ColConstantRowVary(3, 3, matrix)
RowConstantColVaryReverse(3, 2, matrix)
ColConstantRowVaryReverse(2, 0, matrix)
RowConstantColVary(1, 2, matrix)
RowConstantColVaryReverse(2, 2, matrix)

res.Take((row * col)).ToList().ForEach(Function(i) Console.Write(i + " "))

Console.ReadKey()

End Sub

Private Shared Sub RowConstantColVary(startRow As Integer, endCol As Integer, matrix As Integer(,))
For j As Integer = startRow To endCol
res.Add(matrix(startRow, j))
Next

End Sub
Private Shared Sub ColConstantRowVary(endRow As Integer, startCol As Integer, matrix As Integer(,))
For i As Integer = 1 To endRow
res.Add(matrix(i, startCol))
Next

End Sub
Private Shared Sub RowConstantColVaryReverse(startRow As Integer, endCol As Integer, matrix As Integer(,))
For j As Integer = endCol To 0 Step -1
res.Add(matrix(startRow, j))
Next

End Sub

Private Shared Sub ColConstantRowVaryReverse(endRow As Integer, startCol As Integer, matrix As Integer(,))
For i As Integer = endRow To endRow - 1 Step -1
res.Add(matrix(i, startCol))
Next

End Sub
End Class
End Namespace

Comments or Responses

Login to post response