Spiral Matrix II
Description
Given a positive integer n, generate a square matrix filled with elements from 1 to in spiral order.
Example:
Solution
Idea: fill layer by layer. Suppose n = 4
.
Filling the first layer [1,8]
. First from left to right: 1,2,3
. Then from top to bottom: 4,5,6
. Then from right to left, 7,8,9
. Then from bottom to top: 10,11,12
.
Filling the second layer [13,16]
. Similar to filling the first layer.
Last updated