HDU T1242 Rescue
题解:
基础题,可是鄙人因为有处if没加花括号而找了好久的bug,粗心了......
第一次看到这题的时候,以为天使有多个朋友,就从天使开始向外遍历,其实都差不多,一股清流......
因为数据范围比较小,所以dfs和bfs都可以写。
Dfs写法
#include<cstdio>
#include<iostream>
#include<algorithm>
#define maxn 205
#define INF 0x3f3f3f3f
using namespace std;
int n,m,ans,mov[4][2] = {-1,0,0,1,1,0,0,-1};
char maps[maxn][maxn];
bool vis[maxn][maxn];
bool charge(int x,int y){
if(x < 0||x > n-1 || y < 0 || y > m-1 || maps[x][y] == '#')
return false;
return true;
}
void Dfs(int x,int y,int st){
if(maps[x][y] == 'r'){
ans = min(st,ans);
return;
}
for(int i = 0;i < 4; ++i){
int nx = x + mov[i][0];
int ny = y + mov[i][1];
if(charge(nx,ny) && !vis[nx][ny]){ //这里直接进行剪枝
vis[nx][ny] = true; //鄙人开了标记的数组,只是想牺牲空间求代码精简
if(maps[nx][ny] == 'x')
Dfs(nx,ny,st+2);
else
Dfs(nx,ny,st+1);
vis[nx][ny] = false;
}
}
}
int main(){
int x,y;
while(~scanf("%d%d",&n,&m)){
ans = INF;
for(int i = 0; i < n; ++i){
scanf("%s",&maps[i]);
for(int j = 0; j < m; ++j){
if(maps[i][j] == 'a'){
x = i;y = j;
}
vis[i][j] = false;
}
}
vis[x][y] = true;
Dfs(x,y,0);
if(ans == INF)
puts("Poor ANGEL has to stay in the prison all his life.");
else
printf("%d\n",ans);
}
return 0;
}
Bfs写法 + 优先队列
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#define maxn 205
#define INF 0x3f3f3f3f
using namespace std;
int n,m,ans,mov[4][2] = {-1,0,0,1,1,0,0,-1};
char maps[maxn][maxn];
bool vis[maxn][maxn];
struct Node{
int x,y,st;
friend bool operator < (Node a,Node b){ //重载操作符
return b.st < a.st;
}
}now,nex;
bool charge(int x,int y){
if(x < 0||x > n-1 || y < 0 || y > m-1 || maps[x][y] == '#')
return false;
return true;
}
int Bfs(int x,int y,int st){
now.x = x;
now.y = y;
now.st = st;
priority_queue<Node> Q;
Q.push(now);
while(!Q.empty()){
now = Q.top();
Q.pop();
if(maps[now.x][now.y] == 'r') //因为用的优先队列,所以最短的路径在最前面,找到直接返回
return now.st;
for(int i = 0; i < 4; ++i){
nex.x = now.x + mov[i][0];
nex.y = now.y + mov[i][1];
if(charge(nex.x,nex.y) && !vis[nex.x][nex.y]){
vis[nex.x][nex.y] = true;
if(maps[nex.x][nex.y] == 'x')
nex.st = now.st + 2;
else
nex.st = now.st + 1;
Q.push(nex);
}
}
}
return 0; //没有路径
}
int main(){
int x,y;
while(~scanf("%d%d",&n,&m)){
for(int i = 0; i < n; ++i){
scanf("%s",&maps[i]);
for(int j = 0; j < m; ++j){
if(maps[i][j] == 'a'){
x = i;y = j;
}
vis[i][j] = false; //初始化标记数组
}
}
vis[x][y] = true;
ans = Bfs(x,y,0);
if(ans == 0)
puts("Poor ANGEL has to stay in the prison all his life.");
else
printf("%d\n",ans);
}
return 0;
}