1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| func generateMatrix(n int) [][]int {
matrix := make([][]int, n)
for i := range matrix {
matrix[i] = make([]int, n)
}
top, bottom := 0, n-1
left, right := 0, n-1
num := 1
for top <= bottom && left <= right {
// 从左到右填充 top 行
for i := left; i <= right; i++ {
matrix[top][i] = num
num++
}
top++
// 从上到下填充 right 列
for i := top; i <= bottom; i++ {
matrix[i][right] = num
num++
}
right--
// 从右到左填充 bottom 行
if top <= bottom {
for i := right; i >= left; i-- {
matrix[bottom][i] = num
num++
}
bottom--
}
// 从下到上填充 left 列
if left <= right {
for i := bottom; i >= top; i-- {
matrix[i][left] = num
num++
}
left++
}
}
return matrix
}
|