FZ12 牛牛的顺时针遍历
文章目录
题目描述
题解思路
通过一个变量来记录当前方向,遍历矩阵,每次遍历一条边,将该边的信息加入到结果中
题解代码
go
func spiralOrder(matrix [][]int) []int {
// write code here
m, n := len(matrix), len(matrix[0])
final := m * n
res := make([]int, 0, final)
// 0 >
// 1 v
// 2 <
// 3 ^
var direct int
for i := 0; i < final; {
switch direct {
case 0:
i += len(matrix[0])
res = append(res, matrix[0]...)
matrix = matrix[1:]
direct = 1
case 1:
h := len(matrix)
i += h
v := len(matrix[0]) - 1
for j := 0; j < h; j++ {
res = append(res, matrix[j][v])
matrix[j] = matrix[j][:v]
}
direct = 2
case 2:
v := len(matrix[0])
i += v
h := len(matrix) - 1
for j := v - 1; j >= 0; j-- {
res = append(res, matrix[h][j])
}
matrix = matrix[:h]
direct = 3
case 3:
h := len(matrix)
i += h
for j := h - 1; j >= 0; j-- {
res = append(res, matrix[j][0])
matrix[j] = matrix[j][1:]
}
direct = 0
}
}
return res
}