不知道为什么思路都是一样的偶写滴就超时= =
我写的
#include<stdio.h>
#include<string.h>
int m,n,x1,y1,flag,key[5],i,j;
char map[20][20],f[20][20];
void dfs(int x,int y)
{
if(x<0||y<0||x>=m||y>=n||map[x][y]=='X'){
return ;
}
if(map[x][y]=='G')
{
flag=1;
return ;
}
else if(map[x][y]>='a'&&map[x][y]<='e')
{
key[map[x][y]-'a']--;
map[x][y]='.';
}
else if(map[x][y]>='A'&&map[x][y]<='E')
{
if(key[map[x][y]-'A']==0)
{
map[x][y]='.';
}
else
{
return ;
}
}
if(x>=0&&x<m&&y>=0&&y<n&&map[x][y]=='.')
{
map[x][y]='X';
dfs(x-1,y);
dfs(x+1,y);
dfs(y,y-1);
dfs(x,y+1);
map[x][y]='.';
}
return ;
}
int main(){
while(scanf("%d %d",&m,&n)!=EOF)
{
memset(key,0,sizeof(key));
memset(map,0,sizeof(map));
if(m==0&&n==0)
{
break;
}
for(i=0;i<m;i++)
{
scanf("%s",map[i]);
for(j=0;j<n;j++)
{
if(map[i][j]=='S')
{
x1=i;
y1=j;
}
else if(map[i][j]>='a'&&map[i][j]<='e')
{
key[map[i][j]-'a']++;
}
}
}
flag=0;
map[x1][y1]='.';
dfs(x1,y1);
if(flag)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}
AC滴
#include<stdio.h>
#include<string.h>
char map[25][25];
bool vis[25][25];
bool result;
int key[5];
int curkey[5];
int n,m;
int st_x,st_y;
struct node{
int x,y;
bool exit;
}door[5];
void check();
void dfs(int x,int y){
if(x<0||y<0||x>=m||y>=n||map[x][y]=='X'||vis[x][y]){
return ;
}
if(map[x][y]>='A'&&map[x][y]<='E'&&curkey[map[x][y]-'A']<key[map[x][y]-'A']){
door[map[x][y]-'A'].x=x;
door[map[x][y]-'A'].y=y;
door[map[x][y]-'A'].exit=true;
return ;
}
vis[x][y]=true;
if(map[x][y]>='a'&&map[x][y]<='e')
curkey[map[x][y]-'a']++;
if(map[x][y]=='G'){
result=true;
return ;
}
dfs(x+1,y);
dfs(x-1,y);
dfs(x,y-1);
dfs(x,y+1);
check();
}
void check(){
for(int i=0;i<5;i++){
if(door[i].exit){
if(curkey[i]==key[i]){
int x=door[i].x;
int y=door[i].y;
dfs(x+1,y);
dfs(x-1,y);
dfs(x,y+1);
dfs(x,y-1);
}
}
}
}
int main(){
while(scanf("%d %d",&m,&n)!=EOF){
if(m==0&&n==0){
break;
}
memset(key,0,sizeof(key));
memset(map,0,sizeof(map));
memset(vis,false,sizeof(vis));
memset(&door,0,sizeof(&door));
memset(curkey,0,sizeof(curkey));
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
char ch;
scanf(" %c",&ch);
map[i][j]=ch;
if(ch>='a'&&ch<='e')
key[ch-'a']++;
if(ch=='S')
st_x=i,st_y=j;
}
}
result=false;
dfs(st_x,st_y);
if(result)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
很累...我真的好弱啊= =