旋转打印矩阵

将一个数组旋转打印出来,旋转打印矩阵_第1张图片

  


public class JZ {


    public static void creatArr() {
        int[][] arr = new int[3][];
        arr[0] = new int[]{1, 2, 3};
        arr[1] = new int[]{4, 5, 6};
        arr[2] = new int[]{7, 8, 9};
        doWhile(arr);

    }
    /**
     * @param arr
     * 
     * 
     * 如果左上角的点小于等于右下角的点,就进行打印,
     * 每次纸只打印数组最外围的一圈,数组的X轴与Y轴所指方向与平常数学中有所不同
     */

    public static void doWhile(int[][] arr) {
        int UX = 0;
        int UY = 0;
        int DX = arr.length - 1;
        int DY = arr[0].length - 1;
        while (UX <= DX && UY <= DY) {
            doP(arr, UX++, UY++, DX--, DY--);
        }

    }

    public static void doP(int[][] arr, int UX, int UY, int DX, int DY) {

        if (UX == DX) {
            while (UY <= DY) {
                System.out.print(arr[UY++][UX] + " ");
            }
        } else if (UY == DY) {
            while (UX <= DX) {
                System.out.print(arr[UX++][UY] + " ");
            }
        } else {
            int aX = UX;
            int aY = UY;
            while (aY < DY) {
                System.out.print(arr[UX][aY++] + " ");
            }
            while (aX < DX) {
                System.out.print(arr[aX++][DY] + " ");
            }

            while (aY > UY) {
                System.out.print(arr[DX][aY--] + " ");
            }
            while (aX > UX) {
                System.out.print(arr[aX--][UY] + " ");
            }

        }


    }


    public static void main(String[] args) {
        creatArr();
    }
}

你可能感兴趣的:(1024程序员节,排序算法,算法)