zoukankan      html  css  js  c++  java
  • 牛客(19)顺时针打印矩阵

       //    题目描述
    //    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,
    //    例如,如果输入如下矩阵: 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;
        }
  • 相关阅读:
    Golang相关环境变量
    mac catalina关闭系统更新提示
    Git常用命令
    UDP打洞原理
    LANMP相关配置
    Windows平台编译libevent
    Sublime text2 + cygwin编译C++
    C++的指针常量和常量指针
    C++的new和delete
    C/C++产生随机数
  • 原文地址:https://www.cnblogs.com/kaibing/p/9007484.html
Copyright © 2011-2022 走看看