解题思路:
注意事项:
参考代码:
package test;
import java.util.*;
public class Test1796 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int [][] arr = new int[n][n];
int x = 0,y=n-1;
int circle = 0;//圈数
int count = 1;//计数
int start = 0;//每次循环的起始位置(start,n-circle)
while (circle++ < n/2) {
for (x = start; x<n-circle;x++) arr[x][n-circle] = count++;//从上到下
for (y = n-circle; y>=circle;y--) arr[x][y] = count++;//从右到左
for ( ; x >=circle;x--) arr[x][y] = count++;//从下到上
for (y = start; y<n-circle;y++) arr[x][y] = count++;//从左到右
start++;
}
if (n%2 != 0) arr[n/2][n/2] = n*n;//正中心的值
for(int i=0;i<n;i++) {
for(int j=0;j<n-1;j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println(arr[i][n-1]);
}
System.out.println();
}
}
}
0.0分
1 人评分