59. Spiral Matrix II ⭐

Medium
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example 1:
​
​
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
  • 1 <= n <= 20

解題

這題基本上跟 54.Spiral Matrix 差不多!只是改成把數字填進去。
func generateMatrix(n int) [][]int {
count := 1
colBegin, colEnd := 0, n - 1
rowBegin, rowEnd := 0, n - 1
​
ans := make([][]int, 0)
for i:=0; i<n; i++ {
ans = append(ans, make([]int, n) )
}
fmt.Println(ans)
​
for rowBegin <= rowEnd && colBegin <= colEnd {
// 往右邊
for i := colBegin; i <= colEnd; i++ {
ans[rowBegin][i] = count
count++
}
rowBegin++
​
// 往下
for i := rowBegin; i <= rowEnd; i++ {
ans[i][colEnd] = count
count++
}
colEnd--
​
// 往左
if rowBegin <= rowEnd {
for i := colEnd; i >= colBegin; i-- {
ans[rowEnd][i] = count
count++
}
}
rowEnd--
​
// 往上
if colBegin <= colEnd {
for i := rowEnd; i >= rowBegin; i-- {
ans[i][colBegin] = count
count++
}
}
colBegin++
}
return ans
}