HDU 1175 连连看

这一题感觉是深搜的思路比较好想,不过容易超时,必须加些剪枝。广搜的话思路比较难想,代码也挺复杂的,我一直没编对,所以这里只有深搜的代码~

剪枝策略:

1.首先判断两点是否相等,最基础的剪枝;

2.判断起始点是否为0,为0直接输出NO;

3.当当前的路线转折数已经到2时,判断当前点与终点的横纵坐标是否至少有一个相等,如果都不相等则剪去;

AC code:

View Code
 1 #include <iostream>
2 #define MAX 1001
3 using namespace std;
4 int n, m;
5 int map[MAX][MAX];
6 bool vis[MAX][MAX];
7 int sx, sy, ex, ey;
8 int flag;
9 int d[][2] = {0, -1,-1, 0, 1, 0, 0, 1};
10
11 bool inmap(int x, int y)
12 {
13 return x >= 0 && x < n && y >= 0 && y < m;
14 }
15 void dfs(int x, int y, int count, int dir)
16 {
17 int i, tx, ty;
18 if(x == ex && y == ey && count <= 2)
19 { flag = 1; return;}
20 if(count > 2)//不加这两个剪枝也超时
21 return;
22 if(count == 2)
23 {
24 if(x != ex && y != ey)
25 return;
26 }
27 for(i = 0; i < 4; i++)
28 {
29 tx = x + d[i][0];
30 ty = y + d[i][1];
31 if(inmap(tx, ty) && !vis[tx][ty] && (map[tx][ty] == 0 || (tx == ex && ty ==ey)))
32 {
33 vis[tx][ty] = true;
34 if(dir == i)
35 dfs(tx, ty, count, dir);
36 else
37 dfs(tx, ty, count + 1, i);
38 vis[tx][ty] = false;
39 }
40 }
41 return;
42 }
43
44
45 int main()
46 {
47 int question;
48 while(scanf("%d%d", &n, &m) != EOF && n)
49 {
50 for(int i = 0; i < n; i++)
51 for(int j = 0; j < m; j++)
52 scanf("%d", &map[i][j]);
53 scanf("%d", &question);
54 while(question--)
55 {
56 scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
57 sx--;sy--;ex--;ey--;//询问时坐标是从(0,0)开始的
58 if(map[sx][sy] == 0 || (sx == ex && sy == ey)||(map[sx][sy] != map[ex][ey]))//相当重要的剪枝,不加肯定超时
59 { printf("NO\n"); continue;}
60 flag = 0;
61 memset(vis, 0, sizeof(vis));
62 vis[sx][sy] = 1;
63 dfs(sx, sy, -1, -1);
64 if(flag)
65 printf("YES\n");
66 else
67 printf("NO\n");
68 }
69 }
70 return 0;
71 }



转载于:https://www.cnblogs.com/gaigai/archive/2012/03/25/2416345.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值