蛇形填數
- 描述
- 在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、獲取循環總次數n*n次,定義二位數組
-
2、分別循環下左上右,每次循環先給該位置賦值,在判斷該方向的下一位置是否超出數組範圍,若超出則改變方向循環。
-
*******注意:每次循環到拐角改變方向時,需要先將改變的的那個方向的位置前進一格,否則,改變方向的第一個值會覆蓋拐角位置的值。
-
import java.util.Scanner; public class _33_3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int m = scan.nextInt(); int x = 0; int y = m-1; boolean top = false; boolean right = false; boolean left = false; boolean bottum = true; int num; int[][] data = new int[m][m]; for(int i = 1; i <= m*m; ++i){ if(bottum){ data[x][y] = i; num = x + 1; if(num >= m || data[num][y] != 0){ bottum = false; left = true; if(i != 1){ --y; } }else{ ++x; } }else if(left){ data[x][y] = i; num = y - 1; if(num < 0 || data[x][num] != 0){ left = false; top = true; if(i != 1){ --x; } }else{ --y; } }else if(top){ data[x][y] = i; num = x - 1; if(num < 0 || data[num][y] != 0){ top = false; right = true; if(i != 1){ ++y; } }else{ --x; } }else if(right){ data[x][y] = i; num = y + 1; if(data[x][num] != 0){ right = false; bottum = true; if(i != 1){ ++x; } }else{ ++y; } } } for(int i = 0; i < m; ++i){ for(int j = 0; j < m; ++j){ if(j == m - 1){ System.out.println(data[i][j]); }else{ System.out.print(data[i][j] + " "); } } } } }