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

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

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
在这里插入图片描述

思路分析:依据题意,是顺时针打印矩阵,所以打印方向就是右、下、左、上。一直重复这个过程直到打印结束。所以我们可以定义一个direction方向数组,以及visit访问数组,如果已经访问过了,或者访问的索引越界了,我们就更新方向。

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new int[0];
        }
        // rows columns and total
        int rows = matrix.length;
        int columns = matrix[0].length;
        int total = rows * columns;
        int[] result = new int[total];
        // directions right down left up
        int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};
        // visit
        boolean[][] visist = new boolean[rows][columns];
        int direction_index = 0;
        int row = 0,column = 0;

        for(int i = 0;i < total;i++){
            // print
            result[i] = matrix[row][column];
            //update the visit
            visist[row][column] = true;
            // check the index
            int next_row = row + direction[direction_index][0];
            int next_column = column + direction[direction_index][1];

            if(next_column < 0 || next_column >= columns || next_row < 0 || next_row >= rows || visist[next_row][next_column]){
                // change the direction
                direction_index = (direction_index + 1) % 4;
            }

            // update the row and column
            row += direction[direction_index][0];
            column += direction[direction_index][1];
        }

        return result;
    }
}

很明显,如果矩阵的大小是mn,那么时间复杂度是O(mn),而由于题目要求返回数组,所以空间复杂度是O(1);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值