poj3984迷宫问题(bfs)

题目链接:

http://poj.org/problem?id=3984

题目意思很清楚了,直接bfs就行了,需要注意的就是输出路径。

AC代码;

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
#define MAX 10
int vis[10][10],map[10][10];
int dx[5]={1,-1,0,0};
int dy[5]={0,0,1,-1};
int head=0,tot,next;
struct node{
    int x,y,pre;
}q[100];
void print(int i)
{
    if(q[i].pre!=-1)
    {
        print(q[i].pre);
        printf("(%d, %d)\n",q[i].x,q[i].y);
    }
}
void bfs(int x1,int y1)
{
    int n,m;
    q[head].x=x1;
    q[head].y=y1;
    q[head].pre=-1;
    tot=1;
    while(head<tot)
    {
        for(int i=0;i<4;i++)
        {
            m=q[head].x+dx[i];
            n=q[head].y+dy[i];
            if(m>5 || m<0 || n>5 || n<0 || map[m][n]==1)
                continue;
            map[m][n]=1;
            q[tot].x=m;
            q[tot].y=n;
            q[tot].pre=head;
            tot++;
            if(m==4&&n==4)
                print(head);
        }
        head++;

    }
}
int main()
{
    memset(vis,0,sizeof(vis));
    for(int i=0;i<5;i++)
        for(int j=0;j<5;j++)
        {
            scanf("%d",&map[i][j]);
        }
    printf("(0, 0)\n");
    bfs(0,0);
    printf("(4, 4)\n");
}


你可能感兴趣的:(poj)