您的位置:首页 > 其它

hdu 1175 连连看 dfs

2013-07-24 09:37 465 查看
/*



简单的dfs,四个方向搜索,搜过的路标记掉,这个标记着来的方向,找到了return;

为了省时用了一些剪枝和特殊的输入方法

*/

#include<iostream>
#include<string>
using namespace std;
int ans, n, m, s_x, s_y, e_x, e_y;
int map[1002][1002], dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//右上下左

int A()//减时间的输入方式
{
char c;
int temp = 0;
while((c=getchar()) < '0' || c > '9');
temp = c - '0';
while((c=getchar()) >= '0' && c <= '9') temp = temp * 10 + (c-'0');
return temp;
}

void DFS(int x, int y, int times, int d)
{
if(times > 3)
return ;

if(times == 3 && x-e_x != 0 && y-e_y != 0) //大神支招,当有两个转角是终点还是不在该直线上,就剪枝
return ;

if(times <= 3 && x == e_x && y == e_y)
{
ans = 1;
return ;
}

int i;
for( i=0; i < 4; i++ )
{
int next_x = x + dir[i][0];
int next_y = y + dir[i][1];
if(next_x > 0 && next_x <= n && next_y > 0 && next_y <= m)
{
if(map[next_x][next_y] == 0 )
{
if(i-5 != d)
times++;
map[next_x][next_y] = i-5;
DFS(next_x, next_y, times, i-5);
map[next_x][next_y] = 0;
if(i-5 != d && ans == 0)
times--;
}
}

}
}

int main()
{
int i, j, num;
while((n = A(), m = A()) && (n||m) )
{
//memset(dig, 0, sizeof(dig));
memset(map, 0, sizeof(map));
for( i=1; i <= n; i++ )
{
for( j=1; j <= m; j++ )
map[i][j] = A();
//scanf("%d", &map[i][j]);
}
num = A();
//scanf("%d", &num);
for( i=0; i < num; i++ )
{
ans = 0;
s_x = A();
s_y = A();
e_x = A();
e_y = A();
//scanf("%d%d%d%d", &s_x, &s_y, &e_x, &e_y);
if(map[s_x][s_y] != map[e_x][e_y] || (map[e_x][e_y] == map[s_x][s_y] && map[s_x][s_y] == 0))
{
cout << "NO" << endl;
continue;
}
if(s_x == e_x && s_y == e_y)
{
cout << "NO" << endl;
continue;
}
int t1 = map[e_x][e_y];
int t2 = map[s_x][s_y];
map[s_x][s_y] = -1;
map[e_x][e_y] = 0;
DFS(s_x, s_y, 0, -1);
map[s_x][s_y] = t2;
map[e_x][e_y] = t1;

if(ans)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
return 0;
}
/*
3 4
1 2 3 4
0 0 0 4
2 3 0 1
5
1 1 3 4

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: