题意:如图所示,从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;
}