# 漫画：一文看懂螺旋矩阵求解

[

[1, 2, 3, 4],

[5, 6, 7, 8],

[9,10,11,12]

]

up := 0
down := len(matrix) - 1
left := 0
right := len(matrix[0]) - 1


03

Go语言示例

 1func spiralOrder(matrix [][]int) []int {
2    var result []int
3    if len(matrix) == 0 {
4        return result
5    }
6    left, right, up, down := 0, len(matrix[0])-1, 0, len(matrix)-1
7    var x, y int
8    for left <= right && up <= down {
9        for y = left; y <= right && avoid(left, right, up, down); y++ {
10            result = append(result, matrix[x][y])
11        }
12        y--
13        up++
14        for x = up; x = left && avoid(left, right, up, down); y-- {
20            result = append(result, matrix[x][y])
21        }
22        y++
23        down--
24        for x = down; x >= up && avoid(left, right, up, down); x-- {
25            result = append(result, matrix[x][y])
26        }
27        x++
28        left++
29    }
30    return result
31}
32
33func avoid(left, right, up, down int) bool {
34    return up <= down && left <= right
35}