力扣热题100-------54. 螺旋矩阵

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

示例 1:
力扣热题100-------54. 螺旋矩阵_第1张图片

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

力扣热题100-------54. 螺旋矩阵_第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]

提示:

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

思路: 我们先创建一个数组 用于返回结果 定义四个变量 开始行 结束行 开始列 结束列 然后我们使用一个while循环来确保他的某一行或某一列还没有遍历 接着执行 从左到右 从上到下 从右到左 从下到上的依次遍历 注意 每次遍历完需要更改四个条件

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int row=matrix.length;
        int col=matrix[0].length;
        int startRow=0;
        int startCol=0;
        int endRow=row-1;
        int endCol=col-1;
        List<Integer> integers = new ArrayList<>();

        while (startRow<=endRow && startCol<=endCol){
            for (int i = startCol; i <=endCol; i++) {
                integers.add(matrix[startRow][i]);
            }
            startRow++;

            for (int i = startRow; i <= endRow; i++) {
                integers.add(matrix[i][endCol]);
            }
            endCol--;

            if (endRow>=startRow){
            for (int i =  endCol; i >=startCol ; i--) {
                integers.add(matrix[endRow][i]);
            }
            endRow--;
            }

            if (endCol>=startCol){
                for (int i = endRow; i >= startRow; i--) {
                    integers.add(matrix[i][startCol]);
                }
                startCol++;
            }

        }
        return integers;
    }
} 

你可能感兴趣的:(力扣,leetcode,矩阵,java)