蓝桥杯模拟赛
复习蛇形矩阵的构造
方法一:
#include<iostream>
#include<cstring>
using namespace std;
int n,m;
int f[40][40];
int main()
{
cin>>n>>m;
int dx[4] = {0,1,0,-1},dy[4] = {1,0,-1,0};
for(int d = 0,k = 1,x = 0,y = 0;k <= m * n;k++)
{
f[x][y] = k;
int a = x + dx[d],b = y + dy[d];
if(a<0||a>n-1||b<0||b>m-1||f[a][b])
{
d = (d + 1) % 4;
a = x + dx[d],b = y + dy[d];
}
x = a,y = b;
}
cout<<f[19][19];
return 0;
}
方法二:
#include<iostream>
using namespace std;
int a[40][40];
int main() {
int t=0, x=1, y=1;
t = a[x][y] = 1;
while (t < 30 * 30) {
while (y + 1 <= 30 && !a[x][y + 1]) a[x][++y] = ++t;
while (x + 1 <= 30 && !a[x + 1][y]) a[++x][y] = ++t;
while (y - 1 > 0 && !a[x][y - 1]) a[x][--y] = ++t;
while (x - 1 > 0 && !a[x - 1][y]) a[--x][y] = ++t;
}
cout << a[20][20];
return 0;
}