AcWing 756. 蛇形矩阵Java代码
原题链接
简单
作者:
Pikachuu
,
2020-11-02 21:38:32
,
所有人可见
,
阅读 369
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
static int N = 101;
static int[][] a = new int[N][N];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s1 = br.readLine().split(" ");
int n = Integer.parseInt(s1[0]);
int m = Integer.parseInt(s1[1]);
int k = 1;
int x = 0,y = 0;
int cnt = 1;
a[x][y] = cnt;
//如果cnt小于数组数量就继续循环
while (cnt<n*m){
//向右填数 直到到达边界或者被填过
while (y+1<m && a[x][y+1]==0){
a[x][++y] = ++cnt;
}
//向下
while (x+1<n&&a[x+1][y]==0){
a[++x][y] = ++cnt;
}
//向左
while (y-1>=0&&a[x][y-1]==0){
a[x][--y] = ++cnt;
}
//向上
while (x-1>=0&&a[x-1][y]==0){
a[--x][y] = ++cnt;
}
}
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}