LCP 54.螺旋矩阵

这篇博客介绍了如何实现矩阵的螺旋顺序遍历,提供了解题思路和多种编程语言的代码实现,包括Python、C和C++。解题关键在于按顺时针方向逐层遍历矩阵,对于单行或单列的情况进行特殊处理。适合熟悉矩阵操作和递归算法的读者阅读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目简述

给你一个 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

标记难度

难度:中等
通过次数:158025
提交次数:335,777
通过率:47.1%

问题解析

本题主要考察矩阵的遍历,还涉及到递归、矩阵转置等知识。

最直观的方法就是按圈遍历矩阵,从外到里一圈一圈遍历,即先遍历矩阵的最外圈,然后递归地遍历其子矩阵的最外圈。要注意的是,单行或单列需要特殊处理。

python3代码

class Solution(object):
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 
    	row, col = len(matrix), len(matrix[0])
        def getOutermostCircle(row_start, row_end, col_start, col_end): 
            if row_start > row_end or col_start > col_end:# 防错
                return []
            elif row_start == row_end: #单行
                circle = []
                for j in range(col_start, col_end+1): # 上边
                    circle.append(matrix[row_start][j])
                return circle
                # return matrix[row_start][col_start:col_end+1]
            elif col_start == col_end: #单列
                circle = []
                for i in range(row_start, row_end+1):
                    circle.append(matrix[i][col_start])
                return circle
            else: # 多行多列
                circle = []
                for j in range(col_start, col_end+1): # 上边
                    circle.append(matrix[row_start][j])
                    # circle.extend(matrix[row_start][col_start:col_end+1])
                for i in range(row_start+1, row_end): # 右边
                    circle.append(matrix[i][col_end])
                for j in range(col_end, col_start-1, -1): # 下边
                    circle.append(matrix[row_end][j])
                    # circle.extend(reversed(matrix[row_end][col_start:col_end+1]))
                for i in range(row_end-1, row_start, -1): # 左边
                    circle.append(matrix[i][col_start])
                return circle + getOutermostCircle(row_start+1, row_end-1, col_start+1, col_end-1) # 拼接

        return getOutermostCircle(0, row-1, 0, col-1)

C语言代码(官方)

int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize) {
    if (matrixSize == 0 || matrixColSize[0] == 0) {
        *returnSize = 0;
        return NULL;
    }

    int rows = matrixSize, columns = matrixColSize[0];
    int total = rows * columns;
    int* order = malloc(sizeof(int) * total);
    *returnSize = 0;

    int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
    while (left <= right && top <= bottom) {
        for (int column = left; column <= right; column++) {
            order[(*returnSize)++] = matrix[top][column];
        }
        for (int row = top + 1; row <= bottom; row++) {
            order[(*returnSize)++] = matrix[row][right];
        }
        if (left < right && top < bottom) {
            for (int column = right - 1; column > left; column--) {
                order[(*returnSize)++] = matrix[bottom][column];
            }
            for (int row = bottom; row > top; row--) {
                order[(*returnSize)++] = matrix[row][left];
            }
        }
        left++;
        right--;
        top++;
        bottom--;
    }
    return order;
}

C++(官方)

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};
        }

        int rows = matrix.size(), columns = matrix[0].size();
        vector<int> order;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                order.push_back(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; row++) {
                order.push_back(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    order.push_back(matrix[bottom][column]);
                }
                for (int row = bottom; row > top; row--) {
                    order.push_back(matrix[row][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }
};

大佬专属代码

def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        while matrix:
            res += matrix.pop(0)
            matrix = list(zip(*matrix))[::-1]
        return res

敲黑板!!!
熟练掌握矩阵、列表的各种函数或方法!!!

凉梦空间

欢迎你进入我的个人博客网站参观交流:https://www.liangmeng.xyz
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凉丶梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值