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
'