Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to print a given matrix in spiral form with VB.NET

1 Answer

0 votes
Imports System

Public Class Program
    Public Shared Sub PrintMatrixInSpiralForm(ByVal matrix As Integer()())
        If matrix Is Nothing OrElse matrix.Length = 0 Then
            Return
        End If

        Dim top As Integer = 0, bottom As Integer = matrix.Length - 1
        Dim left As Integer = 0, right As Integer = matrix(0).Length - 1

        While True
            If left > right Then
                Exit While
            End If

            For i As Integer = left To right
                Console.Write(matrix(top)(i) & " ")
            Next
            Console.Write(Environment.NewLine)
            top += 1

            If top > bottom Then
                Exit While
            End If

            For i As Integer = top To bottom
                Console.Write(matrix(i)(right) & " ")
            Next
            Console.Write(Environment.NewLine)
            right -= 1

            If left > right Then
                Exit While
            End If

				For i As Integer = right To left step -1
                Console.Write(matrix(bottom)(i) & " ")
            Next
            Console.Write(Environment.NewLine)
            bottom -= 1

            If top > bottom Then
                Exit While
            End If

				For i As Integer = bottom To top step -1
                Console.Write(matrix(i)(left) & " ")
            Next
            Console.Write(Environment.NewLine)
            left += 1
        End While
    End Sub

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




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

 



answered Sep 13, 2022 by avibootz

Related questions

1 answer 71 views
1 answer 75 views
1 answer 73 views
1 answer 88 views
1 answer 97 views
1 answer 91 views
1 answer 114 views
...