力扣54.螺旋矩阵

54. 螺旋矩阵 - 力扣(LeetCode)

java 复制代码
class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> order = new ArrayList<Integer>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int rows = matrix.length, columns = matrix[0].length;

        // 四个边界:左、右、上、下
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;

        // 循环条件:还有圈可以遍历(左右边界不交叉,上下边界不交叉)
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                order.add(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; row++) {
                order.add(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    order.add(matrix[bottom][column]);
                }
                for (int row = bottom; row > top; row--) {
                    order.add(matrix[row][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }
}

是可以的,只要保证避免重复,具体边角处放在哪个循环是可以调整的

注意元素表示为:matrix行列,别混了,行即第几行,列同理

相关推荐
choumou_M3 小时前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen3 小时前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
心仪久了会沦陷5 小时前
C语言数据结构入门——树与二叉树详解:概念、堆实现与链式遍历
c语言·数据结构·算法
小此方5 小时前
[算法实战论:动态规划]背包问题概念,01不满背包问题,01满背包问题,背包问题的滚动数组空间优化
算法·动态规划
悠仁さん6 小时前
【C++】哈希表
c++·算法·散列表
地平线开发者7 小时前
点云算法整理与常用计算模块:从数据到模型,再到工程与量化
算法·自动驾驶
武子康9 小时前
H3-World 为何在加载 LoRA 前,先检查导入的代码?
人工智能·深度学习·算法
秋天的怀念_David10 小时前
算法一千零一夜 · 第二十八夜 注册
java·程序人生·算法
Rain的Java大神之路12 小时前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode