蛇形填数
描述在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
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
1 import java.util.Scanner; 2 3 public class Main { 4 public static void main(String[] args) { 5 Scanner scanner=new Scanner(System.in); 6 int n; 7 int flag[][]=new int[101][101]; 8 int i; 9 int j; 10 int count; 11 String direction; 12 13 n=scanner.nextInt(); 14 15 for(i=0;i<n;i++){ 16 for(j=0;j<n;j++) 17 flag[i][j]=0; 18 } 19 20 i=0; 21 j=n-1; 22 direction="south"; 23 count=1; 24 25 while(true){ 26 flag[i][j]=count; 27 count++; 28 29 if(direction.compareTo("south")==0){ 30 i++; 31 32 if(i==n || flag[i][j]!=0){ 33 direction="west"; 34 i--; 35 j--; 36 } 37 } 38 39 else if(direction.compareTo("west")==0){ 40 j--; 41 42 if(j==-1 || flag[i][j]!=0){ 43 direction="north"; 44 j++; 45 i--; 46 } 47 } 48 49 else if(direction.compareTo("north")==0){ 50 i--; 51 52 if(i==-1 || flag[i][j]!=0){ 53 direction="East"; 54 i++; 55 j++; 56 } 57 } 58 59 else if(direction.compareTo("East")==0){ 60 j++; 61 62 if(j==n || flag[i][j]!=0){ 63 direction="south"; 64 j--; 65 i++; 66 } 67 } 68 69 if(count==n*n+1) 70 break; 71 } 72 73 for(i=0;i<n;i++){ 74 for(j=0;j<n;j++) 75 System.out.print(flag[i][j]+" "); 76 77 System.out.println(); 78 } 79 } 80 }