Description

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Example 2:

Input:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]

从外向内螺旋形遍历矩阵。

Solution

列出遍历的四方边界:leftrighttopbottom; 每次循环时,边界向中间收紧。

在循环中,分别遍历上边右边底边左边

 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
49
50
51
52
53
54
55
56
57
func spiralOrder(matrix [][]int) []int {
    // 矩阵有效性判断
    row := len(matrix)
    if row == 0 {
        return nil
    }
    col := len(matrix[0])
    if col == 0 {
        return nil
    }

    res := make([]int, row*col)
    idx := 0

    append_ans := func(x, y int) {
        res[idx] = matrix[x][y]
        idx++
    }

    // 边界:left, right, top, bottom
    l, r := 0, col-1
    t, b := 0, row-1

    for l <= r && t <= b {
        // 从左往右遍历top行
        for i := l; i <= r; i++ {
            append_ans(t, i)
        }

        // 从上往下遍历right列
        for i := t + 1; i < b; i++ {
            append_ans(i, r)
        }

        if t < b {
            // 从右往左遍历bottom行
            for i := r; i >= l; i-- {
                append_ans(b, i)
            }
        }

        if l < r {
            // 从下往上遍历left列
            for i := b - 1; i > t; i-- {
                append_ans(i, l)
            }
        }

        // 收紧边界
        l++
        r--
        t++
        b--
    }

    return res
}

Similar Problem