AcWing 756. 蛇形矩阵
原题链接
困难
作者:
JAVA小老弟
,
2020-03-13 22:32:57
,
所有人可见
,
阅读 940
import java.io.*;
import java.util.*;
public class Main{
public static void main(String args[])throws IOException{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
String s[]=r.readLine().split(" ");
int n=Integer.parseInt(s[0]);
int m=Integer.parseInt(s[1]);
//left、right|up、down 分别为左边界、有边界、上边界、下边界
int left=0;
int right=m-1;
int up=0;
int down=n-1;
//Hang、Lie 分别为起始点的横纵坐标
int Hang=0;
int Lie=0;
int[][] arr=new int[n][m];
int idx=1;
while(true){
//1.往右走
while(left<=right && Lie<=right){
arr[Hang][Lie++]=idx++;
}
Lie--;
Hang++;
up++;
if(up>down)
break;
//2.往下走
while(up<=down && Hang<=down){
arr[Hang++][Lie]=idx++;
}
Hang--;
Lie--;
right--;
if(left>right)
break;
//3.往左走
while(left<=right && Lie>=left){
arr[Hang][Lie--]=idx++;
}
Lie++;
Hang--;
down--;
if(up>down)
break;
//4.往上走
while(up<=down && Hang>=up){
arr[Hang--][Lie]=idx++;
}
Hang++;
Lie++;
left++;
if(left>right)
break;
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
}
}