題目:
在nn方陣裏填入1,2,...,nn,要求填成蛇形。例如n=4時方陣爲:java
10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4
解法:
這題感受挺麻煩的,要對整個矩陣的造成過程有清晰的認識。spa
填數的循環按照Step1->Step2->Step3->Step4走。重點是控制蛇的方向和移動範圍。code
我用了一個布爾控制蛇垂直走仍是水平走,
另一個布爾控制在當前方向遞增遞減,
另外用四個變量控制蛇上下左右活動範圍。blog
假設j表示行數,i表示列數:
S1: 垂直向下,j遞增,i不變,到達最下方變水平,遞增變爲遞減。
S2: 水平向左,j不變,i遞減,到達最左方變垂直,遞減仍是遞減。
S3:垂直向上, j遞減,i不變,到達最上方變水平,遞減變遞增。
S4: 水平向右,j不變,i遞增,到達(最右-1)列時變垂直進入下一個內環,遞增仍是遞增。rem
尤爲要注意分清行數列數和水平垂直方向的關係:水平走是列數變,垂直走是行數變。it
還有要注意矩陣下標和x,y座標的區別,原點位置不一樣,不建議用x,y做爲變量名,易混淆。io
代碼:class
import java.util.*; public class Main { private static void snakeSquare(int n) { int[][] square = new int[n][n]; // true is increment, false is decrement boolean delta = true; // ture is going through row j(vertically), false is going through column i (horizontally) boolean direction = true; // R,r是上下邊界值;C,c是左右邊界值 int R = n-1, C = n-1, r = 0, c = 0; for(int i = n-1, j = 0,counter = 0 ; counter < n*n;counter++){ square[j][i] = counter + 1; // 垂直往下 if(direction && delta) { j+=1; if(j == C) {direction = !direction;delta = !delta;} } //垂直向上 else if(direction && !delta) { j -= 1; if(j == c) {direction = !direction;delta = !delta;} } //水平向右 else if(!direction && delta) { i += 1; if(i == R-1) { direction = !direction; //水平向右結束後說明要進入下一個內環,要改變邊界範圍 C -= 1;R -= 1;r += 1;c += 1; } } //水平向左 else { i -= 1; if(i == r) direction = !direction; } } for(int i = 0 ; i < n; i++){ for(int j = 0; j < n;j++) System.out.print(square[i][j] + " "); System.out.printf("%n"); } } public static void main(String[] args) { // write your code here Scanner scn = new Scanner(System.in); while(scn.hasNextInt()) snakeSquare(scn.nextInt()); scn.close(); } }