在m*n方阵中依次填入1,2,3,。。。,m*n,要填成蛇形。如n=4,m=3时候如下:
1 2 3 4
10 11 12 5
9 8 7 6
我的代码如下:
package ch02;
import java.util.Scanner;
public class SnakeMatrix { public static void main(String[] args){
int i = 0;
int m = 0;
int n = 0;
int[] a = new int[2];
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
a[i++] = sc.nextInt();
if(i==2){
m = a[0];
n = a[1];
int b[][] = new int[m][n];
int x = 0,y = 0;
int tips = 1;
b[0][0] = 1;
while(tips<m*n){
//判断下一步是否越界,并且判断下一步是否已经填满
while(x+1 < n&&b[y][x+1] == 0){
b[y][++x] = ++tips;
}
while(y+1 < m&&b[y+1][x] == 0){
b[++y][x] = ++tips;
}
while(x-1 >= 0&&b[y][x-1] == 0 ){
b[y][--x] = ++tips;
} while( y-1 >= 0&&b[y-1][x] == 0 ){
b[--y][x] = ++tips;
}
}
for(int s = 0;s < m ;s++){
for(int t = 0;t < n;t++){
System.out.print(b[s][t]+" ");
}
System.out.println(" ");
}
}
}
}
}
该算法的关键在于要先判断下个数是否越界,然后是否已经被填,最后才去填数据。还有就是要把第一个要填的数据初始化。