来源:点击打开链接
终于把BFS看水了,包括路径优化和奇偶剪枝。一年了也就看明白了这点东西,so sad。。。。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int visited[205][205];
char mat[205][205];
int n,m;
int dir[4][2]={-1,0,1,0,0,1,0,-1};
class node
{
public:
int x;
int y;
int step;
};
bool judge(int x,int y)
{
if(x>=0 && x<n && y>=0 && y<m && visited[x][y]==0 && mat[x][y]!='#')
return 1;
else
return 0;
}
int bfs(node st,node ed)
{
memset(visited,0,sizeof(visited));
queue<node> q;
node first,next;
first.x=st.x;
first.y=st.y;
first.step=0;
visited[first.x][first.y]=1;
q.push(first);
while(!q.empty())
{
first=q.front();
q.pop();
for(int i=0;i<4;i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
next.step=first.step;
if(next.x==ed.x && next.y==ed.y)
return next.step+1;
if(judge(next.x,next.y) && mat[next.x][next.y]=='.')
{
next.step+=1;
visited[next.x][next.y]=1;
q.push(next);
}
if(judge(next.x,next.y) && mat[next.x][next.y]=='x')
{
next.step+=2;
visited[next.x][next.y]=1;
q.push(next);
}
}
}
return -1;
}
int main()
{
while(cin>>n>>m)
{
node s1,e1;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mat[i][j];
if(mat[i][j]=='a')
{
s1.x=i;
s1.y=j;
}
if(mat[i][j]=='r')
{
e1.x=i;
e1.y=j;
}
}
}
int res=bfs(s1,e1);
if(res!=-1)
{
cout<<res<<endl;
}
else
{
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
}
return 0;
}