[Java Code]顺时针输出二维数组

package com.coding_sloth;

/**
 * 顺时针打印矩阵
 * example:有如下矩阵:
 *      1   2   3   4   5
 *      14  15  16  17  6
 *      13  20  19  18  7
 *      12  11  10   9  8
 * 输出结果为:1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
 * Created by 孔武有力 on 14-3-28.
 */
public class Clockwise2DArray {
    public void test() {
        int[][] array = {{1, 2, 3, 4, 5}, {14, 15, 16, 17, 6},
                {13, 20, 19, 18, 7}, {12, 11, 10, 9, 8}};
        /*
        int[][] array = {{1, 2, 3, 4}, {12, 13, 14, 5},
                {11, 16, 15, 6}, {10, 9, 8, 7}};
        /*
        int[][] array = {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}};
        */
        int[] result = clockwise2DArray(array, 4, 5);
        for(int a : result) {
            System.out.print(a + " ");
        }
    }
    //M为数组array的行数,N为列数
    private int[] clockwise2DArray (int[][] array, int M, int N){
        int[] result = new int[M*N];
        int count = 1;  //圈数
        int k = 0; //result[] 下标
        while(count <= (min(M, N)+1)/2)
        {
            //从左到右横向打印
            for (int i = count - 1; i < N - count; i ++) {
                result[k] = array[count - 1][i];
                k ++;
            }
            //从上到下纵向打印
            for (int i = count - 1; i < M - count; i ++) {
                result[k] = array[i][N - count];
                k++;
            }
            //从右到左横向打印
            for (int i = N - count; i > count - 1; i --) {
                result[k] = array[M - count][i];
                k++;
            }
            //从下到上纵向打印
            for (int i = M - count; i > count - 1; i --) {
                result[k] = array[i][count - 1];
                k++;
            }
            count ++;
        }
        /* 当最后一圈只有一个元素[如3*3数组]时,上述循环不会执行,
         * 需将最后一个元素插入到数组result中
        */
        if (k < M*N) {
            result[k] = array[count - 2][count - 2];
        }
        return result;
    }

    private int min(int a, int b) {
        return (a>b) ? b : a;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章