54. 螺旋矩阵

Posted hequnwang10

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了54. 螺旋矩阵相关的知识,希望对你有一定的参考价值。

一、题目描述

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

示例 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) 
        List<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) 
            return res;
        
        int top = 0,buttom = matrix.length-1,left = 0,right = matrix[0].length-1;
        int m = matrix.length,n = matrix[0].length;
        int sum = m*n;
        int index = 0;

        while(index < sum)
            //上下左右开始遍历
            //从左往右遍历
            for(int i = left;i<=right;i++)
                res.add(matrix[top][i]);
                index++;
            
            top++;
            //判断是否越界
            if(top > buttom)
                break;
            
            //从上往下遍历
            for(int i = top;i<=buttom;i++)
                res.add(matrix[i][right]);
                index++;
            
            right--;
            //判断是否越界
            if(left > right)
                break;
            
            //从右往左遍历
            for(int i = right;i >= left;i--)
                res.add(matrix[buttom][i]);
                index++;
            
            buttom--;
            //判断是否越界
            if(top > buttom)
                break;
            
            for(int i = buttom;i>=top;i--)
                res.add(matrix[i][left]);
                index++;
            
            left++;
            //判断是否越界
            if(left > right)
                break;
            
        
        return res;
    

时间复杂度:O(n);

空间复杂度:O(n)。

开发者涨薪指南 48位大咖的思考法则、工作方式、逻辑体系

以上是关于54. 螺旋矩阵的主要内容,如果未能解决你的问题,请参考以下文章

54. 螺旋矩阵

54. 螺旋矩阵

54. 螺旋矩阵

LeetCode:螺旋矩阵54

Leetcode 54:Spiral Matrix 螺旋矩阵

Leetcode 54.螺旋矩阵