螺旋填数
读入两个整数m,n,输出一个m行n列的矩阵,这个矩阵是1~m*n这些自然数按照右、下、左、上螺旋填入的结果。
例如读入数字4,5,则输出结果为:
1 2 3 4 5
14 15 16 17 6
13 20 19 18 7
12 11 10 9 8
package cn.tedu.Pro;
import java.util.Arrays;
import java.util.Scanner;
public class Pro5_2 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int m=sc.nextInt();//行
int n=sc.nextInt();//列
int s=1;
int x,y;
x=0;
y=0;
int[][] a=new int[m][n];
a[0][0]=1;
while(s<m*n){
//右
while(y<n-1&&a[x][y+1]==0){
y++;
s++;
a[x][y]=s;
}
//下
while (x+1<m&&a[x+1][y]==0){
x++;
s++;
a[x][y]=s;
}
//左
while (y-1>=0&&a[x][y-1]==0){
y--;
s++;
a[x][y]=s;
}//上
while (x-1>=0&&a[x-1][y]==0){
x--;
s++;
a[x][y]=s;
}
}
for(int i=0;i<a.length;i++){
System.out.println(Arrays.toString(a[i]));
}
}
}