2 solutions
-
1
#include
using namespace std;
int a[105][105]; int n; int x,y,k, dir; int tx = 0, ty = 0;//tx ty描述我要去的下一个点是哪里
void go(){ //当前(x,y)位置 要往dir方向走一步
//往右移动: x不变,y+1 dir=0 //往下移动: x+1,y不变 dir=1 //往左移动: x不变,y-1 dir=2 //往上移动: x-1,y不变 dir=3 if (dir == 0) tx = x, ty = y+1; else if (dir==1) tx = x+1, ty = y; else if (dir==2) tx = x, ty = y-1; else tx = x-1, ty = y;
}
int main(){ cin >> n; //读入行和列 x=1, y=1,k=1, dir = 0;
while (k<=n*n){ a[x][y] = k; go(); if (tx>n || tx<=0 || ty>n || ty<=0 || a[tx][ty]!=0){ dir = dir + 1; if (dir == 4) dir = 0; go(); } x = tx, y = ty, k++; } for (int i=1;i<=n;i++){ for (int j=1;j<=n;j++) printf("%5d",a[i][j]); cout << endl; }
}
-
0
#include <iostream> using namespace std; int a[105][105]; int n; int x,y,k, dir; int tx = 0, ty = 0;//tx ty描述我要去的下一个点是哪里 void go(){ //当前(x,y)位置 要往dir方向走一步 //往右移动: x不变,y+1 dir=0 //往下移动: x+1,y不变 dir=1 //往左移动: x不变,y-1 dir=2 //往上移动: x-1,y不变 dir=3 if (dir == 0) tx = x, ty = y+1; else if (dir==1) tx = x+1, ty = y; else if (dir==2) tx = x, ty = y-1; else tx = x-1, ty = y; } int main(){ cin >> n; //读入行和列 x=1, y=1,k=1, dir = 0; while (k<=n*n){ a[x][y] = k; go(); if (tx>n || tx<=0 || ty>n || ty<=0 || a[tx][ty]!=0){ dir = dir + 1; if (dir == 4) dir = 0; go(); } x = tx, y = ty, k++; } for (int i=1;i<=n;i++){ for (int j=1;j<=n;j++) printf("%3d",a[i][j]); cout << endl; } }
- 1
Information
- ID
- 4696
- Time
- 1000ms
- Memory
- 125MiB
- Difficulty
- 1
- Tags
- (None)
- # Submissions
- 70
- Accepted
- 36
- Uploaded By