HDU 1175 连连看(bfs)

连连看

Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 39459    Accepted Submission(s): 9783


Problem Description
“连连看”相信很多人都玩过。没玩过也没关系,下面我给大家介绍一下游戏规则:在一个棋盘中,放了很多的棋子。如果某两个相同的棋子,可以通过一条线连起来(这条线不能经过其它棋子),而且线的转折次数不超过两次,那么这两个棋子就可以在棋盘上消去。不好意思,由于我以前没有玩过连连看,咨询了同学的意见,连线不能从外面绕过去的,但事实上这是错的。现在已经酿成大祸,就只能将错就错了,连线不能从外围绕过。
玩家鼠标先后点击两块棋子,试图将他们消去,然后游戏的后台判断这两个方格能不能消去。现在你的任务就是写这个后台程序。
 

Input
输入数据有多组。每组数据的第一行有两个正整数n,m(0注意:询问之间无先后关系,都是针对当前状态的!
 

Output
每一组输入数据对应一行输出。如果能消去则输出"YES",不能则输出"NO"。
 

Sample Input
 
   
3 4
1 2 3 4
0 0 0 0
4 3 2 1
4
1 1 3 4
1 1 2 4
1 1 3 3
2 1 2 4
3 4
0 1 4 3
0 2 4 1
0 0 0 0
2
1 1 2 4
1 3 2 3
0 0
 

Sample Output
 
   
YES
NO
NO
NO
NO
YES


    这个题我都不知道什么时候做过,于是又用了原来的dfs做了一遍,竟然一直超时,然后又找到原来的的代码,提交是900多MS,最后选择了bfs , 也不用剪枝,也不咋会剪枝。bfs才100多MS

#include
#include
#include
using namespace std;
int f[4][2]={0,1,1,0,0,-1,-1,0};
int vis[1005][1005];
int mat[1005][1005];
int x1,x2,y1,y2;
int n,m,flag;
struct node{
	int x,y;//坐标 
	int temp;//步数 
	int dire;//方向 
	int turn;//转折数 
};
void bfs()
{
	node s,t;
	queueq;
	s.x = x1;
	s.y = y1;
	s.dire =0;
	s.turn =0;
	s.temp =0;
	vis[x1][y1]=1;
	q.push(s);
	while(!q.empty())
	{
		t=q.front();
		q.pop();
		if(t.x==x2&&t.y==y2&&t.turn<=2)
		{
			flag=1;
			return;
		}
		for(int i=0;i<4;i++)
		{
			s=t;
			s.x =t.x +f[i][0];
			s.y =t.y +f[i][1];
			s.temp=t.temp +1;
			if(s.x >n||s.y>m||s.x<=0||s.y<=0||vis[s.x][s.y]||mat[s.x][s.y]!=0)//边界判断 
				continue;
			if(s.dire!=0&&s.dire!=i+1)//当前方向不一致,需要转折 
			{
				s.dire =i+1;
				s.turn +=1;
				if(s.turn >2)//转折数>2,不行,continue 
					continue;
			}
			else
			{
				s.dire =i+1;//方向一致,记录方向 
			}
			vis[s.x ][s.y ]=1;
			q.push(s);
		}
	}
	return;
}
int main()
{
	int t;
	while(~scanf("%d%d",&n,&m)&&n&&m)
	{
		for(int i=1;i<=n;i++)
			for(int j=1;j<=m;j++)
				scanf("%d",&mat[i][j]);
		scanf("%d",&t);
		while(t--)
		{
			flag=0;
			memset(vis,0,sizeof(vis));
			scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
			if(x1==x2&&y1==y2||mat[x1][y1]==0||mat[x2][y2]==0||mat[x1][y1]!=mat[x2][y2])
			{
				printf("NO\n");
				continue;
			}
			int st=mat[x1][y1];//先将起点终点值变为0 
			int end=mat[x2][y2];
			mat[x1][y1]=0;
			mat[x2][y2]=0;
			bfs();
			if(flag)
				printf("YES\n");
			else
				printf("NO\n");
			mat[x1][y1]=st;//再变回来,否则影响下一次判断 
			mat[x2][y2]=end;
		}
	}
	return 0;
}

你可能感兴趣的:(搜索(bfs&&dfs))