首页 > 其他 > 详细

牛客(19)顺时针打印矩阵

时间:2018-05-08 13:06:37      阅读:207      评论:0      收藏:0      [点我收藏+]
   //    题目描述
//    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
//    例如,如果输入如下矩阵: 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.


    public static ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();

        int topLine = 0;
        int firstColumn = 0;
        for (int i = topLine; i < matrix.length - topLine&&firstColumn<matrix[i].length - firstColumn; i++) {
            for (int j = firstColumn; j < matrix[i].length - firstColumn; j++) {
                arrayList.add(matrix[i][j]);

            }
            for (int j = topLine + 1; j < matrix.length - topLine; j++) {
                if (matrix[j].length - firstColumn - 1 < firstColumn) {
                    break;
                }
                arrayList.add(matrix[j][matrix[j].length - firstColumn - 1]);
            }
            for (int j = matrix[i].length - firstColumn - 2; j >= firstColumn; j--) {
                if (topLine >= matrix.length - topLine - 1) {
                    break;
                }
                arrayList.add(matrix[matrix.length - topLine - 1][j]);

            }
            for (int j = matrix.length - topLine - 2; j > topLine; j--) {
                if (firstColumn >= matrix[j].length - firstColumn - 1) {
                    break;
                }
                arrayList.add(matrix[j][firstColumn]);
            }

            topLine++;
            firstColumn++;
        }
        return arrayList;
    }

 

牛客(19)顺时针打印矩阵

原文:https://www.cnblogs.com/kaibing/p/9007484.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!