【深基5.习6】蛇形方阵
题目描述
给出一个不大于
9
9
9 的正整数
n
n
n,输出
n
×
n
n\times n
n×n
的蛇形方阵。
从左上角填上 1 1 1 开始,顺时针方向依次填入数字,如同样例所示。注意每个数字有都会占用 3 3 3 个字符,前面使用空格补齐。
输入格式
输入一个正整数 n n n,含义如题所述。
输出格式
输出符合题目要求的蛇形矩阵。
样例 #1
样例输入 #1
4
样例输出 #1
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
提示
数据保证, 1 ≤ n ≤ 9 1 \leq n \leq 9 1≤n≤9。
代码
import java.io.*;
import java.util.*;
/**
* @author: ZZJ
* @date: 2023/01/30
* @desc:
*/
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int nextInt = scanner.nextInt();
int nums = nextInt * nextInt;
int init = 1;
int row = 0;
int col = 0;
int[][] ints = new int[nextInt][nextInt];
while (init < nums){
while (col + 1 < nextInt && ints[row][col+1] == 0) {
ints[row][col++] = init++;
}
while (row + 1 < nextInt && ints[row+1][col] == 0){
ints[row++][col] = init++;
}
while (col - 1 >= 0 && ints[row][col-1] == 0){
ints[row][col--] = init++;
}
while (row - 1 >= 0 && ints[row-1][col] == 0){
ints[row--][col] = init++;
}
}
ints[row][col] = init;
for (int i = 0; i < nextInt; i++) {
for (int j = 0; j < nextInt; j++) {
System.out.format("%3d",ints[i][j]);
}
System.out.println();
}
}
}
总结:row,col顺时针循环