题目:
在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(); } }