[LeetCode] 54. 螺旋矩阵

给定一个包含m*n个元素的mn列矩阵(m,n),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

示例 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]

思路:

每个边的遍历方向是固定的, 可以理解为四种连续的遍历操作, 只能费力地全部写出来了。

AC代码:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) return {};
        
        int m = matrix.size();      // 行数
        int n = matrix[0].size();   // 列数
        
        // 定义四个边界
        int top = 0, bottom = m - 1;
        int left = 0, right = n - 1;
        
        vector<int> result;
        
        while (top <= bottom && left <= right) {
            // 1. 从左到右遍历上边
            for (int j = left; j <= right; j++) {
                result.push_back(matrix[top][j]);
            }
            top++;  // 上边界下移
            
            // 2. 从上到下遍历右边
            for (int i = top; i <= bottom; i++) {
                result.push_back(matrix[i][right]);
            }
            right--;  // 右边界左移
            
            // 3. 从右到左遍历下边(需要检查是否还有行)
            if (top <= bottom) {
                for (int j = right; j >= left; j--) {
                    result.push_back(matrix[bottom][j]);
                }
                bottom--;  // 下边界上移
            }
            
            // 4. 从下到上遍历左边(需要检查是否还有列)
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    result.push_back(matrix[i][left]);
                }
                left++;  // 左边界右移
            }
        }
        
        return result;
    }
};Code language: C++ (cpp)