import java.util.Scanner;
public class Test{
static void snakeMatrix(int row, int col){
int r,c;//维度
int[][] numberMatric = new int[row][col];
int num = numberMatric[r = 0][c = 0] = 1;//起始位置
while(num < row*col){
//往右移动
while(c+1<col && numberMatric[r][c+1] == 0/*未填充默认的项其值为0*/){
c++;
numberMatric[r][c] = ++num;
}
//往下移动
while(r+1<row && numberMatric[r+1][c] == 0){
r++;
numberMatric[r][c] = ++num;
}
//往左移动
while(c-1>=0 && numberMatric[r][c-1] == 0){
c--;
numberMatric[r][c] = ++num;
}
//往上移动
while(r-1>=0 && numberMatric[r-1][c] == 0){
r--;
numberMatric[r][c] = ++num;
}
}
//打印输出
for(r = 0;r < row;r++){
for(c = 0;c < col;c++){
System.out.print(numberMatric[r][c] + " ");
}
System.out.println();//换行
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int row = in.nextInt();
int col = in.nextInt();
snakeMatrix(row, col);
}
}
}
输入:
3 4
输出:
1 2 3 4
10 11 12 5
9 8 7 6