题目描述
一个 n 行 n 列的螺旋方阵按如下方法生成:从方阵的左上角(第 1 行第 1 列)出发,初始时向右移动;如果前方是未曾经过的格子,则继续前进;否则,右转。重复上述操作直至经过方阵中所有格子。根据经过顺序,在格子中依次填入 1,2,3,…,n,便构成了一个螺旋方阵。下面是一个 n=4 的螺旋方阵。
编程输入一个正整数 n,生成一个 n×n 的螺旋方阵。
样例输入
5
样例输出
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
代码
#include <bits/stdc++.h> using namespace std; int n; int direction = 1; void go(int &y, int &x, bool haha[][1000]) { bool flag = false; for(int time = 1; flag != true && time<=2;time++) { if (direction == 0) { if(y-1<1 || haha[y-1][x] == true) { direction = (direction+1)%4; continue; } y--; flag = true; } if (direction == 1) { if(x+1>n || haha[y][x+1] == true) { direction = (direction+1)%4; continue; } x++; flag = true; } if (direction == 2) { if(y+1>n || haha[y+1][x] == true) { direction = (direction+1)%4; continue; } y++; flag = true; } if (direction == 3) { if(x-1<1 || haha[y][x-1] == true) { direction = (direction+1)%4; continue; } x--; flag = true; } } } int main() { cin>>n; int a[n+10][n+10]; bool vis[n+10][1000] = {false}; pair<int,int>position = {1,1}; for(int i=1; i<=n*n; i++) { a[position.first][position.second] = i; vis[position.first][position.second] = true; go(position.first,position.second,vis); } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ cout<<setw(5)<<a[i][j]; } cout<<endl; } return 0; }