leetcode题目54. 螺旋矩阵

2022-02-16  本文已影响0人  castlet

题目描述

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

示例

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

代码

    private static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix == null || matrix.length <= 0) {
            return result;
        }
        int top = 0;
        int right = matrix[0].length - 1; //
        int left = 0;
        int bottom = matrix.length - 1; // 二维数组的lengh是行数
        int remainElementCount = matrix.length * matrix[0].length; // 二维数组中元素数量

        while (remainElementCount > 0) {
            // 从左上到右上
            for (int i = left; i <= right && remainElementCount > 0; i++ ) {
                result.add(matrix[top][i]);
                remainElementCount --;
            }
            top ++;

            // 从右上往右下
            for (int j = top; j <= bottom && remainElementCount > 0; j++ ) {
                result.add(matrix[j][right]);
                remainElementCount --;
            }
            right --;

            // 从右下到左下
            for (int k = right; k >= left && remainElementCount > 0; k -- ) {
                result.add(matrix[bottom][k]);
                remainElementCount --;
            }
            bottom --;

            // 从左下到左上
            for (int e = bottom; e >= top && remainElementCount > 0; e -- ) {
                result.add(matrix[e][left]);
                remainElementCount --;
            }
            left ++;
        }
        return result;
    }


上一篇下一篇

猜你喜欢

热点阅读