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);
        }
    }
  • 相关阅读:
    android systembar tabletUI
    linux mv
    修改framework/base下面的api要注意要修改的地方
    git 从远程主服务器当中创建新分支
    修改android framework 添加service
    DUILIB 界面基本知识
    Duilib vlc c++ 字符编码
    android 应用APK使用系统APK
    linux 查找文件内容及文件
    修改android 开机动画
  • 原文地址:https://www.cnblogs.com/moris5013/p/11628478.html
Copyright © 2011-2022 走看看