这个题的题意还是很好理解的,貌似是一种游戏,通过控制小人上下左右找到出口出去。但是有几条规则:
1.可以上下左右走,但只有碰到墙(#)才会转弯。
2.地图中有可能会出现钥匙,只有当集齐所有钥匙的时候才可以打开门并且出去(钥匙的数量小于7)。
3.地图中也会有一些强制转弯的标志,当遇到这些标志的时候立刻向这个方向转弯。
4.当直着走出这个地图的时候就再也回不来。。
问最短走出去的步数,走不出去为-1。
很明显的搜索,用bfs即可。只是需要用状压来记录当前拿到钥匙的状态,同时要注意,有可能一个格子重复来过,但是手上的钥匙可能不同,这个时候我们的标记数组要再开一维标识现在已有钥匙的状态。其他的只要注意一些细节就好了。(做的时候思路倒是很清晰,就是细节处理的不好,看了看题解,自己又写了一遍。。)
/*********************************************************
> File Name: 4634.cpp
> Author:Lawrence_
> Created Time: 2015年03月10日 星期二 20时08分37秒
*********************************************************/
#include <cstdio>
#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <deque>
#include <list>
#include <map>
#include <vector>
#include <cstdlib>
#include <set>
#include <cctype>
#define ll long long
#define lson l,m,rt << 1
#define rson m+1,r,rt << 1 | 1
#define pi acos(-1)
#define INF 0x7f7f7f7f
#define Clear(name,init) memset(name,init,sizeof(name))
#define eps 1e-8
using namespace std;
char g[205][205];
int sx,sy,ex,ey;
int key_num;
int dir[4][2] = {{0,-1},{-1,0},{1,0},{0,1}};
int key_map[205][205];
int n,m;
struct point{
int x,y;
int step;
int key;
};
bool used[202][202][1<<7][4];
int bfs(){
queue<point> q;
while(!q.empty()) q.pop();
point hd;
hd.x = sx;
hd.y = sy;
hd.step = 0;
hd.key = 0;
q.push(hd);
Clear( used , false);
//used[sx][sy][0][0] = true;
while(!q.empty()){
point now,pre;
pre = q.front();
q.pop();
for(int i = 0;i < 4; i++){
// puts("debug");
int mx = dir[i][0];
int my = dir[i][1];
int xx = pre.x;
int yy = pre.y;
int ss = pre.key;
while(1){
int mo;
if(g[xx][yy] == 'L'){
mx = 0;
my = -1;
}
if(g[xx][yy] == 'U'){
mx = -1;
my = 0;
}
if(g[xx][yy] == 'D'){
mx = 1;
my = 0;
}
if(g[xx][yy] == 'R'){
mx = 0;
my = 1;
}
if(mx == 0 && my == -1) mo = 0;
else if(mx == -1 && my == 0) mo = 1;
else if(mx == 1 && my == 0) mo = 2;
else if(mx == 0 && my == 1) mo = 3;
if(used[xx][yy][ss][mo]) break;
used[xx][yy][ss][mo] = true;
if(g[xx][yy] == 'K')
ss |= key_map[xx][yy];
if(xx == ex && yy == ey && ss == ((1 << key_num) - 1))
return pre.step + 1;
if(xx+mx >= 0 && xx+mx < n && yy+my >= 0 && yy+my < m){
if(g[xx+mx][yy+my] == '#'){
now.x = xx;
now.y = yy;
now.step = pre.step + 1;
now.key = ss;
q.push(now);
break;
}
else{
xx += mx;
yy += my;
}
}
else
break;
}
}
}
return -1;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input", "r", stdin);
#endif
while(~scanf("%d%d",&n,&m)){
key_num = 0;
Clear( key_map , 0 );
for(int i = 0;i < n; i++){
scanf("%s",g[i]);
for(int j = 0;j < m; j++){
if(g[i][j] == 'S'){
sx = i;
sy = j;
}
if(g[i][j] == 'E'){
ex = i;
ey = j;
}
if(g[i][j] == 'K'){
key_map[i][j] = (1<<key_num);
key_num++;
}
}
}
printf("%d\n",bfs());
}
return 0;
}