题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1242
题意简单,Angel要救他的朋友,"." 代表道路,,"a" 代表Angel,"r" 代表Angel的朋友,"x"代表敌人,每走一步需要一秒钟,杀死一个敌人需要一秒钟,问Angel最少多少秒能救他的朋友。
简单广搜 BFS,当然DFS也行,不过一般有个结论:问最少多少秒到达用BFS,问能否到达用DFS。
BFS 代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/
struct xh
{
int x,y,s;//s 记录步数
}w,ww;
char maps[205][205];
int visit[205][205];
int n,m,flag;
int xb,yb;
int t[4][2]={-1,0,1,0,0,-1,0,1};
bool panduan(int x,int y)
{
return x>=1&&x<=n&&y>=1&&y<=m;
}
void bfs()
{
queue<xh>q;
w.s=0;
w.x=xb;
w.y=yb;
q.push(w);
visit[xb][yb]=0;
while(!q.empty())
{
ww=q.front();
q.pop();
if(maps[ww.x][ww.y]=='r')
{
printf("%d\n",ww.s);
flag=1;
return ;
}
for(int i=0;i<4;i++)
{
w=ww;
w.x+=t[i][0];
w.y+=t[i][1];
if(panduan(w.x,w.y)&&maps[w.x][w.y]!='#')
{
if(maps[w.x][w.y]=='x')
w.s+=2;
else
w.s++;
if(visit[w.x][w.y]>=w.s)
{
visit[w.x][w.y]=w.s;
q.push(w);
}
}
}
}
}
int main()
{
int i,j,k;
while(cin>>n>>m)
{
for(i=1;i<=n;i++)
{
getchar();
for(j=1;j<=m;j++)
{
scanf("%c",&maps[i][j]);
if(maps[i][j]=='a')
{
xb=i;yb=j;
}
}
}
memset(visit,1,sizeof(visit));//将visit初始化大一些
flag=0;
bfs();
if(!flag)
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 520;
}
优先队列代码(A*算法):对于这道题其实和上面的差不多,但是有些题用优先队列更省时
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/
char maps[205][205];
int visit[205][205];
int n,m,flag;
int xb,yb,xe,ye;
int t[4][2]={-1,0,1,0,0,-1,0,1};
struct xh
{
int x,y,s;//s 记录步数+目标函数
bool operator <(const xh t) const
{
return (s+abs(x-xe)+abs(y-ye))>(t.s+abs(t.x-xe)+abs(t.y-ye));//目标函数
}
}w,ww;
bool panduan(int x,int y)
{
return x>=1&&x<=n&&y>=1&&y<=m;
}
void bfs()
{
priority_queue<xh>q;//优先队列
w.s=0;
w.x=xb;
w.y=yb;
q.push(w);
visit[xb][yb]=0;
while(!q.empty())
{
ww=q.top();
q.pop();
if(maps[ww.x][ww.y]=='r')
{
printf("%d\n",ww.s);
flag=1;
return ;
}
for(int i=0;i<4;i++)
{
w=ww;
w.x+=t[i][0];
w.y+=t[i][1];
if(panduan(w.x,w.y)&&maps[w.x][w.y]!='#')
{
if(maps[w.x][w.y]=='x')
w.s+=2;
else
w.s++;
if(visit[w.x][w.y]>=w.s)
{
visit[w.x][w.y]=w.s;
q.push(w);
}
}
}
}
}
int main()
{
int i,j;
while(cin>>n>>m)
{
for(i=1;i<=n;i++)
{
getchar();
for(j=1;j<=m;j++)
{
scanf("%c",&maps[i][j]);
if(maps[i][j]=='a')
{
xb=i;yb=j;
}
if(maps[i][j]=='r')
{
xe=i;ye=j;
}
}
}
memset(visit,1,sizeof(visit));//将visit初始化大一些
flag=0;
bfs();
if(!flag)
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 520;
}