【剑指offer】顺时针打印矩阵

题目链接

acwing
leetcode

题目描述

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

数据范围矩阵中元素数量 [0,400]。

输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

解题

用偏移量的思想来做!
在这里插入图片描述

  1. 所以定义偏移量数组
    • dx[] = {-1, 0, 1, 0} //dx存x的偏移量
    • dy[] = {0, 1, 0, -1} //dy存y的偏移量
  2. 枚举四个方向的时候,for循环i从0开始枚举到<4
  3. 求枚举后的新的坐标 a=x+dx[i] b=y+dy[i]
  4. 什么时候更换方向:当越界或者a,b的下标已经存在值之后 更换方向

代码实现

class Solution {
    int[] dx = {0, 1, 0, -1};
    int[] dy = {1, 0, -1, 0};
    public int[] printMatrix(int[][] matrix) {
        // 初始方向
        int d = 0;
        int xlength = matrix.length;
        if(xlength == 0) return new int[0];
        int ylength = matrix[0].length;
        
        int[] res = new int[xlength * ylength];
        boolean[][] visit = new boolean[xlength][ylength];
        
        int x = 0, y = 0;
        for(int i = 0; i < xlength*ylength; i ++){
            visit[x][y] = true;
            res[i] = matrix[x][y];
            
            int xNext = x + dx[d];
            int yNext = y + dy[d];
            
            if(xNext < 0 || xNext >= xlength || yNext < 0 || yNext >= ylength || visit[xNext][yNext]){
                d = (d + 1) % 4;
                xNext = x + dx[d];
                yNext = y + dy[d];
            }
            
            x = xNext;
            y = yNext;
        }
        
        return res;
    }
}

相关推荐

  1. offer A + B

    2024-03-27 18:08:02       37 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-27 18:08:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-27 18:08:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-27 18:08:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-27 18:08:02       20 阅读

热门阅读

  1. leetcode 栈和队列1

    2024-03-27 18:08:02       14 阅读
  2. 数据共享(InheritedWidget)

    2024-03-27 18:08:02       14 阅读
  3. 设计模式之装饰器模式

    2024-03-27 18:08:02       14 阅读
  4. 蓝桥杯真题训练 包子凑数(数论)

    2024-03-27 18:08:02       18 阅读
  5. C++之std::mem_fn使用和实现原理(全)

    2024-03-27 18:08:02       15 阅读
  6. 【力扣】134.加油站

    2024-03-27 18:08:02       16 阅读
  7. 2024-3-22 阿里云实习-一面

    2024-03-27 18:08:02       17 阅读
  8. uni-app 富文本编辑器

    2024-03-27 18:08:02       16 阅读