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

第一眼看到这个题,感觉和LeetCode上的59. Spiral Matrix II 很像。但是这个题比那个要复杂。LeetCode上的那个题,只需要不停按圈顺时针遍历,使用二维数组的值是否为0来判断边界。其代码如下:

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int x = 0, y = -1, count = 1;
        while (count <= n * n) {
            while (++y < n && res[x][y] == 0) res[x][y] = count++;
            y--;
            while (++x < n && res[x][y] == 0) res[x][y] = count++;
            x--;
            while (--y >= 0 && res[x][y] == 0) res[x][y] = count++;
            y++;
            while (--x >= 0 && res[x][y] == 0) res[x][y] = count++;
            x++;
        }
        return res;
    }
}

这个题不同的地方,只是需要手动设置4个变量来记录之前遍历过的边界,在代码中体现为x1,x2,y1,y2。

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return res;
        // 矩阵的行数和列数
        int row = matrix.length, col = matrix[0].length;
        // 当前位于矩阵的位置
        int x = 0, y = -1;
        // x1和x2分别代表当前允许的行数的最小值和最大值
        // y1和y2分别代表当前允许的列数的最小值和最大值
        int x1 = 1, x2 = row - 1, y1 = 0, y2 = col - 1;
        // 一共需要输出的数字个数
        int count = row * col;
        while (res.size() < count) {
            // 从左上往右上遍历
            while (++y <= y2) res.add(matrix[x][y]);
            y--;
            y2--;
            // 从右上往右下遍历
            while (res.size() < count && ++x <= x2) res.add(matrix[x][y]);
            x--;
            x2--;
            // 从右下往左下遍历
            while (res.size() < count && --y >= y1) res.add(matrix[x][y]);
            y++;
            y1++;
            // 从左下往左上遍历
            while (res.size() < count && --x >= x1) res.add(matrix[x][y]);
            x++;
            x1++;
        }
        return res;
    }
}

这个题目中还需要注意的地方是,不要把矩阵看成行列相等,并且要注意特殊输入,比如数组只有一个数、数组只有一行、数组只有一列、数组只有一行一列的情况。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值