import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int m=scan.nextInt();
int n=scan.nextInt();
int[][] num=new int[m][n];
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
num[i][j]=scan.nextInt();
}
}
int cnt=1,i=1,j=0;
System.out.print(num[0][0]);
num[0][0]=-1;
while (cnt<m*n){
/*自上向下,先判断能否取数,再判断是否已经打印,顺序混乱会造成数组越界*/
while (i<m&&num[i][j]!=-1){
System.out.print(" "+num[i][j]);
num[i][j]=-1;
i++;cnt++;
}
i--;j++;
/*自左向右*/
while (j<n&&num[i][j]!=-1){
System.out.print(" "+num[i][j]);
num[i][j]=-1;
j++;cnt++;
}
i--;j--;
/*自下向上*/
while (i>=0&&num[i][j]!=-1){
System.out.print(" "+num[i][j]);
num[i][j]=-1;
i--;cnt++;
}
i++;j--;
/*自右向左*/
while (j>=0&&num[i][j]!=-1){
System.out.print(" "+num[i][j]);
num[i][j]=-1;
j--;cnt++;
}
i++;j++;
}
}
}
回形取数
最新推荐文章于 2024-03-16 01:51:23 发布