-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerateMatrix.go
More file actions
48 lines (43 loc) · 913 Bytes
/
Copy pathgenerateMatrix.go
File metadata and controls
48 lines (43 loc) · 913 Bytes
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
47
48
/* https://leetcode.com/problems/spiral-matrix-ii/description/
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
package larray
func generateMatrix(n int) [][]int {
matrix := make([][]int, n)
for i := range matrix {
matrix[i] = make([]int, n, n)
}
count := 1
rowStart, rowEnd, colStart, colEnd := 0, n-1, 0, n-1
for count <= n*n {
for i := colStart; i <= colEnd; i++ {
matrix[rowStart][i] = count
count++
}
rowStart++
for j := rowStart; j <= rowEnd; j++ {
matrix[j][colEnd] = count
count++
}
colEnd--
for i := colEnd; i >= colStart; i-- {
matrix[rowEnd][i] = count
count++
}
rowEnd--
for j := rowEnd; j >= rowStart; j-- {
matrix[j][colStart] = count
count++
}
colStart++
}
return matrix
}