題意:如圖所示,從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;
}