Given a positive integer n, generate an n × n matrix filled with elements from 1 to n² in spiral order (clockwise from the top-left).
n = 3[[1,2,3],[8,9,4],[7,6,5]]n = 4[[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]top=0, bottom=n-1, left=0, right=n-1, num=1mat[top][c] = num++, then top++mat[r][right] = num++, then right--mat[bottom][c] = num++, then bottom--mat[r][left] = num++, then left++num > n² — boundaries shrink inward each passThe four boundaries (top, right, bottom, left) define the current unfilled shell. After traversing each edge we shrink that boundary inward, so the next iteration fills the next inner ring. This is identical to reading Spiral Matrix I — except we write sequential integers instead of reading existing values.