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
...