蛇形填数

来源:互联网 发布:java反序列化是什么 编辑:程序博客网 时间:2024/05/16 14:10
#include <stdio.h>#include <stdlib.h>#define MAXN 102#define WALL -1#define BLANK 0int map[MAXN][MAXN];int x,y,n;void init(void){    int i,j;    scanf("%d",&n);    x=1,y=n;    for(i=0;i<MAXN;i++)    {        for(j=0;j<MAXN;j++)        {            map[i][j]=WALL;        }    }    for(i=1;i<=n;i++)    {        for(j=1;j<=n;j++)        {            map[i][j]=BLANK;        }    }}void nextstep(void){    if(map[x-1][y]==BLANK&&map[x+1][y]!=BLANK&&map[x][y+1]!=BLANK&&map[x][y-1]!=BLANK)   //只能向上    {        x--;    }    else if(map[x-1][y]!=BLANK&&map[x+1][y]==BLANK&&map[x][y+1]!=BLANK&&map[x][y-1]!=BLANK)//只能向上    {        x++;    }    else if(map[x-1][y]!=BLANK&&map[x+1][y]!=BLANK&&map[x][y+1]!=BLANK&&map[x][y-1]==BLANK)//只能向左    {        y--;    }    else if(map[x-1][y]!=BLANK&&map[x+1][y]!=BLANK&&map[x][y+1]==BLANK&&map[x][y-1]!=BLANK)//只能向右    {        y++;    }    else if(map[x+1][y]==BLANK&&map[x][y-1]==BLANK)//向左或向下,则向下    {        x++;    }    else if(map[x-1][y]==BLANK&&map[x][y-1]==BLANK)//向左或向上,则向左    {        y--;    }    else if(map[x-1][y]==BLANK&&map[x][y+1]==BLANK)//向右或向上,则向上    {        x--;    }    else if(map[x+1][y]==BLANK&&map[x][y+1]==BLANK)//向右或向下,则向右    {        y++;    }}int main(){    init();    int step,i,j;    step=1;    while(step<=n*n)    {        map[x][y]=step;        nextstep();        step++;    }    for(i=1;i<=n;i++)    {        for(j=1;j<=n;j++)        {            printf("%d ",map[i][j]);        }        printf("\n");    }    return 0;}

0 0