链接:点击打开链接
这个是r去救a,遇到x先要杀死,然后才能走,花时间2,遇到点就花时间1.
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
#define N 210
struct ss{
int x;
int y;
int time;
};
char map[N][N];
int sx,sy,vis[N][N],n,m,a[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
void bfs(){
int i;
queue<ss>Q;
ss p,s;
p.x=sx;p.y=sy;p.time=0;
Q.push(p);
vis[sx][sy]=1;
while(!Q.empty()){
p=Q.front();
Q.pop();
if(map[p.x][p.y]=='x'){
p.time++;
map[p.x][p.y]='.';
Q.push(p);
}
else{
for(i=0;i<4;i++){
s=p;
s.x+=a[i][0];s.y+=a[i][1];
if(vis[s.x][s.y]==0&&map[s.x][s.y]!='#'&&s.x>0&&s.x<=n&&s.y>0&&s.y<=m){
s.time++;
if(map[s.x][s.y]=='a'){
printf("%d\n",s.time);
return;
}
vis[s.x][s.y]=1;
Q.push(s);
}
}
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main(){
int i,j;
while(~scanf("%d %d",&n,&m)){
for(i=1;i<=n;i++){
getchar();
for(j=1;j<=m;j++){
scanf("%c",&map[i][j]);
if(map[i][j]=='r'){
sx=i;
sy=j;
}
}
//getchar();
}
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}
优先队列:
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
#define N 210
struct ss{
int x;
int y;
int time;
friend bool operator<(ss a,ss b){
return a.time>b.time;
};
};
char map[N][N];
int sx,sy,vis[N][N],n,m,a[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
void bfs(){
int i;
priority_queue<ss>Q;
ss p,s;
p.x=sx;p.y=sy;p.time=0;
Q.push(p);
vis[sx][sy]=1;
while(!Q.empty()){
p=Q.top();
Q.pop();
if(map[p.x][p.y]=='x'){
p.time++;
map[p.x][p.y]='.';
Q.push(p);
}
else{
for(i=0;i<4;i++){
s=p;
s.x+=a[i][0];s.y+=a[i][1];
if(vis[s.x][s.y]==0&&map[s.x][s.y]!='#'&&s.x>0&&s.x<=n&&s.y>0&&s.y<=m){
s.time++;
if(map[s.x][s.y]=='a'){
printf("%d\n",s.time);
return;
}
vis[s.x][s.y]=1;
Q.push(s);
}
}
}
}
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
int main(){
int i,j;
while(~scanf("%d %d",&n,&m)){
for(i=1;i<=n;i++){
getchar();
for(j=1;j<=m;j++){
scanf("%c",&map[i][j]);
if(map[i][j]=='r'){
sx=i;
sy=j;
}
}
//getchar();
}
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}