nyoj1100

题目链接[http://acm.nyist.net/JudgeOnline/problem.php?pid=1100]

题意很好懂,bfs+优先队列

#include
#include
#include
#include
#include
#include
#define maxn 1005
using namespace std;
char map[maxn][maxn];
int vis[maxn][maxn];
int n,m;
int dx[4]= {0,0,1,-1};
int dy[4]= {1,-1,0,0};
int sx,sy;//起始坐标
struct node
{
    int x,y,cost;
    bool friend operator<(node a,node b)
    {
        return a.cost>b.cost;//最小值优先
    }
};
bool judge(node s)
{
    if(s.x<0||s.x>=n||s.y<0||s.y>=m)
        return false;
    if(map[s.x][s.y]=='#'||vis[s.x][s.y])
        return false;
    return true;
}
int bfs(int x,int y)
{
    priority_queueq;
    node now,next;
    memset(vis,0,sizeof(vis));
    now.x=x,now.y=y,now.cost=0;
    vis[now.x][now.y]=1;
    q.push(now);
    while(!q.empty())
    {
        now=q.top();
        q.pop();
        for(int i=0; i<4; i++)
        {
            next.x=now.x+dx[i];
            next.y=now.y+dy[i];
            if(judge(next))
            {
                if(map[next.x][next.y]=='l')
                {
                    return now.cost;//已经找到目的地,不用再交生活费了
                }
                else
                    next.cost=now.cost+map[next.x][next.y]-'@';
                vis[next.x][next.y]=1;
                q.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i=0;iscanf("%s",map[i]);
            for(int j=0;jif(map[i][j]=='s')
                    sx=i,sy=j;
            }
        }
      int ans=bfs(sx,sy);
      printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(搜索)