剑指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.

思路:顺时针打印的方法很简单,只要循环就可以按照圈圈打印了。每次打印一圈都需要一个计数count,方便寻找下一圈的起点。保持循环的标志是行rows,列columns的长度均大于2倍的圈数,即

rows > 2 * cicle && columns > 2 * cicle

此外,本题最最关键的是考虑特殊输入,包括:空数组,数组长度为0,二维数组只有一行或者一列,行列数不等(比如5行3列,3行5列)。其中行列数不等是最容易犯错的点。很容易出现竖行从上往下打印了,有从下往上回去打印了一遍。

参考代码


import java.util.ArrayList;

public class PrintMatrixAAAA {
     public static ArrayList<Integer> printMatrix(int [][] matrix) {
           if(matrix == null)
               return null;
           if (matrix.length == 0)
               return null;
           int rows = matrix.length,columns = matrix[0].length,cicle = 0;
           ArrayList<Integer> printResult = new ArrayList<>();
           while (rows > 2 * cicle && columns > 2 * cicle) {
               printCicle(matrix,cicle,printResult);
               cicle ++;
        }
           return printResult;
    }

    private static void printCicle(int[][] matrix, int cicle,ArrayList<Integer> list) {
        for(int i = cicle;i < matrix[0].length - cicle;i++) {
            list.add(matrix[cicle][i]);
        }
        for(int i = cicle + 1;i < matrix.length - cicle;i++) {
            list.add(matrix[i][matrix[0].length - 1 - cicle]);
        }
        for(int i = matrix[0].length - 2 - cicle;i >= cicle;i--) {
            if(matrix.length - 1 - cicle != cicle)//防止同一行来回打印
                list.add(matrix[matrix.length - 1 - cicle][i]);
        }
        for(int i = matrix.length - 2 - cicle;i > cicle;i--) {
            if (matrix[0].length - 1 - cicle!= cicle) {//防止同一列来回打印
                list.add(matrix[i][cicle]);
            }
        }
    }

    //测试用的主程序
    public static void main(String[] args) {
        int row = 5,column = 3,count = 1;
        int[][] matrix  = new int[row][column];
        for(int  i = 0; i < row;i++) {
            for(int j = 0;j < column;j++) {
                matrix[i][j] = count++;
                System.out.print(matrix[i][j] + ",");
            }
            System.out.println(" ");
        }
        ArrayList<Integer> arrayList = printMatrix(matrix);
        for (Integer integer : arrayList) {
            System.out.print(String.valueOf(integer) + " ");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值