描述: java
在n*n方陳裏填入1,2,...,n*n,要求填成蛇形。例如n=4時方陣爲:spa
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4code
輸入:直接輸入方陳的維數,即n的值。(n<=100)orm
輸出:輸出結果是蛇形方陳。ci
輸入數據:
it
3
輸出數據:io
7 8 1 6 9 2 5 4 3
/***************************************************************************/
class
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] arr = new int[n][n]; for(int i=0;i<n;i++){ for(int z=0;z<n;z++){ arr[i][z] = 0; } } int number = 1; Direction d = Direction.down; int x=0; int y=n-1; while(number < n*n){ if(d == Direction.down){ if(x == n-1 || arr[x+1][y] != 0){ d = Direction.left; }else{ arr[x][y]= number; number ++ ; x++; } } if(d == Direction.left){ if(y==0 || arr[x][y-1] != 0){ d = Direction.up; }else{ arr[x][y]= number; number ++ ; y--; } } if(d == Direction.up){ if(x == 0 || arr[x-1][y] != 0){ d = Direction.right; }else{ arr[x][y]= number; number ++ ; x--; } } if(d == Direction.right){ if(y == n-1 || arr[x][y+1] !=0){ d = Direction.down; }else{ arr[x][y]= number; number ++ ; y++; } } } for(int i=0;i<n;i++){ for(int z=0;z<n;z++){ if(arr[i][z] == 0){ arr[i][z] = n*n; } System.out.print(arr[i][z]+" "); } System.out.println(); } } } enum Direction{ down,left,up,right }
只要存數字時按照方向來就存就好了,若是到邊界或者下一個有數字了就讓他轉向存.這裏有個問題,若是把最後一個數字也在循環裏面放進去的話 就進入無限循環了..不知道怎麼跳出,乾脆就在輸出的時候把這個數字替換掉了...import