【简单的spfa+优先队列】

题目是给出只有x和y构成的图,相同元素走路不花费,不同元素间花费1,给出起点终点,最少花费是

#include<cstdio>
#include<algorithm>
#include<math.h>
#include<queue>
#include<string.h>
using namespace std;
const int maxn=110;
int nxt[4][2]={ {0,1},{0,-1},{-1,0},{1,0} };
int vis[maxn][maxn];
char a[maxn][maxn];
int n,m;
int tx,ty,endx,endy;
struct node
{
int x,y,step;
};
bool operator<(node a,node b)
{
return a.step>b.step;
}
priority_queue<node>q;
int bfs()
{
while(!q.empty()) q.pop();
memset(vis,0,sizeof(vis));
node temp;
temp.x=tx,temp.y=ty,temp.step=0;
q.push(temp);
vis[tx][ty]=1;
while(!q.empty()){
node t=q.top();
q.pop();
for(int i=0;i<=3;i++){
int nowx=t.x+nxt[i][0];
int nowy=t.y+nxt[i][1];
if(nowx<0||nowy<0||nowx>=n||nowy>=m) continue;
if(vis[nowx][nowy]) continue;
vis[nowx][nowy]=1;
node tmp;
tmp.x=nowx,tmp.y=nowy;
if(a[tmp.x][tmp.y]==a[t.x][t.y]) tmp.step=t.step;
else tmp.step=t.step+1;
if(nowx==endx&&nowy==endy){
return tmp.step;
}
else q.push(tmp);
}
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=0;i<n;i++){
scanf("%s",a[i]);
}
scanf("%d%d%d%d",&tx,&ty,&endx,&endy);
int ans=bfs();
printf("%d\n",ans);
}
return 0;
}

原文地址:https://www.cnblogs.com/hgangang/p/11526949.html