AcWing 756. 蛇形矩阵 - Java
原题链接
简单
作者:
KYCygni
,
2021-03-16 22:43:34
,
所有人可见
,
阅读 196
Java 代码
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int m = cin.nextInt();
int[][] s = new int[n][m];
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, 1, 0, -1};
int d = 1;
int x = 0;
int y = 0;
for (int i = 1; i <= m*n; i++)
{
s [x][y] = i;
int a = x + dx[d];
int b = y + dy[d];
if (a < 0 || b < 0 || a >= n || b >= m || s[a][b] > 0)
{
d = (d + 1) % 4;
a = x + dx[d];
b = y + dy[d];
}
x = a;
y = b;
}
for (int i = 0; i < n; i ++)
{
for (int j = 0; j < m; j ++)
System.out.print(s[i][j] + " ");
System.out.print("\n");
}
}
}