leetcode-54.螺旋矩阵(易理解)

要按照顺时针螺旋顺序遍历一个矩阵,可以通过逐步缩小矩阵的边界来实现。具体步骤如下:

  1. 从矩阵的左上角开始,沿着上边界从左到右遍历一行。
  2. 然后沿着右边界从上到下遍历一列。
  3. 如果还有剩余行,沿着下边界从右到左遍历一行。
  4. 如果还有剩余列,沿着左边界从下到上遍历一列。
  5. 缩小边界,重复以上步骤,直到遍历完整个矩阵。

以下是一个用 Java 实现的示例代码:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length == 0) {
            return result;
        }

        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        while (top <= bottom && left <= right) {
            // Traverse from left to right along the top row
            for (int i = left; i <= right; i++) {
                result.add(matrix[top][i]);
            }
            top++;

            // Traverse from top to bottom along the right column
            for (int i = top; i <= bottom; i++) {
                result.add(matrix[i][right]);
            }
            right--;

            // Traverse from right to left along the bottom row, if there is a bottom row
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    result.add(matrix[bottom][i]);
                }
                bottom--;
            }

            // Traverse from bottom to top along the left column, if there is a left column
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    result.add(matrix[i][left]);
                }
                left++;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println(solution.spiralOrder(matrix)); // 输出: [1, 2, 3, 6, 9, 8, 7, 4, 5]
    }
}

解释

  • 边界定义:使用 top, bottom, left, right 四个变量来定义当前未遍历区域的边界。
  • 循环条件:在 top <= bottomleft <= right 的条件下循环,确保在每一次迭代中只遍历未访问的区域。
  • 遍历顺序:顺时针依次遍历上边界、右边界、下边界和左边界。
  • 更新边界:每次遍历完一条边界后,缩小相应的边界。

这种方法能够有效地遍历矩阵中的所有元素,并且时间复杂度为 (O(m \times n)),其中 (m) 和 (n) 分别是矩阵的行数和列数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

看个人简介有交流群(付费)

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

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

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

打赏作者

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

抵扣说明:

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

余额充值