public class Test {
public static int[][] makeMatrix(int w, int h) {
int[][] mtr = new int[w][h];
int d = 1, x = 0, y = 0;
while(true) {
mtr[x][y] = d++;
//各方向可否前进
boolean right = x< w-1&&mtr[x+1][y]==0;
boolean down = y< h-1&&mtr[x][y+1]==0;
boolean left = x>0&&mtr[x-1][y]==0;
boolean up = y>0&&mtr[x][y-1]==0;
//判断前进方向
if(right) if(up) y--; else x++;
else if(down) if(right) x++; else y++;
else if(left) if(down) y--; else x--;
else if(up) if(left) x--; else y--;
else break;
}
return mtr;
}
public static void printMatrix(int[][] mtr) { //输出
int w = mtr.length;
int h = mtr[0].length;
for(int i=0; i< h; i++) {
for(int j=0; j< w; j++) {
System.out.print(mtr[j][i] + "\t");
}
System.out.println ();
}
}
public static void main(String[] args) {
int h = Integer.parseInt(args[0]);
int w = Integer.parseInt(args[1]);
printMatrix(makeMatrix(h,w));
}
} |