題意:從起點出發,可向東南西北4個方向走,如果前面沒有墻則可走;如果前面只有一堵墻,則可將墻向前推一格,其余情況不可推動,且不能推動游戲區域邊界上的墻。問走出迷宮的最少步數,輸出任意一個移動序列。
分析:
1、最少步數--IDA*。
2、注意,若此墻可推動,必須改變當前格子,和沿當前格子向前一步的格子的墻的標記。
3、若沿當前格子向前兩步的格子存在,則這個格子的墻的標記也要改變。不存在的情況是:把墻推向了邊界。
4、因為每個格子的值是是1(如果正方形以西有一個墻),2(北),4(東)和8(南)的總和,所以通過與1,2,4,8 & 分別來判斷西,北,東,南四個方向是否有墻。
5、可以通過當前步數與當前格子和最近邊界的垂直距離的和是否大于maxn來剪枝。
6、注意起點要標記成已走過。
#pragma comment(linker, "/STACK:102400000, 102400000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
typedef long long ll;
typedef unsigned long long llu;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, -1, 0, 1, -1, -1, 1, 1};//西北東南
const int dc[] = {-1, 0, 1, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-15;
const int MAXN = 50 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int pic[10][10];
int vis[10][10];
int ans[30];
int maxn;
const string s = "WNES";
int dir[] = {1, 2, 4, 8};
int solve(int x, int y){if(x == 1 && !(pic[x][y] & 2)) return 1;//此刻位于迷宮最北面,且當前格子北面沒有墻if(x == 4 && !(pic[x][y] & 8)) return 3;//東if(y == 1 && !(pic[x][y] & 1)) return 0;//北if(y == 6 && !(pic[x][y] & 4)) return 2;//南return -1;
}
bool judge(int x, int y){return x >= 1 && x <= 4 && y >= 1 && y <= 6;
}
bool dfs(int x, int y, int cur){if(cur >= maxn) return false;int tmp = solve(x, y);if(tmp != -1){ans[cur] = tmp;return true;}for(int i = 0; i < 4; ++i){int tx = x + dr[i];int ty = y + dc[i];if(judge(tx, ty) && !vis[tx][ty]){if(!(pic[x][y] & dir[i])){//向pic[tx][ty]方向走,無墻vis[tx][ty] = 1;ans[cur] = i;if(dfs(tx, ty, cur + 1)) return true;vis[tx][ty] = 0;}else if(!(pic[tx][ty] & dir[i])){//向pic[tx][ty]方向走,有墻但可推vis[tx][ty] = 1;pic[tx][ty] += dir[i];//墻推動導致格子對墻的標記改變pic[x][y] -= dir[i];if(judge(tx + dr[i], ty + dc[i])){pic[tx + dr[i]][ty + dc[i]] += dir[(i + 2) % 4];//注意對于該格子加反方向的墻,但是該格子可能不存在,比如把墻推向了邊界}ans[cur] = i;if(dfs(tx, ty, cur + 1)) return true;if(judge(tx + dr[i], ty + dc[i])){pic[tx + dr[i]][ty + dc[i]] -= dir[(i + 2) % 4];}pic[x][y] += dir[i];pic[tx][ty] -= dir[i];vis[tx][ty] = 0;}}}return false;
}
int main(){int sx, sy;while(scanf("%d%d", &sx, &sy) == 2){if(!sx && !sy) return 0;memset(ans, 0, sizeof ans);for(int i = 1; i <= 4; ++i){for(int j = 1; j <= 6; ++j){scanf("%d", &pic[i][j]);}}for(maxn = 1; ; ++maxn){memset(vis, 0, sizeof vis);vis[sy][sx] = 1;if(dfs(sy, sx, 0)){for(int i = 0; i < maxn; ++i){printf("%c", s[ans[i]]);}printf("\n");break;}}}return 0;
}
?
?