> ## Content Index
> Fetch the complete content index at: https://zyx322.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# 一天一道算法题（10）：螺旋矩阵的边界收缩思路与实现解析
- URL: https://zyx322.xyz/csdn-2026-08-14-38ac615a8549/
- Published: 2026-08-14T04:00:00.000Z
- Updated: 2026-11-26T07:02:02.000Z
- Author: ZYX
- Tags: 算法

### 一、题目描述

**LeetCode 54\. 螺旋矩阵**

给你一个 `m` 行 `n` 列的矩阵 `matrix` ，请按照 **顺时针螺旋顺序** ，返回矩阵中的所有元素。

**示例 1：**

```
输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出：[1,2,3,6,9,8,7,4,5]

```

**示例 2：**

```
输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出：[1,2,3,4,8,12,11,10,9,5,6,7]

```

**提示：**

- `m == matrix.length`
- `n == matrix[i].length`
- `1 <= m, n <= 10`
- `-100 <= matrix[i][j] <= 100`

### 二、思路分析

#### 1\. 题目的难点在哪？

这道题看起来简单，就是"转圈"遍历矩阵，但实现时容易出问题：

- **四个方向的边界控制**：向右、向下、向左、向上，每一步的边界条件都不一样
- **重复遍历或漏遍历**：边界没控制好，可能导致角落元素被重复添加或遗漏
- **只剩一行或一列时的处理**：如果矩阵不是方阵，最后可能只剩一行或一列，需要额外判断

#### 2\. 核心思路：边界收缩

我们可以用四个指针来表示当前未遍历区域的边界：

- `top`：上边界（行）
- `bottom`：下边界（行）
- `left`：左边界（列）
- `right`：右边界（列）

每次按顺序走完一圈（右→下→左→上），就把四个边界往内收缩一圈，直到所有元素都被遍历完。

**四个方向的遍历规则：**

| 方向 | 遍历范围                     | 遍历完后            |
| -- | ------------------------ | --------------- |
| 向右 | left → right，固定 top 行    | top++（上边界下移）    |
| 向下 | top → bottom，固定 right 列  | right--（右边界左移）  |
| 向左 | right → left，固定 bottom 行 | bottom--（下边界上移） |
| 向上 | bottom → top，固定 left 列   | left++（左边界右移）   |

**循环终止条件**：当 `top > bottom` 或 `left > right` 时，说明所有元素都已遍历完毕。

#### 3\. 特别注意事项

- **向左和向上遍历前，必须检查边界**：如果只剩一行，向左遍历完后，向上遍历会重复添加元素；如果只剩一列，同理。
- **循环条件用 `top <= bottom && left <= right`**，每次进入循环就遍历一圈，简洁明了。

### 三、Golang 代码实现

#### 版本一：边界收缩（推荐）

```go
func spiralOrder(matrix [][]int) []int {
    if len(matrix) == 0 || len(matrix[0]) == 0 {
        return []int{}
    }

    top, bottom := 0, len(matrix)-1
    left, right := 0, len(matrix[0])-1
    ret := make([]int, 0, (bottom+1)*(right+1))

    for top <= bottom && left <= right {
        // 1. 向右：从左到右，固定 top 行
        for i := left; i <= right; i++ {
            ret = append(ret, matrix[top][i])
        }
        top++

        // 2. 向下：从上到下，固定 right 列
        for i := top; i <= bottom; i++ {
            ret = append(ret, matrix[i][right])
        }
        right--

        // 3. 向左：从右到左，固定 bottom 行（需要检查是否还有行）
        if top <= bottom {
            for i := right; i >= left; i-- {
                ret = append(ret, matrix[bottom][i])
            }
            bottom--
        }

        // 4. 向上：从下到上，固定 left 列（需要检查是否还有列）
        if left <= right {
            for i := bottom; i >= top; i-- {
                ret = append(ret, matrix[i][left])
            }
            left++
        }
    }

    return ret
}

```

#### 版本二：使用 count 计数（另一种写法）

如果不想用边界检查，可以用 `count` 记录已遍历元素个数，用 `total` 控制循环：

```go
func spiralOrder(matrix [][]int) []int {
    if len(matrix) == 0 || len(matrix[0]) == 0 {
        return []int{}
    }

    top, bottom := 0, len(matrix)-1
    left, right := 0, len(matrix[0])-1
    total := (bottom + 1) * (right + 1)
    count := 0
    ret := make([]int, 0, total)

    for count < total {
        // 向右
        for i := left; i <= right && count < total; i++ {
            ret = append(ret, matrix[top][i])
            count++
        }
        top++

        // 向下
        for i := top; i <= bottom && count < total; i++ {
            ret = append(ret, matrix[i][right])
            count++
        }
        right--

        // 向左
        for i := right; i >= left && count < total; i-- {
            ret = append(ret, matrix[bottom][i])
            count++
        }
        bottom--

        // 向上
        for i := bottom; i >= top && count < total; i-- {
            ret = append(ret, matrix[i][left])
            count++
        }
        left++
    }

    return ret
}

```

#### 两种版本对比

| 版本            | 优点                   | 缺点                              |
| ------------- | -------------------- | ------------------------------- |
| 版本一（边界控制）     | 逻辑清晰，不需要 count，代码更短  | 向左/向上需要额外边界检查                   |
| 版本二（count 控制） | 统一用 count 退出，不需要边界检查 | 每个方向都多了一个 && count < total，略显冗余 |

**个人推荐版本一**，因为它更贴近"一圈一圈往里走"的物理意义，代码可读性更高。

### 四、复杂度分析

| 复杂度   | 值                   |
| ----- | ------------------- |
| 时间复杂度 | O(mn)，每个元素恰好被遍历一次   |
| 空间复杂度 | O(1)，除返回结果外只用了常数个变量 |

### 五、总结

**本题的核心考察点**：

1. **边界控制能力**：能否用四个指针精确控制矩阵的遍历范围。
2. **边界条件的处理**：当矩阵不是方阵时，能否正确处理只剩一行或一列的情况。
3. **模拟类问题的思路**：按顺序模拟"转圈"过程，关键是找到每一圈的起始和结束位置。

**易错点提醒**：

- 向左和向上遍历前，一定要检查边界，否则会重复遍历或越界。
- 循环条件用 `top <= bottom && left <= right`，确保每一圈都还有元素可遍历。
- 如果矩阵为空或包含空行，需要提前返回空切片。

---

**📌 专栏推荐**：更多算法题解，欢迎关注我的专栏。

**💬 互动**：如果你有更好的思路或疑问，欢迎在评论区留言讨论！

---