编程语言
首页 > 编程语言> > Java学习——二维数组的应用(回形数组)

Java学习——二维数组的应用(回形数组)

作者:互联网

首先,二维数组可以看作是一维数组中的元素是引用类型——数组。

输入:数字n

输出:n*n的回形数组

代码:

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] huiWen = new int[n][n];
huiWen[0][0] = 1;
//m判断while循环需要多少次执行,分为奇数偶数情况,奇数时为n/2+1,偶数时为n/2
int m=0;
if(n%2==0)
    m =n/2;
else
    m = n/2+1;
int count =0;
//给二维数组从左到右、从上到下、从右到左、从下到上不断循环赋值缩小回形(只给零元素赋值)
while (count<=m-1){
for (int i = 0; i < n; i++)
    if(huiWen[count][i]==0)
        huiWen[count][i] = huiWen[count][i-1] + 1;
for (int j = 0; j < n; j++)
    if(huiWen[j][n-count-1]==0)
        huiWen[j][n-count-1] = huiWen[j - 1][n - count -1] + 1;
for (int i = n - count-1; i >= count; i--)
    if (huiWen[n-count-1][i] == 0)
        huiWen[n - count-1][i] = huiWen[n - count-1][i + 1] + 1;
for (int j = n - count-1; j >= count; j--)
    if(huiWen[j][count]==0)
        huiWen[j][count] = huiWen[j + 1][count] + 1;
count++;
}


for (int i = 0; i < n; i++) {
    for (int j = 0; j < huiWen[i].length; j++) {
        System.out.print(huiWen[i][j]+" ");
    }
    System.out.println();
}

标签:count,Java,int,System,++,数组,回形,huiWen
来源: https://blog.csdn.net/qq_43507965/article/details/122048763