zoukankan      html  css  js  c++  java
  • 转圈打印矩阵

    打印矩阵的思路:

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

    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);
        }
    }
  • 相关阅读:
    Codeforces 512D
    Codeforces Gym 101480C
    Codeforces 575A
    Codeforces Round #691 (Div. 2) 题解
    .net Core 中文等非英文文字html输出编码输出问题
    .net5 grpc服务在windows上的架设方法
    北大集训 2020 游记
    北大集训2020游记
    Tricks -「网络流」经典模型汇总
    Solution -「BJWC 2018」「洛谷 P4486」Kakuro
  • 原文地址:https://www.cnblogs.com/moris5013/p/11628478.html
Copyright © 2011-2022 走看看