蛇形填数
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
3
描述
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
-
输入
- 直接输入方陈的维数,即n的值。(n<=100)
-
输出
- 输出结果是蛇形方阵。
-
样例输入
3
样例输出
7 8 1
6 9 2
5 4 3
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(new BufferedInputStream(System.in));
int arr[][];
int n = cin.nextInt();
int i = -1;
int j = n-1;
int temp = 0;
arr = new int[n][n];
while(temp<n*n){
while(i<n-1&&arr[i+1][j]==0){
arr[++i][j] = ++temp;
}
while(j>0&&arr[i][j-1]==0){
arr[i][--j] = ++temp;
}
while(i>0&&arr[i-1][j]==0){
arr[--i][j] = ++temp;
}
while(j<n-1&&arr[i][j+1]==0){
arr[i][++j] = ++temp;
}
}
for(int x=0;x<n;x++){
for(int y=0;y<n;y++)
System.out.print(arr[x][y]+" ");
System.out.println("");
}
}
}