您的位置:首页 > 其它

HDU 1175 连连看 bfs + 优先队列

2016-11-08 09:29 288 查看

题目:

http://acm.hdu.edu.cn/showproblem.php?pid=1175

题意:

Problem Description

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

玩家鼠标先后点击两块棋子,试图将他们消去,然后游戏的后台判断这两个方格能不能消去。现在你的任务就是写这个后台程序。

Input

输入数据有多组。每组数据的第一行有两个正整数n,m(0

思路:

bfs + 优先队列,转弯次数少的先出队,这样可以保证到达终点的路径转弯次数最少,符合题目要求。这么一个简单bfs被窝写搓了,真气,刚开始我把所有能到达的点无论到达此点转弯几次都入队,然后出队的点的转弯次数大于2时直接返回false,一直WA,后来想到一个点最多可由另外四个点到达,可能从这四个点中的某个点到达此点时转弯次数超过了2,而我之前的写法是直接就入队了,但可能从另外的点到达此点转弯次数不超过2,于是我就错了。。。因此只把转弯次数不超过2的点入队,这样就可以避免此类问题

#include <bits/stdc++.h>
using namespace std;

const int N = 1010;
struct node
{
int x, y, dir, num;
node(int x = 0, int y = 0, int dir = 0, int num = 0)
{
this->x = x, this->y = y, this->dir = dir, this->num = num;
}
friend bool operator< (node a, node b)
{
return a.num > b.num;
}
}p, e;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1};
int mat

;
bool vis

;
int n, m, q;
bool bfs(int x1, int y1, int x2, int y2)
{
priority_queue<node> que;
memset(vis, 0, sizeof vis);
que.push(node(x1, y1, -1, -1)), vis[x1][y1] = true;
while(! que.empty())
{
p = que.top(); que.pop();
if(p.x == x2 && p.y == y2) return p.num <= 2;
for(int i = 0; i < 4; i++)
{
int nx = p.x + dx[i], ny = p.y + dy[i];
if(nx >= 1 && nx <= n && ny >= 1 && ny <= m && (mat[nx][ny] == 0 || (nx == x2 && ny == y2)) && !vis[nx][ny])
{
if(p.dir == i) que.push(node(nx, ny, i, p.num)), vis[nx][ny] = true;
else
{
if(p.num + 1 <= 2) que.push(node(nx, ny, i, p.num+1)), vis[nx][ny] = true;
}
}
}
}
return false;
}
int main()
{
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", &q);
while(q--)
{
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
if(mat[x1][y1] != mat[x2][y2] || mat[x1][y1] == 0 || mat[x2][y2] == 0 || (x1 == x2 && y1 == y2))
{
printf("NO\n"); continue;
}
if(bfs(x1, y1, x2, y2)) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: