poj 3984 迷宫问题

简单的bfs。。

#include<stdio.h>
#include<string.h>
int map[10][10];
struct sb
{
    int x;
    int y;
}fathernode[10][10];
int move[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int queue[30];
int way[10][10];
void bfs()
{
    int front=0;
    int end=0;
    queue[end++]=4;
    queue[end++]=4;
    memset(way,-1,sizeof(way));
    way[4][4]=1;
    while(front!=end)
    {
        int oldx=queue[front++];
        int oldy=queue[front++];
        for(int i=0;i<4;i++)
        {
            int newx=oldx+move[i][0];
            int newy=oldy+move[i][1];
            if(newy>=0&&newy<5&&newx>=0&&newx<5&&map[newx][newy]==0&&way[newx][newy]==-1)
            {
                fathernode[newx][newy].x=oldx;
                fathernode[newx][newy].y=oldy;
                if(newx==0&&newy==0)
                    return ;
                way[newx][newy]=1;
                queue[end++]=newx;
                queue[end++]=newy;
            }
        }
    }
}
int main()
{
    int i,j;
    for(i=0;i<5;i++)
        for(j=0;j<5;j++)
        {
            scanf("%d",&map[i][j]);
        }
    fathernode[4][4].x=-1;
    fathernode[4][4].y=-1;
    bfs();
    printf("(0, 0)\n");
    int startx=0;
    int starty=0;
    while(fathernode[startx][starty].x!=-1&&fathernode[startx][starty].y!=-1)
    {
        printf("(%d, %d)\n",fathernode[startx][starty].x,fathernode[startx][starty].y);
        int startx1=fathernode[startx][starty].x;
        int starty1=fathernode[startx][starty].y;
        startx=startx1;
        starty=starty1;
    }
    return 0;
}

出答案的还有种方式是递推

#include<stdio.h>
#include<string.h>
struct node
{
 int x,y;
}map2[10][10];
void print(int x,int y)
{
 if(x==1&&y==1)
 return ;
 print(map2[x][y].x,map2[x][y].y);
 printf("(%d, %d)\n",map2[x][y].x-1,map2[x][y].y-1);
}
int way[10][10];
int queue[23333];
int map[10][10];
int front,end;
int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
int map1[10][10];
void bfs(int x,int y)
{
 int i;
 front=end=0;
 queue[end++]=x;
 queue[end++]=y;
 memset(map1,-1,sizeof(map1));
 map2[0][0].x=-1;
 map2[0][0].y=-1;
 map1[0][0]=0;
 while(front!=end)
 {
 x=queue[front++];
 y=queue[front++];
 map1[x][y]=0;
 for(i=0;i<=4;i++)
 {
 int ex=dir[i][0]+x;
 int ey=dir[i][1]+y;
 if(ex<1||ex>5||ey<1||ey>5||map[ex][ey]==1||map1[ex][ey]!=-1)
 continue;
 queue[end++]=ex;
 queue[end++]=ey;
 map2[ex][ey].x=x;
 map2[ex][ey].y=y;
 }
 }
}
int main()
{
int i,j;
for(i=1;i<=5;i++)  for(j=1;j<=5;j++) scanf("%d",&map[i][j]); bfs(1,1); int x1=1,y1=1; print(5,5); printf("(4, 4)\n"); return 0; }

你可能感兴趣的:(poj,bfs,递推)