键盘输入一个整数n,以n为矩阵大小,按顺时针螺旋的形式输出每个数(1、2、3…n*n)
比如输入3,则输出为
1 2 3
8 9 4
7 6 5
比如输入4,则输出为
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
思路:以4为例
-
只要找到顺时针方向的行号和列号,依次赋值即可
-
可以分为4部分:【上、右、下、左】,把最外层的螺旋规律摸清,内层螺旋规律同理
【伪代码,以4为例】 【声明变量】 startRow = 0; // 存储开始行 endRow = 3; // 存储结束行 startCol = 0 // 存储开始列 endCol = 3; // 存储结束列 i = startRow // 行号 j = startCol; // 列号 type = "top" | "right" | "bottom" | "left"; // 方向类型 【外层螺旋】 (top) i固定startRow,j从startCol 到 endCol,startRow++; (right) j固定endCol,i从startRow 到 endRow,endCol--; (bottom)i固定endRow j从endCol 到 startCol,endRow--; (left) j固定startCol i从endRow 到 startRow,startCol++; 【内层螺旋,重复外层】 (top) i固定startRow,j从startCol 到 endCol,startRow++; (right) j固定endCol,i从startRow 到 endRow,endCol--; (bottom)i固定endRow j从endCol 到 startCol,endRow--; 【跳出循环条件】 if (startRow > endRow && startCol > endCol) break;
代码实现
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// 输入整数
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
// 动态初始化二维数组
int[][] arr = new int[num][num];
// 声明变量
int startRow = 0;
int endRow = num - 1;
int startCol = 0;
int endCol = num - 1;
int i;
int j;
int count = 1; // 具体填入的值,从1开始
String type = "top"; // 默认从top开始
// 循环
while(startRow <= endRow || startCol <= endCol) {
if (type == "top") {
i = startRow; // 固定行
j = startCol;
// 遍历列
while(j <= endCol) {
arr[i][j] = count;
j++;
count++;
}
type = "right";
startRow++;
} else if (type == "right") {
i = startRow;
j = endCol; // 固定列
// 遍历行
while(i <= endRow) {
arr[i][j] = count;
i++;
count++;
}
type = "bottom";
endCol--;
} else if (type == "bottom") {
i = endRow;
j = endCol;
while(j >= startCol) {
arr[i][j] = count;
j--;
count++;
}
type = "left";
endRow--;
} else if (type == "left") {
i = endRow;
j = startCol;
while(i >= startRow) {
arr[i][j] = count;
i--;
count++;
}
type = "top";
startCol++;
}
}
// 输出矩阵
for (int k = 0; k < arr.length; k++) {
for (int l = 0; l < arr[k].length; l++) {
System.out.print(arr[k][l] + "\t");
}
System.out.println();
}
}
}