马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
我们先看一下这道标题,我们的数字是顺时针填的,也就是先从右,再从下,再去左,再去上,我们只要按这个序次来写方向向量,然后不停的模仿就行了,非常的简单- #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;
- }
复制代码 |