您的位置:首页 > 其它

hdu 1175 连连看 (DFS)

2013-06-22 19:06 417 查看
#include<stdio.h>
#include<string.h>
int flag,map[1005][1005],v[1005][1005];
int n,m,start_x,start_y,end_x,end_y,f[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
void dfs(int x,int y,int num,int d)
{
if(num > 2) return ;
if(num == 2 && x - end_x !=0 && y - end_y != 0) return;//剪枝,不剪时间直接蹦到8000+
if(num <= 2 && x == end_x && y == end_y)
{
flag = 1;
return ;
}
if(flag)  return ;
for(int i = 0 ; i < 4 ; i ++)
{
int fx = x + f[i][0];
int fy = y + f[i][1];
if(v[fx][fy]) continue;
if(fx > 0 && fx <= n && fy > 0 && fy <= m && ( map[fx][fy] == 0 || (fx == end_x && fy == end_y) ) )
{
if(d != -1 && i != d)//判断方向是否改变
num ++;
v[fx][fy] = 1;
dfs(fx,fy,num,i);
v[fx][fy] = 0;
if(d != -1 && i != d)
num -- ;
}
}

}
int main()
{
int i,j,T;
while(scanf("%d%d",&n,&m) && (n + m))
{
for(i = 1 ; i <= n ; i ++)
for(j = 1 ; j <= m ; j ++)
scanf("%d",&map[i][j]);
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d",&start_x,&start_y,&end_x,&end_y);
if(start_x == end_x && start_y == end_y) continue;
if(!map[start_x][start_y] || !map[end_x][end_y] || map[start_x][start_y] != map[end_x][end_y])
{
printf("NO\n");
continue;
}
memset(v,0,sizeof(v));
flag = 0;
v[start_x][start_y] = 1;
dfs(start_x,start_y,0,-1);
v[start_x][start_y] = 0;
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DFS