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

1.思路:模拟顺时针打印的过程,从{0, 0}开始。遍历矩阵,最开始是向右,当row或者col超过下标或者元素已经被访问,则改变访问的方向。
2.代码:
class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)return new int[0];
        //模拟顺时针打印矩阵
        int rows = matrix.length, cols = matrix[0].length;
        //结果
        int[] res = new int[rows * cols];
        //标记矩阵中的元素是否打印
        boolean[][] vis = new boolean[rows][cols];
        int row = 0, col = 0;
        //表示向右,向下,向左,向上四个方向
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        //方向索引,便于访问directions,irectionIndex = 0, 1, 2, 3即代表了向右,向下,向左,向上四个方向
        int directionIndex = 0;
        for(int i = 0 ; i < rows * cols; i++){
            res[i] = matrix[row][col];
            vis[row][col] = true;
            int nexRow = row + directions[directionIndex][0];
            int nexCol = col + directions[directionIndex][1];
            //判断是否需要改变方向
            //下一个row或col超出下标或已经访问,则需要改变方向
            if(nexRow < 0 || nexRow >= rows || nexCol < 0 || nexCol >= cols || vis[nexRow][nexCol]){
                directionIndex = (directionIndex + 1) % 4;
            }
            row += directions[directionIndex][0];
            col += directions[directionIndex][1];
        }
    return res;
    }
}
3.复杂度分析:时间0(mn),m,n分别是矩阵的行和列,空间o(mn),需要欸外的vis数组。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值