hdu 1175 连连看 dfs

本文介绍了一种基于深度优先搜索(DFS)的迷宫路径寻找算法。通过四个方向的递归搜索来寻找从起点到终点的可行路径,并采用剪枝技巧来减少不必要的搜索,提高效率。文中提供了一个实现该算法的C++程序示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*




简单的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

  */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值