Oliver的救援

来源:互联网 发布:c语言百分号什么意思 编辑:程序博客网 时间:2024/05/24 15:43

题目

Description
在你的帮助下,Oliver终于追到小X了,可有一天,坏人把小X抓走了。这正是Oliver英雄救美的时候。所以,Oliver又找到哆啦A梦,借了一个机器,机器显示出一幅方格地图,它告诉Oliver哪里能走,哪里不能走,。并且Oliver在这个地图的右下角,而小X在左上角。时间紧急,Oliver想知道,最少要走多少个格子,才能找到小X。(只能直走)。
Input
共N+1行,第一行为N,以下N行N列0-1矩阵,1表示不能通过,0表示可以通过(左上角和右下角为0). N<30.
Output
共一个数,为最少的走的格子数.
Sample Input
5
0 1 1 1 1
0 0 1 1 1
1 0 0 0 1
1 1 1 0 1
1 1 1 0 0
Sample Output
9

解题思路

这是一道广搜,模板化的题目。

代码

#include<cstdio>using namespace std; const int max=1001,maxn=5;int n,xx,yy,qx,qy,ss;int fa[1000001],state[1000001][2]; bool a[max][max];int dx[maxn]={-1,1,0,0},dy[maxn]={0,0,1,-1};int write(int p){    if (p==0) return 0;    ss++;    write(fa[p]);}void bfs(){    int head,tail,i,j;     head=0; tail=1; state[1][1]=xx; state[1][2]=yy; fa[1]=0;    do    {        head++;        for (i=0;i<maxn;i++)        {            int x=state[head][1]+dx[i];int y=state[head][2]+dy[i];         if (x>=1&&x<=n&&y>=1&&y<=n&&a[x][y]==true) //处理边界情况          {            tail++;            fa[tail]=head; //fa记录父节点            state[tail][1]=x;            state[tail][2]=y;            a[x][y]=false;            if (x==qx&&y==qy) //输出条件             {                write(tail);                tail=0; break;//退出循环             }         }        }    } while (head<tail); }int main(){    int i,j; char c;    scanf("%d",&n);    c=getchar();    for(i=1;i<=n;i++)    {      for(j=1;j<=n;j++)      {         c=getchar();          if (c=='0') a[i][j]=true;          else a[i][j]=false; //用布尔型存数      }      c=getchar();    }//处理输入    scanf("%d%d%d%d",&xx,&yy,&qx,&qy);    bfs();     printf("%d",ss-1); //因为在write时,ss多算了一次}
原创粉丝点击