趣味填数

在n×n方阵里填入1、2、3……n×n,要求填成盘蛇形。例如n=4时为:

10 11 12 01

09 16 13 02

08 15 14 03

07 06 05 04

在上面的方阵中,小于10的数前面都补足0,数与数之间有一个空格。

Input

n     (n<=9)

Output

盘蛇形方阵

Sample Input

4

Sample Output

10 11 12 01
09 16 13 02
08 15 14 03
07 06 05 04
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mm(a) memset(a,0,sizeof(a))
#define max(x,y) (x)>(y)?(x):(y)
#define min(x,y) (x)<(y)?(x):(y)
const int INF = 0x3f3f3f3f;
const int MAXN = INF;
int a[11][11],dirx[4]= {1,0,-1,0},diry[4]= {0,-1,0,1};
int n,cnt,sum;
void dfs1(int x,int y,int sta) {
    a[x][y]=++cnt;
    if(cnt==sum) {
        return;
    }
    int new_x=x+dirx[sta];
    int new_y=y+diry[sta];
    if(a[new_x][new_y]||new_x>n||new_x<1||new_y>n||new_y<1) {
        ++sta;
        sta%=4;
        new_x=x+dirx[sta];
        new_y=y+diry[sta];
        dfs1(new_x,new_y,sta);
        return;
    }
    dfs1(new_x,new_y,sta);
}
int main() {
    while(~scanf("%d",&n)) {
        mm(a);
        sum=n*n;;
        cnt=0;
        dfs1(1,n,0);
        for(int i=1; i<=n; i++) {
            for(int j=1; j<=n; j++) {
                if(j!=1)printf(" ");
                printf("%02d",a[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44061561/article/details/94589258