蛇形矩阵
输入两个整数n和m,输出一个n行m列的矩阵,将数字 1 到 n*m 按照回字蛇形填充至矩阵中。
具体矩阵形式可参考样例。
输入格式
输入共一行,包含两个整数n和m。
输出格式
输出满足要求的矩阵。
矩阵占n行,每行包含m个空格隔开的整数。
数据范围
1≤n,m≤100
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
分析:
设置一个num,用于记录数组矩阵中某个位置该填写的数字,设置一个x,y用于记录下一步该填哪个位置。在while循环里逐个填入。
代码:
c++:
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 101;
int a[N][N],n,m;
int main()
{
cin >> n >> m;
int num = 1,x=0,y=0;
a[x][y] = num;
while (num < m * n)
{
while (y + 1 < m && !a[x][y + 1]) //向右填入num
{
a[x][++y] = ++num;
}
while (x + 1 < n && !a[x + 1][y]) //向下填入num
{
a[++x][y] = ++num;
}
while (y > 0 && !a[x][y - 1]) //向左填入num
{
a[x][--y] = ++num;
}
while (x > 0 && !a[x - 1][y]) //向上填入num
{
a[--x][y] = ++num;
}
}
for(int i = 0;i < n;i++)
{
for (int j = 0;j < m;j++)
{
cout << a[i][j] << " ";
}
cout<<endl;
}
return 0;
}
python:
n,m = map(int,input().split())
a = [[0]*(m) for i in range(n)]
x = 0
y = 0
num = 1
a[x][y] = num
while num < n*m:
while (y + 1 < m) and (not(a[x][y + 1])): #向右填入num
num += 1 # python中没有自增自减语句
y += 1
a[x][y] = num
while (x + 1 < n) and (not(a[x + 1][y])): #向下填入num
num += 1
x += 1
a[x][y] = num
while (y > 0) and (not(a[x][y - 1])): #向左填入num
num += 1
y -= 1
a[x][y] = num
while (x > 0) and (not(a[x - 1][y])): #向上填入num
num += 1
x -= 1
a[x][y] = num
for r in a:
for i in r:
print(i,end=" ")
print()