package Java2012大赛;
import java.util.Scanner;
public class 打印矩阵 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
System.out.println("input a number:");
int a = scan.nextInt();
while(a!=0){
int[][] arr = fx1(a);
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= a; j++)
System.out.print(arr[i][j] + "\t");
System.out.println();
}
System.out.println("input a number:");
a = scan.nextInt();
}
scan.close();
}
private static int[][] fx1(int a) {
// TODO Auto-generated method stub
int sum = 1;
int max = a * a;// 求出该矩阵中最大的那个谁
int[][] array = new int[a + 1][a + 1];
int times = (a + 1) / 2;// 循环的圈数
for (int i = 1; i <= times; i++) {
for (int m = i, n = i; n <= a - i; n++) {// 横边
array[m][n] = sum;
++sum;
}
if(max==sum)
break;
for (int n = a - i + 1, m = i; m <= a - i; m++) {// 右边
array[m][n] = sum;
++sum;
}
for (int m = a - i + 1, n = a - i + 1; n >= i+1; n--) {// 下边
array[m][n] = sum;
++sum;
}
//sum--;
for (int m = a - i + 1, n = i; m >= i+1; m--) {// 左边
array[m][n] = sum;
++sum;
}
}
if(a%2==1)
array[times][times] = max;
return array;
}
}
//运行结果
input a number:
5
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
打印数字矩阵
最新推荐文章于 2022-11-11 08:55:33 发布