UVa 10384:The Wall Pusher(IDA*)
2015-09-14 10:15
489 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=842&page=show_problem&problem=1325
题意:如图所示,从S处出发,每次可以往东、南、西、北4个方向之一前进。如果前方有墙壁,游戏者可以把墙壁往前推一格。如果有两堵或者多堵连续的墙,则不能推动。另外游戏者也不能推动游戏区域边界上的墙。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
使用IDA*。枚举需要走的步数,进行DFS。需要加入最优性剪枝,即当前所走步数加上还需走的最少步数如果已经超过最大步数限制的话,则直接return。
代码:
题意:如图所示,从S处出发,每次可以往东、南、西、北4个方向之一前进。如果前方有墙壁,游戏者可以把墙壁往前推一格。如果有两堵或者多堵连续的墙,则不能推动。另外游戏者也不能推动游戏区域边界上的墙。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
使用IDA*。枚举需要走的步数,进行DFS。需要加入最优性剪枝,即当前所走步数加上还需走的最少步数如果已经超过最大步数限制的话,则直接return。
代码:
#include <iostream> #include <algorithm> #include <fstream> #include <string> #include <cstring> #include <vector> #include <queue> #include <cmath> #include <cctype> #include <stack> #include <set> using namespace std; const int maxn = 10 + 5, INF = 10; const int dx[] = {0, -1, 0, 1}, dy[] = {-1, 0, 1, 0}; const string dir = "WNES"; int x, y; int a[maxn][maxn]; int h(int x, int y) { int res = INF; for (int i = 1; i <= 4; ++i) { if ((a[i][1] & 1) != 1) res = min(res, abs(x - i) + y); if ((a[i][6] & 4) != 4) res = min(res, abs(x - i) + 7 - y); } for (int i = 1; i <= 6; ++i) { if ((a[1][i] & 2) != 2) res = min(res, abs(y - i) + x); if ((a[4][i] & 8) != 8) res = min(res, abs(y - i) + 5 - x); } return res; } bool DFS(int x, int y, int deep, int limit, string s) { if (deep == limit && (x == 0 || x == 5 || y == 0 || y == 7)) { cout << s << '\n'; return true; } if (h(x, y) + deep > limit) return false; for (int i = 0; i < 4; ++i) { int xx = x + dx[i], yy = y + dy[i]; if (xx >= 0 && xx <= 5 && yy >= 0 && yy <= 7) { if ((a[x][y] & (1 << i)) == (1 << i)) { if (xx != 0 && xx != 5 && yy != 0 && yy != 7 && ((a[xx][yy] & (1 << i)) != (1 << i))) { a[x][y] -= (1 << i); a[xx][yy] += ((1 << i) - (1 << ((i + 2) % 4))); a[xx + dx[i]][yy + dy[i]] += (1 << ((i + 2) % 4)); if (DFS(xx, yy, deep + 1, limit, s + dir[i])) return true; a[x][y] += (1 << i); a[xx][yy] -= ((1 << i) - (1 << ((i + 2) % 4))); a[xx + dx[i]][yy + dy[i]] -= (1 << ((i + 2) % 4)); } } else { if (DFS(xx, yy, deep + 1, limit, s + dir[i])) return true; } } } return false; } int main() { while (~scanf("%d%d", &y, &x), x || y) { for (int i = 1; i <= 4; ++i) for (int j = 1; j <= 6; ++j) scanf("%d", &a[i][j]); for (int maxd = 1; ; ++maxd) if (DFS(x, y, 0, maxd, "")) break; } return 0; }
相关文章推荐
- Foundation框架—字符串
- tomcat端口被占用
- JQuery ajax中error返回错误及一直返回error的解答
- 20150830-Linux文件系统上的特殊权限
- 常用的webservice接口
- Eclipse启动报错
- 剑指offer:二维数组中的查找
- linux服务器之间如何复制文件
- Foundation框架—结构体
- 20150830-linux vim文本编辑器
- c#使用SqlBulkCopy批量插入数据
- Nucleus PLUS应用系统示例
- sizeof求数组长度
- maven 常用配置项 详解
- 欧拉角的万向锁
- Android判断网络状态方法详解
- 接口的作用
- 20150830-linux文件查找工具
- 【OJ测试技巧】大量示例测试方法
- Mac系统运行MapReduce程序报错:exitCode 127