剑指offer之顺时针打印二维数组

题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

解题思路:
大家都知道一个矩阵只需要知道左上角和右下角坐标就可以得到它的大小,所以首先取矩阵的左上角和右下角坐标分别记为:

int x_top = 0;int y_top = 0; 
int x_bottom = row - 1;int y_bottom = col - 1;//row为矩阵行,col为矩阵列

整个过程可分为:从左到右打印数组、从上到下打印、从右到左、从下到上。通过上述四个位置变量来控制打印,没打印一圈,x_top++;y_top++;x_bottom–;y_bottom–;意思就是往矩阵中心缩进一步,当两个坐标点重合时,即到最后一个数字,遍历结束。

private static ArrayList<Integer> pMatrix(int[][] matrix) {
    int col = matrix[0].length;// 列数
    int row = matrix.length;// 行数
    ArrayList<Integer> resultList = new ArrayList<>();
    if(col == 0 || row == 0){
        return resultList;
    }
    int x_top = 0;int y_top = 0;//矩阵左上点和右下点
    int x_bottom = row - 1;int y_bottom = col - 1;
    while(x_top <= x_bottom && y_top <= y_bottom){
        //左边到右边=>行不变,列变
        for(int i = y_top;i <= y_bottom;i++) resultList.add(matrix[x_top][i]);
        //上到下=>列不变,行变
        for(int i = x_top + 1;i <= x_bottom;i++) resultList.add(matrix[i][y_bottom]);
        //右到左=>行不变,列变
        if (x_top != x_bottom)
        {
            for(int i = y_bottom - 1; i >= y_top; --i)  
                resultList.add(matrix[x_bottom][i]);
        }
        //下到上=>列不变,行变
        if(y_top != y_bottom)
        {
            for(int i = x_bottom - 1; i > x_top; --i) 
                resultList.add(matrix[i][y_top]);
        }
        x_top++;y_top++;x_bottom--;y_bottom--;

    }
    return resultList;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只打杂的码农

你的鼓励是对我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值