描述
我知道你们不想看英语….
输入
The input consists of multiple test cases. The first line of each test case contains two integers M and N (1 < N, M < 20), which denote the size of the maze. The next M lines give the maze layout, with each line containing N characters. A character is one of the following: ‘X’ (a block of wall, which the explorer cannot enter), ‘.’ (an empty block), ‘S’ (the start point of Acm), ‘G’ (the position of treasure), ‘A’, ‘B’, ‘C’, ‘D’, ‘E’ (the doors), ‘a’, ‘b’, ‘c’, ‘d’, ‘e’ (the keys of the doors). The input is terminated with two 0’s. This test case should not be processed.
输出
For each test case, in one line output “YES” if Acm can find the treasure, or “NO” otherwise.
样例输入
4 4
S.X.
a.X.
..XG
….
3 4
S.Xa
.aXB
b.AG
0 0
样例输出
YES
NO
我知道你们不想看英语…
翻译:
题目描述
给你一张地图,上面有几个门和门对应的钥匙,你只有在:持有这扇门所有的钥匙的情况下才能开这扇门,给你起点终点,求能不能到终点。
输入
多组数据….大写字母代表门,小写字母代表大写字母的门对应的钥匙。S起点,G终点,X是墙不能走。
n==0&&m==0时退出
输出
YES or NO
这个题DFS BFS都能做,个人感觉DFS好打些?
DFS:
从起点出发….如果能拿到一种门的全部要是,就把这个门开掉,然后把vis数组清成可走,继续跑DFS,如果能到终点,就输出YES,到不了就输出NO。
(这次题解好短..)
DFS代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<queue>
using namespace std;
int n,m;
int sx,sy;
int ex,ey;
int ktot[30];
int key[30][30];
int door[30][30];
bool map[30][30];
bool vis[30][30];
int xx[]={0,1,0,-1,0};
int yy[]={0,0,1,0,-1};
bool flag;
void clr()
{
flag=0;
memset(map,0,sizeof(map));
memset(ktot,0,sizeof(ktot));
memset(key,0,sizeof(key));
memset(door,0,sizeof(door));
for(int i=1;i<=25;i++)
for(int j=1;j<=25;j++)
vis[i][j]=1;
}
void kaimen(int num)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(door[i][j]==num)
map[i][j]=1;
}
}
memset(vis,1,sizeof(vis));
}
void dfs(int x1,int yy1)
{
for(int i=1;i<=4;i++)
{
int x=x1+xx[i];
int y=yy1+yy[i];
if(map[x][y])
{
if(vis[x][y])
{
vis[x][y]=0;
if(key[x][y])
{
int num=key[x][y];
ktot[num]--;
key[x][y]=0;
if(ktot[num]<=0)
{
kaimen(num);
dfs(sx,sy);
}
}
if(x==ex&&y==ey)
{
flag=1;
return;
}
dfs(x,y);
}
}
}
}
int main()
{
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0)
break;
clr();
char hah[30];
for(int i=1;i<=n;i++)
{
scanf("%s",hah);
for(int j=0;j<m;j++)
{
map[i][j+1]=1;
if(hah[j]=='X')
map[i][j+1]=0;
else if(hah[j]=='S')
sx=i,sy=j+1;
else if(hah[j]=='G')
ex=i,ey=j+1;
else if(hah[j]<='e'&&hah[j]>='a')
key[i][j+1]=hah[j]-'a'+1,ktot[hah[j]-'a'+1]++;
else if(hah[j]<='E'&&hah[j]>='A')
door[i][j+1]=hah[j]-'A'+1,map[i][j+1]=0;
}
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
vis[i][j]=1;
vis[sx][sy]=0;
dfs(sx,sy);
if(flag)
puts("YES");
else
puts("NO");
}
return 0;
}
BFS,我们可以开两个队列,一个队列是BFS的队列,当我们遇到门的时候,把当前节点扔到第二个队列,然后继续跑第一个队列,捡到钥匙就记录一下,当第一个队列空的时候,就跑第二个队列,能开门就扩展,直到两个队列都空。
代码不贴了……