其他分享
首页 > 其他分享> > LeetCode54螺旋矩阵----模拟

LeetCode54螺旋矩阵----模拟

作者:互联网

题目表述

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

模拟

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();
        int highIndex = 0,lowIndex = matrix.length - 1;
        int leftIndex = 0,rightIndex = matrix[0].length -1;
        while(true){
            for(int i = leftIndex; i <= rightIndex;i++){
                res.add(matrix[highIndex][i]);
            }
            if(++highIndex > lowIndex){
                break;
            }
            for(int i = highIndex; i <= lowIndex;i++){
                res.add(matrix[i][rightIndex]);
            }
            if(--rightIndex < leftIndex) break;
            for(int i = rightIndex; i >= leftIndex;i--){
                res.add(matrix[lowIndex][i]);
            }
            if(--lowIndex < highIndex) break;
            for(int i = lowIndex; i >= highIndex;i--){
                res.add(matrix[i][leftIndex]);
            }
            if(++leftIndex > rightIndex) break;
        }
        return res;
    }
}

标签:LeetCode54,leftIndex,边界,int,lowIndex,矩阵,----,highIndex,matrix
来源: https://www.cnblogs.com/youngerwb/p/16184073.html