Java_打印回行数组

public static void spiralArray(int[][] arr,int m, int n){
    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            System.out.print(arr[i][j]+"    ");
        }
        System.out.println();
    }
}

public static void spiralArrayHelper(int[][] arr, int m, int n, int level, int count){
    if (m - 2 * level == 0 || n - 2*level == 0){
        return;
    }
    if (m - 2 * level == 1){
        for(int i = level; i < n - level; i++){
            arr[level][i] = count ++;
        }
        return;
    }
    if (n - 2 * level == 1){
        for(int i = level; i < m - level; ++i){
            arr[i][level] = count++;
        }
        return;
    }

    for(int i = level; i < n - level; ++i){
        arr[level][i] = count++;
    }

    for(int i = level + 1; i < m - 1 - level; ++i){
        arr[i][n-1-level] = count ++;
    }

    for(int i = n - 1 - level; i >= level; --i){
        arr[m-1-level][i] = count ++;
    }

    for(int i = m-2-level; i > level; --i){
        arr[i][level] = count ++;
    }
    spiralArrayHelper(arr, m, n, ++level, count);
}

public static void main(String[] args) {
    int m = 4;
    int n = 5;
    int[][] arr = new int[m][n];
    spiralArrayHelper(arr, m, n, 0, 0);
    spiralArray(arr, m, n);
}

输出:
0    1    2    3    4    
13    14    15    16    5    
12    19    18    17    6    
11    10    9    8    7   

你可能感兴趣的:(java,算法)