Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Input: n = 1
Output: [[1]]
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
}