描述

回旋数组

例子

Input:
	3  3
Output:
	1 2 3
    8 9 4
    7 6 5

思路

用count来计数, x,y当前坐标(行,列) last_t上次所走方向,右1 下2 左3 上4

代码

public class Question008 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();

        int [][] array = new int [m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                array[i][j] = -1;
            }
        }
        int x = 0, y = 0;
        int count = 1;
        // 右1 下2 左3 上4
        int last_t = 1;
        while (count <= m*n) {
            array[x][y] = count++;
            if(last_t == 1) {
                if (y+1<n && array[x][y+1] < 0){
                    y++;
                } else {
                    last_t = 2;
                    if (x+1 < m && array[x+1][y] < 0) {
                        x++;
                    }else {
                        break;
                    }
                }
                //下
            } else if (last_t == 2) {
                if(x+1 < m && array[x+1][y] < 0) {
                    x++;
                } else {
                    last_t = 3;
                    if (y-1 >= 0 && array[x][y-1] < 0) {
                        y--;
                    } else {
                        break;
                    }
                }
                //左
            } else if (last_t == 3) {
                if(y-1 >= 0 && array[x][y-1] < 0) {
                    y--;
                } else {
                    last_t = 4;
                    if (x-1 >= 0 && array[x-1][y] < 0) {
                        x--;
                    } else {
                        break;
                    }
                }
            }
            //上
            else {
                if(x-1 >= 0  && array[x-1][y] < 0) {
                    x--;
                } else {
                    last_t = 1;
                    if (y+1 < n  && array[x][y+1] < 0) {
                        y++;
                    } else {
                        break;
                    }
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(array[i][j]+"\t");
            }
            System.out.println();
        }
    }
}