• 转圈打印矩阵


    打印矩阵的思路:

    先找出矩阵的左上顶点和右下顶点,然后转圈打印四条边,打印一圈后,左上顶点和右下顶点同时往内移动一个单位,在转圈打印

    public class PrintMatrixInSpiral {
        
        public static  void print(int [][] matrix ) {
            int tR = 0;
            int tC = 0;
            int bR = matrix.length - 1;
            int bC = matrix[0].length - 1;
            while (tR <= bR && tC <= bC) {
                printEdge(matrix, tR++, tC++, bR--, bC--);
            }
        }
        
    
        public static void printEdge(int[][] m, int tR, int tC, int bR, int bC) {
            if (tR == bR) { //行相等了,打印整行
                for (int i = tC; i <= bC; i++) {
                    System.out.print(m[tR][i] + " ");
                }
            } else if (tC == bC) { //列相等,打印整列
                for (int i = tR; i <= bR; i++) {
                    System.out.print(m[i][tC] + " ");
                }
            } else { //打印四条边,打印每条边时,注意结束元素的下标
                int curC = tC;
                int curR = tR;
                while (curC != bC) {
                    System.out.print(m[tR][curC] + " ");
                    curC++;
                }
                while (curR != bR) {
                    System.out.print(m[curR][bC] + " ");
                    curR++;
                }
                while (curC != tC) {
                    System.out.print(m[bR][curC] + " ");
                    curC--;
                }
                while (curR != tR) {
                    System.out.print(m[curR][tC] + " ");
                    curR--;
                }
            }
        }
    
        public static void main(String[] args) {
            int[][] matrix = { { 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 } };
            print(matrix);
        }
    }
  • 相关阅读:
    用代码初始化AE控件许可
    打开shpfile,mdb,sde工作空间
    UESTC_Tournament CDOJ 124
    UESTC_Little Deer and Blue Cat CDOJ 1025
    UESTC_Judgment Day CDOJ 11
    UESTC_One Step Two Steps CDOJ 1027
    UESTC_In Galgame We Trust CDOJ 10
    UESTC_贪吃蛇 CDOJ 709
    UESTC_冰雪奇缘 CDOJ 843
    java 常用API 时间
  • 原文地址:https://www.cnblogs.com/moris5013/p/11628478.html
Copyright © 2020-2023  润新知