蓝桥杯备考:学会使用方向向量
我们先看一下这道题目,我们的数字是顺时针填的,也就是先从右,再从下,再去左,再去上,我们只要按这个顺序来写方向向量,然后不断的模拟就行了,非常的简单
#include <iostream>
using namespace std;
int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};
const int N = 15;
int a[N][N];
int main()
{
int n;cin >> n;
int cnt = 1;
int x = 1,y=1;
int pos = 0;
while(cnt<=n*n)
{
a[x][y] = cnt;
cnt++;
int px = x+dx[pos];
int py = y+dy[pos];
if(px<1 || py<1 || px>n || py>n || a[px][py])
{
pos = (pos+1)%4;
px=x+dx[pos];
py=y+dy[pos];
}
x = px;y=py;
}
for(int i = 1;i<=n;i++)
{
for(int j = 1;j<=n;j++)
{
printf("%3d",a[i][j]);
}
puts("");
}
return 0;
}