数组实现矩阵逐层加1

public class javaMain {

    public static void main(String[] args) {
        // 逐层加
        // 1 1 1 1 1 1   1 1 1 1 1   1 1 1 1   1 1 1
        // 1 2 2 2 2 1   1 2 2 2 1   1 2 2 1   1 2 1
        // 1 2 3 3 2 1   1 2 3 2 1   1 2 2 1   1 1 1
        // 1 2 3 3 2 1   1 2 2 2 1   1 1 1 1
        // 1 2 2 2 2 1   1 1 1 1 1
        // 1 1 1 1 1 1
        show();
    }

    public static void show() {
        int w = 11;//图形宽度
        int[][] arr = new int[w][w];
    
        for (int ceng = 1; ceng <= (w + 1) / 2; ceng++) {
            doWork(ceng, w ,arr);//i是数字层数及数字
        }
        //打印数组
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j]+" ");
            }
            System.out.println();
        }
    }
    public static void doWork(int ceng, int width,int[][] arr) {
        for (int i = ceng-1; i < width-ceng+1; i++) {
            for (int j = ceng-1; j < width-ceng+1; j++) {
                arr[i][j]=ceng;
            }
        }        
    }

}

猜你喜欢

转载自blog.csdn.net/quyunde/article/details/56671998