hdu

http://acm.hdu.edu.cn/showproblem.php?pid=2822

给定起点和终点,问从起点到终点需要挖几次只有从# 到 .或者从. 到  . 才需要挖一次。

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 1001;
int n,m;
int sx,sy,ex,ey;
char maze[maxn][maxn];
int vis[maxn][maxn];
int dir[4][2]={-1,0,1,0,0,1,0,-1};
struct point
{
    int x,y,step;
    char z;
    bool operator < (const point a) const
    {
        return step>a.step;
    }
};

int bfs()
{
   // printf("%d %d
",a,b);
    for(int i=0;i<=n;i++)
        for(int j=0;j<=m;j++)
        vis[i][j]=1<<29;
    priority_queue<point>que;
    point s;
    s.x=sx;s.y=sy;s.step=0;s.z='X';
    que.push(s);
    vis[s.x][s.y]=0;
    while(!que.empty())
    {
        point e=que.top();que.pop();
       //printf("%d %d %d
",e.x,e.y,e.step);
        if(e.x==ex&&e.y==ey) return e.step;
        for(int i=0;i<4;i++)
        {
            s=e;
            s.x=e.x+dir[i][0];
            s.y=e.y+dir[i][1];
            if(s.x>=0&&s.x<n&&s.y>=0&&s.y<m)
            {
                if(maze[s.x][s.y]=='X') s.step=e.step;
                else if(maze[s.x][s.y]=='.') s.step=e.step+1;
                if(s.step<vis[s.x][s.y])
                {
                    vis[s.x][s.y]=s.step;
                    que.push(s);
                }
            }
        }
    }
}

int main()
{
    //freopen("a.txt","r",stdin);
    while(~scanf("%d%d",&n,&m))
    {
        if(n==0&&m==0) break;
        for(int i=0;i<n;i++)
        {
            scanf("%s",maze[i]);
           // printf("%s
",maze[i]);
        }
        scanf("%d %d",&sx,&sy);
        scanf("%d %d",&ex,&ey);
        //printf("%d%d%d%d
",sx,sy,ex,ey);
        sx--,sy--,ex--,ey--;
        printf("%d
",bfs());
    }
    return 0;
}
原文地址:https://www.cnblogs.com/nowandforever/p/4547681.html