算法:顺时针打印矩阵

/**
 * 题目:顺时针打印矩阵
 * 描述:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
 *    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--;
            }
        }
    }
    
}

 

posted @ 2018-11-16 15:10  弄潮儿儿  阅读(238)  评论(0编辑  收藏  举报