题目:输入一个数n,输出n*n的蛇形数组。如输入n = 5,输出:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
这道题主要是考虑边数组的边界问题,我们可以先一环一环的进行数组的赋值,代码如下:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
int count = 1; //给数组赋值的数字
int[][] arr = new int[n][n];
for (int start = 0; start * 2 < n; start++) {
int end = n - 1- start;
for (int i = start; i < end; i++) { //对最上面的一行进行从左到右赋值
arr[start][i] = count++;
}
for (int i = start; i < end; i++) { //对最右边的一列进行从上到下赋值
arr[i][end] = count++;
}
for (int i = end; i > start; i--) { //对最下边的一行进行从右到左赋值
arr[end][i] = count++;
}
for (int i = end; i > start; i--) { //对最左边的一列进行从上到下赋值
arr[i][start] = count++;
}
}
if (n%2 != 0) { //判断n是否为奇数,是的话就要对数组最中间那个元素赋值
arr[n/2][n/2] = count;
}
for (int i = 0; i < arr.length; i++) { //输出
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
sc.close();
}
}
结果: