我自己写了一代代码实现,但感觉应该有更好的算法,请各位大神多多指正,不胜荣幸!
import java.util.Scanner;
public class CircleNum {
public static void main(String[] args ) {
System.out.println("请输入数组长度:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][n];
round(n, arr);
System.out.println("打印结果:");
print(arr);
}
public static void round(int n, int[][] arr) {
int last = n * n;
int count = 1;
for(int i=0; i<n/2; i++) {
for(int c=0+i; c<n-i; c++) {
arr[0+i][c] = count;
count ++;
}
for(int r=1+i; r<n-i; r++) {
arr[r][n-1-i] = count;
count ++;
}
for(int c=n-i-2; c>=0+i; c--) {
arr[n-1-i][c] = count;
count ++;
}
for(int r=n-i-2; r>=1+i; r--) {
arr[r][0+i] = count;
count ++;
}
}
if(1 == n%2) {
arr[n/2][n/2] = last;
}
}
public static void print(int[][] arr) {
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();
}
}
}
|
|