题目链接[http://acm.nyist.net/JudgeOnline/problem.php?pid=1100]
题意很好懂,bfs+优先队列
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<queue>
#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_queue<node>q;
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;i<n;i++)
{
scanf("%s",map[i]);
for(int j=0;j<m;j++)
{
if(map[i][j]=='s')
sx=i,sy=j;
}
}
int ans=bfs(sx,sy);
printf("%d\n",ans);
}
return 0;
}