题目要求:打印螺旋矩阵
1 2 3 4 5 6 7
24 25 26 27 28 29 8
23 40 41 42 43 30 9
22 39 48 49 44 31 10
21 38 47 46 45 32 11
20 37 36 35 34 33 12
19 18 17 16 15 14 13
解题思路
n 阶矩阵用 n+2 阶矩阵求解
外围 0 作用:解决坐标标越界
内圈 -1 作用:解决累加范围
0 0 0 0 0 0 0 0 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 -1 -1 -1 -1 -1 -1 -1 0
0 0 0 0 0 0 0 0 0
赋值后的n+2阶螺旋矩阵:
0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 0
0 24 25 26 27 28 29 8 0
0 23 40 41 42 43 30 9 0
0 22 39 48 49 44 31 10 0
0 21 38 47 46 45 32 11 0
0 20 37 36 35 34 33 12 0
0 19 18 17 16 15 14 13 0
0 0 0 0 0 0 0 0 0
package lesson01;
import java.util.Scanner;
public class demo05_Spiral_Matrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = n + 2;
int arr[][] = new int[m][m];
for (int i = 1; i < m - 1; i++)
for (int j = 1; j < m - 1; j++)
arr[i][j] = -1;
int temp = 1; // 用
int x = 1, y = 1; // 初始化坐标
while (temp <= n * n) {
while (arr[x][y] == -1)
arr[x][y++] = temp++; // --->
y--;
x++;
while (arr[x][y] == -1)
arr[x++][y] = temp++; // 向下
x--;
y--;
while (arr[x][y] == -1)
arr[x][y--] = temp++; // <---
y++;
x--;
while (arr[x][y] == -1)
arr[x--][y] = temp++;
x++;
y++;
}
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < m - 1; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}