【題目】
Rescue
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 21820 Accepted Submission(s): 7774
Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.
You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)
Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.
Process to the end of the file.
【思路】
【代碼】
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace std;
#define INF 1e9
int n,m,dp[205][205],ex,ey,ans;
char ma[205][205];
bool vis[205][205];
const int dx[4]={0,0,1,-1};
const int dy[4]={1,-1,0,0};
void dfs(int x,int y)
{
if(dp[x][y]>=dp[ex][ey]) return;
for(int i=0;i<4;++i)
{
int xx=x+dx[i];
int yy=y+dy[i];
if(ma[xx][yy]=='#'||vis[xx][yy]) continue;//這裏錯寫成break了調了半天T_T
if(ma[xx][yy]=='x')
{
if(dp[xx][yy]==-1||dp[xx][yy]>dp[x][y]+2)
dp[xx][yy]=dp[x][y]+2;
else continue;
}
else if(ma[xx][yy]=='a')
{
if(dp[xx][yy]==-1||dp[xx][yy]>dp[x][y]+1)
dp[xx][yy]=dp[x][y]+1;
return;
}
else if(ma[xx][yy]=='.')
{
if(dp[xx][yy]==-1||dp[xx][yy]>dp[x][y]+1)
dp[xx][yy]=dp[x][y]+1;
else continue;
}
vis[xx][yy]=true;
dfs(xx,yy);
vis[xx][yy]=false;
}
}
int main()
{
ios::sync_with_stdio(false);
int sx,sy;
while(cin>>n>>m)
{
memset(ma,'#',sizeof(ma));
memset(vis,0,sizeof(vis));
ex=ey=-1;
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
{
dp[i][j]=-1;
cin>>ma[i][j];
if(ma[i][j]=='r')
{
sx=i;
sy=j;
}
if(ma[i][j]=='a')
{
ex=i;
ey=j;
dp[i][j]=INF;
}
}
if(ex==-01&&ey==-1)
{
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
continue;
}
dp[sx][sy]=0;
dfs(sx,sy);
if(dp[ex][ey]!=INF)
cout<<dp[ex][ey]<<endl;
else
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
}
//system("pause");
return 0;
}