#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int m,n;
int z1,z2,s1,s2;
char board[25][25];
int vis[25][25][25][25];//开四维数组记录数据
int to[4][2] = {1,0,-1,0,0,-1,0,1};//Z的走法
int to2[4][2] = {-1,0,1,0,0,1,0,-1};//S走相反路线
struct node {
int x1, x2, y1, y2, step;
};
bool valid(int x,int y) {
if(x<0 || y<0 || x>=n || y>=m || board[x][y] == 'X')
return false;
return true;
}
int ok(int x, int x1, int y, int y1) { //符合条件的状况
if(x == x1 && y == y1)
return 1;
if(x == x1+1 && y == y1)
return 1;
if(x == x1-1 && y == y1)
return 1;
if(x == x1 && y == y1-1)
return 1;
if(x == x1 && y == y1+1)
return 1;
return 0;
}
int bfs() {
int i;
queue<node> Q;
node cur,next;
memset(vis, 0, sizeof(vis));
cur.x1 = z1;
cur.x2 = s1;
cur.y1 = z2;
cur.y2 = s2;
cur.step = 0;
vis[z1][z2][s1][s2] = 1;//四维数组记录行走状况
Q.push(cur);
while( !Q.empty() ) {
cur = Q.front();
Q.pop();
if(ok(cur.x1, cur.x2, cur.y1, cur.y2))
return cur.step;
for(i = 0; i<4; i++) {
next = cur;
next.x1 = cur.x1 + to[i][0];
next.y1 = cur.y1 + to[i][1];
next.x2 = cur.x2 + to2[i][0];
next.y2 = cur.y2 + to2[i][1];
if(!valid(next.x1, next.y1))
continue;
if(!valid(next.x2,next.y2)) {//原地不动
next.x2 = cur.x2;
next.y2 = cur.y2;
}
if(vis[next.x1][next.y1][next.x2][next.y2])
continue;
vis[next.x1][next.y1][next.x2][next.y2] = 1;
next.step = cur.step + 1;
Q.push(next);
}
}
return -1;
}
int main() {
freopen("data.in", "r", stdin);
while(scanf("%d%d",&n,&m) == 2) {
int i,j;
for(i = 0; i < n; i++) {
scanf("%s", board[i]);
for(j = 0; j < m ; j++) {
if(board[i][j] == 'Z') {
z1 = i;
z2 = j;
} else if(board[i][j] == 'S') {
s1 = i;
s2 = j;
}
}
}
int ans;
ans = bfs();
if(ans != -1)
printf("%d\n",ans);
else
printf("Bad Luck!\n");
}
return 0;
}
HDU 2216 Game III(BFS,四维数组记录状态)
最新推荐文章于 2020-12-05 17:02:37 发布