力扣练习之螺旋矩阵

我爱海鲸 2023-07-16 23:22:19 高级算法

简介高级、力扣、给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-hard/xw3ng2/

解法一(python):

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix:
            return []

        m, n = len(matrix), len(matrix[0])
        result = []

        top, bottom = 0, m - 1
        left, right = 0, n - 1

        while len(result) < m * n:
            # 从左到右
            for j in range(left, right + 1):
                result.append(matrix[top][j])
            top += 1

            if len(result) == m * n:
                break

            # 从上到下
            for i in range(top, bottom + 1):
                result.append(matrix[i][right])
            right -= 1

            if len(result) == m * n:
                break

            # 从右到左
            for j in range(right, left - 1, -1):
                result.append(matrix[bottom][j])
            bottom -= 1

            if len(result) == m * n:
                break

            # 从下到上
            for i in range(bottom, top - 1, -1):
                result.append(matrix[i][left])
            left += 1

        return result

思路:

  1. 初始化一个空列表 result 用于存储螺旋顺序的元素。

  2. 初始化四个变量 topbottomleftright 分别表示当前螺旋区域的边界。

  3. 使用一个循环来遍历矩阵中的元素,直到 result 的长度等于矩阵元素的总数。

  4. 在每一轮循环中,按照顺时针的顺序遍历当前螺旋区域的元素,并将其添加到 result 中。

  5. 更新螺旋区域的边界:上边界 top 向下移动一行;右边界 right 向左移动一列;下边界 bottom 向上移动一行;左边界 left 向右移动一列。

你好:我的2025

上一篇:go语言学习之包的使用

下一篇:Rust入门