zoukankan      html  css  js  c++  java
  • 顺时针打印矩阵


    分析:

    特殊情况处理

    代码:

    package arrays20;
    
    public class Demo01 {
    
        public static void ClockwisePrintMatrix(int[][] arrays,int columns,int rows){
            if(arrays==null || columns<=0 || rows<=0){
                return;
            }
            int start = 0;
            while(columns>start*2 && rows>start*2){
                CirclePrintMatrix(arrays,columns,rows,start);
                start++;
            }
        }
    
        public static void CirclePrintMatrix(int[][] arrays,int columns,int rows,int start){
            int endX = columns-1-start;
            int endY = rows-1-start;
    
            //从左到右打印一行
            for (int i = start; i <= endX; i++) {
                int number = arrays[start][i];
                System.out.print(number+" ");
            }
    
            //从上到下打印一行
            if(start<endY){
                for (int i = start+1; i <= endY; i++) {
                    int number = arrays[i][endX];
                    System.out.print(number+" ");
                }
            }
    
    
            //从右到左打印一行
            if (start<endX && start<endY) {
                for (int i = endX-1; i >= start; i--) {
                    int number = arrays[endY][i];
                    System.out.print(number+" ");
                }
            }
    
            //从下到上打印一行(至少三行两列)
            if (start<endX && start<endY-1) {
                for (int i = endY-1; i >= start+1; i--) {
                    int number = arrays[i][start];
                    System.out.print(number+" ");
                }
            }
        }
    
        public static void main(String[] args) {
            int[][] arrays = {
                    {1,2,3,4},
                    {5,6,7,8},
                    {9,10,11,12},
                    {13,14,15,16}
                    };
            //System.out.println(arrays.length+","+arrays[0].length);
            // 列 行
            ClockwisePrintMatrix(arrays,arrays[0].length,arrays.length);
        }
    }

    执行结果:

    1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 

    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    Flask--目录
    Linux相关目录
    Mac 提示错误”xcrun: error“
    subprocess模块
    压缩模块
    GitPython模块
    Ansible-ansible命令
    YAML语法
    Ansible-安装
    Ansible-概念
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4891111.html
Copyright © 2011-2022 走看看