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

    /**
     * 题目:顺时针打印矩阵
     * 描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
     *    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.
     * 方案:   定义两个点:左上角和右下角,然后移动;
     *              注意代码合理性,只有一行或者只有一列
     *   while终止条件:左上角坐标值大于右下角坐标值时
     *
     * */

    public class Four {
        static List<Integer>  data = new ArrayList<>();
        public static void one(int[][] arr) {
            int cow1 = 0;
            int col1 = 0;
            int cow2 = arr.length-1 ;
            int col2 = arr[0].length-1 ;
            while(cow1 <= cow2  && col1 <=col2 ) {
                getData(arr,cow1++,col1++,cow2--,col2--);
            }
        }
        
        private static void getData(int[][] arr, int cow1, int col1, int cow2, int col2) {
            List<Integer>  data = new ArrayList<Integer>();
            if(cow1 == cow2 ) { //只有一行
                for(int i = col1;i<=col2;col1++) {
                    data.add(arr[cow1][i]);
                }
            }else if(col1 == col2) {//只有一列
                for(int i = cow1;i<=cow2;i++) {
                    data.add(arr[i][col1]);
                }
            }else {
                int tempCow = cow1;
                int tempCol = col1;
                while(col1 != col2) {
                    data.add(arr[cow1][tempCol]);
                    tempCol++;
                }
                while(cow1 != cow2) {
                    data.add(arr[tempCow][col1]);
                    tempCow++;
                }
                while(cow1 != cow2){
                    data.add(arr[cow2][tempCol]);
                    tempCol--;
                }while(col1 != col2) {
                    data.add(arr[tempCow][col1]);
                    tempCow--;
                }
            }
        }
        
    }
    天助自助者
  • 相关阅读:
    JVM系列(五)并发相关
    String的hashCode 和equals 区别
    JVM系列(四)生命周期和classloader
    jvm面试题解答
    memcached(十三)注意事项
    memcached(十二)监控
    memcached(十)动态扩容
    memcached(九)--LRU
    memcached(八)-- set指令内部实现
    用通俗易懂的大白话讲解Map/Reduce原理
  • 原文地址:https://www.cnblogs.com/ZeGod/p/9969447.html
Copyright © 2011-2022 走看看