题目描述
输入两个整数n和m,输出一个n行m列的矩阵,将数字 1 到 n*m 按照回字蛇形填充至矩阵中。
基本的模拟题 —
$ 模拟蛇的移动过程(依次是东e南s西w北n),并注意对边界条件的判断,完成填表$
- 根据当前蛇头的朝向,判断将会向哪个方向前进,让蛇蛇一直往这边走,直到遇到边界再去转换方向(内层while循环)
- 当填写完全部的数(n*m)时,结束填数
蒟蒻的代码在这
#include <iostream>
using namespace std;
const int N = 105;
int arr[N][N];
int main()
{
int n, m;
cin >> n >> m;
char fx = 'e';
int x = 1, y = 0,next=1;
while (true)
{
// 蛇头朝向东 , 蛇往东填数
if (fx == 'e')
{
while (y + 1 <= m && arr[x][y + 1] == 0)
{
y++;
arr[x][y] = next;
next++;
}
fx = 's';
}
// 蛇头朝向南 , 蛇往南填数
if (fx == 's')
{
while (x + 1 <= n && arr[x + 1][y] == 0)
{
x++;
arr[x][y] = next;
next++;
}
fx = 'w';
}
// 蛇头朝向西 , 蛇往西填数
if (fx == 'w')
{
while (y - 1 >= 1 && arr[x][y - 1] == 0)
{
y--;
arr[x][y] = next;
next++;
}
fx = 'n';
}
// 蛇头朝向北 , 蛇往北填数
if (fx == 'n')
{
while (x - 1 >= 1 && arr[x - 1][y] == 0)
{
x--;
arr[x][y] = next;
next++;
}
fx = 'e';
}
if (next > n * m)break;
}
// 全部打印输出出来
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}