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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,683 questions

55,435 answers

573 users

How to generate an n x n matrix filled with elements from 1 to N^2 in spiral order in VB.NET

1 Answer

0 votes
Imports System

Class SpiralMatrixGenerator
    Public Shared Function GenerateSpiralMatrix(ByVal n As Integer) As Integer(,)
        Dim matrix As Integer(,) = New Integer(n - 1, n - 1) {}
        Dim top As Integer = 0, bottom As Integer = n - 1
        Dim left As Integer = 0, right As Integer = n - 1
        Dim num As Integer = 1

        While top <= bottom AndAlso left <= right
            For i As Integer = left To right
                matrix(top, i) = Math.Min(System.Threading.Interlocked.Increment(num), num - 1)
            Next

            top += 1

            For i As Integer = top To bottom
                matrix(i, right) = Math.Min(System.Threading.Interlocked.Increment(num), num - 1)
            Next

            right -= 1

            If top <= bottom Then
				For i As Integer = right To left step -1
                    matrix(bottom, i) = Math.Min(System.Threading.Interlocked.Increment(num), num - 1)
                Next

                bottom -= 1
            End If

            If left <= right Then
				For i As Integer = bottom To top step -1
                    matrix(i, left) = Math.Min(System.Threading.Interlocked.Increment(num), num - 1)
                Next

                left += 1
            End If
        End While

        Return matrix
    End Function

    Public Shared Sub Main()
        Dim n As Integer = 3
        Dim spiralMatrix As Integer(,) = GenerateSpiralMatrix(n)

        For i As Integer = 0 To n - 1
            For j As Integer = 0 To n - 1
                Console.Write(spiralMatrix(i, j) & " ")
            Next
            Console.WriteLine()
        Next
    End Sub
End Class


 
' run:
'
' 1 2 3 
' 8 9 4 
' 7 6 5 
' 


 



answered Jun 24, 2025 by avibootz
...