leetcode 54.螺旋矩阵Java

螺旋矩阵

  • 做题博客链接
  • 题目链接
  • 描述
  • 示例
  • 初始代码模板
  • 代码

做题博客链接

https://blog.csdn.net/qq_43349112/article/details/108542248

题目链接

https://leetcode-cn.com/problems/spiral-matrix/

描述

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

提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

示例

示例 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]

初始代码模板

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
       
    }
}

代码

一层层遍历就行,注意边界值

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new LinkedList<>();

        int left = 0;
        int up = 0;
        int right = matrix[0].length - 1;
        int down = matrix.length - 1;

        while (list.size() < matrix.length * matrix[0].length) {
            for (int i = left; i <= right && up <= down; i++) {
                list.add(matrix[up][i]);
            }
            up++;

            for (int i = up; i <= down && left <= right; i++) {
                list.add(matrix[i][right]);
            }
            right--;

            for (int i = right; i >= left && up <= down; i--) {
                list.add(matrix[down][i]);
            }
            down--;

            for (int i = down; i >= up && left <= right; i--) {
                list.add(matrix[i][left]);
            }
            left++;
        }

        return list;
    }
}

你可能感兴趣的:(leetcode刷题,算法,leetcode,java)