题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5025
3 1 K.S ##1 1#T 3 1 K#T .S# 1#. 3 2 K#T .S. 21. 0 0
5 impossible 8
题意:
给一个地图,孙悟空(K)救唐僧(T),地图中‘S‘表示蛇,第一次到这要杀死的蛇(蛇最多5条),多花费一分钟,‘1‘~‘m‘表示m个钥匙(m<=9),孙悟空要依次拿到这m个钥匙,然后才能去救唐僧,集齐m个钥匙之前可以经过唐僧,集齐x个钥匙以前可以经过x+1,x+2..个钥匙,问最少多少步救到唐僧。
思路:
BFS,每个节点维护四个值:
x,y : 当前坐标
key :已经集齐了key个钥匙
step:已经走了多少步
代码如下:
#include <cstdio>
#include <cstring>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
const int MAXN = 117;
int dir[4][2]= {1,0,0,1,0,-1,-1,0,};
char mm[MAXN][MAXN];
int vis[17][MAXN][MAXN];
struct MM
{
int x, y;
int step;
int key;
set<pair<int, int > >se;
};
int n, m;
int check(int x, int y)
{
if(x>=0&&x<n&&y>=0&&y<n)
return 1;
return 0;
}
queue<MM>q;
int BFS(int x, int y)
{
MM next, tt, fro;
fro.step = 0, fro.key = 0;
fro.x = x, fro.y = y;
q.push(fro);
while(!q.empty())
{
tt = q.front();
q.pop();
for(int i = 0; i < 4; i++)
{
int xx = tt.x+dir[i][0];
int yy = tt.y+dir[i][1];
if(check(xx,yy) && mm[xx][yy]!='#')
{
next.se = tt.se;
if(mm[xx][yy]=='S' && next.se.find(make_pair(xx,yy))==next.se.end())
{
next.step = tt.step+2;
next.se.insert(make_pair(xx,yy));
}
else
{
next.step = tt.step+1;
}
next.x = xx, next.y = yy;
if(mm[xx][yy] == tt.key+1+'0')
{
next.key = tt.key+1;
}
else
next.key = tt.key;
if(next.step<vis[next.key][xx][yy] || vis[next.key][xx][yy]==-1)
{
vis[next.key][xx][yy] = next.step;
q.push(next);
}
}
}
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(mm[i][j] == 'T')
{
return vis[m][i][j];
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
if(n==0 && m==0)
break;
memset(vis,-1,sizeof(vis));
while(!q.empty())
{
q.pop();
}
for(int i = 0; i < n; i++)
{
scanf("%s",mm[i]);
}
int ans = -1;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(mm[i][j] == 'K')
{
ans = BFS(i,j);
// break;
}
}
}
if(ans == -1)
{
printf("impossible\n");
}
else
printf("%d\n",ans);
}
return 0;
}
HDU 5025 Saving Tang Monk(BFS+状压)
原文地址:http://blog.csdn.net/u012860063/article/details/39480021