- public class Main {
- public static void main(String[] args) {
- // 设定参数
- final int N = 7;
- final int COUNT = 11;
- // 初始化
- int mat[][] = new int[N][N];
- for (int i = 0; i < N; i++) {
- for (int j = 0; j < N; j++) {
- mat[i][j] = 0;
- }
- }
- {// 写入
- int i = 0;
- int j = 0;
- int count = COUNT;
- mat[0][0] = count++;
- while (count < N * N + COUNT) {
- while (j + 1 < N && mat[i][j + 1] == 0) {
- mat[i][++j] = count++;
- }
- while (i + 1 < N && mat[i + 1][j] == 0) {
- mat[++i][j] = count++;
- }
- while (j - 1 >= 0 && mat[i][j - 1] == 0) {
- mat[i][--j] = count++;
- }
- while (i - 1 >= 0 && mat[i - 1][j] == 0) {
- mat[--i][j] = count++;
- }
- }
- }
- //输出
- for (int i = 0; i < N; i++) {
- for (int j = 0; j < N; j++) {
- String out = String.valueOf(mat[i][j]);
- String str = " ";
- out = str.substring(0, 5 - out.length()) + out;
- System.out.print(out);
- }
- System.out.println();
- }
- }
- }
复制代码- 11 12 13 14 15 16 17
- 34 35 36 37 38 39 18
- 33 50 51 52 53 40 19
- 32 49 58 59 54 41 20
- 31 48 57 56 55 42 21
- 30 47 46 45 44 43 22
- 29 28 27 26 25 24 23
复制代码 |