0
点赞
收藏
分享

微信扫一扫

【LeetCode】剑指 Offer 29. 顺时针打印矩阵

老北京的热干面 2022-01-23 阅读 39

题目链接:剑指 Offer 29. 顺时针打印矩阵
题目描述:
在这里插入图片描述
解法:和蛇形填数差不多思想,进行模拟。定义上下左右四个变量模拟即可,具体见代码。

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }
        int index=0;
        int right=matrix[0].length,bottom=matrix.length; //右和下
        int left=0,top=0; //左和上
        int []res=new int[right*bottom];
        right--;
        bottom--;
        while(left<=right&&top<=bottom){
            for(int i=left;i<=right;i++) res[index++]=matrix[top][i]; //左到右
            top++;
            for(int i=top;i<=bottom;i++) res[index++]=matrix[i][right]; //上到下
            right--;
            for(int i=right;i>=left&&top<=bottom;i--) res[index++]=matrix[bottom][i]; //右到左
            bottom--;
            for(int i=bottom;i>=top&&left<=right;i--) res[index++]=matrix[i][left]; //下到上
            left++;
        }
        return res;
    }
}
举报

相关推荐

0 条评论