广搜

来源:互联网 发布:崔永元 知乎 编辑:程序博客网 时间:2024/04/19 09:28
不多说,看描述

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

经典广收,直接贴代码:

  1. #include
  2. #include
  3. #include
  4. using namespace std;
  5. #define maxn 1005
  6. int map[maxn][maxn];
  7. int d[maxn][maxn];
  8. int m, n, x2, y2;
  9. int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
  10. struct node
  11. {
  12. int k, ways, x, y;
  13. friend bool operator < (node a, node b)
  14. {
  15. return a.k > b.k;
  16. }
  17. };

  18. int bfs(int x1, int y1);
  19. void clean();

  20. int main()
  21. {
  22. while(scanf("%d%d", &m, &n), m || n)
  23. {
  24. for(int i=1; i<=m; i++)
  25. for(int j=1; j<=n; j++)
  26. scanf("%d", &map[i][j]);

  27. int T, x1, y1;

  28. scanf("%d", &T);

  29. while(T--)
  30. {
  31. scanf("%d%d%d%d", &x1, &y1, &x2, &y2);

  32. if(!map[x1][y1] || map[x1][y1]!=map[x2][y2] || x1==x2&&y1==y2)
  33. {
  34. printf("NO\n");
  35. continue;
  36. }
  37. clean();
  38. int res = bfs(x1, y1);

  39. if(res)
  40. printf("YES\n");
  41. else
  42. printf("NO\n");
  43. }
  44. }

  45. return 0;
  46. }
  47. int bfs(int x1, int y1)
  48. {
  49. priority_queue que;
  50. node q, s;
  51. d[x1][y1] = q.k = -1, q.ways = -1, q.x = x1, q.y = y1;
  52. que.push(q);

  53. while(que.size())
  54. {
  55. q = que.top(), que.pop();

  56. if(q.k == 3)break;
  57. if(q.x == x2 && q.y == y2)return 1;

  58. for(int i=0; i<4; i++)
  59. {
  60. s.x = q.x + dir[i][0], s.y = q.y + dir[i][1];

  61. if(s.x>0&&s.x<=m && s.y>0&&s.y<=n && !map[s.x][s.y] || s.x==x2 && s.y==y2)
  62. {
  63. if(q.ways != i)s.k = q.k + 1;
  64. else s.k = q.k;
  65. s.ways = i;

  66. if(s.k <= d[s.x][s.y])
  67. {
  68. d[s.x][s.y] = s.k;
  69. que.push(s);
  70. }
  71. }
  72. }
  73. }

  74. return 0;
  75. }
  76. void clean()
  77. {
  78. for(int i=0; i<=m; i++)
  79. for(int j=0; j<=n; j++)
  80. d[i][j] = 10;
  81. }
0 0
原创粉丝点击