您的位置:首页 > 其它

hdu 1254 推箱子(bfs + bfs)

2014-03-08 14:33 507 查看
小记: 这种题,思路很容易想出来,但是考你的不是算法,而是你的细心。

思路:首先,此题要注意的是你将箱子 挪过去之后,还可以将箱子挪回来,即 你人的位置换了,而箱子的位置没变,相信玩过的人应该深知这个原理,不多阐述。

我们用bfs箱子的位置,箱子往一个方向挪动的话,那么我们必须要能达到箱子挪动的方向的反方向的位置,这个时候我们可以用dfs或bfs查看我们当前所在的位置是否可以到达那个位置,若可以,那么就代表着我们是可以将箱子往那个方向挪动的,但是这里会有重复出现的情况,我们必须在此判重,一个是箱子的位置,一个是我们自己的位置,以这两个位置来判重,用一个四维数组就行了。

bfs每次寻到一种可能的时候,记录的是箱子的位置 以及我们自己本人所在的位置。两个。

在bfs我们自己在自己当前的位置能到达哪些位置时,记得回溯。

做这样的题的时候,头脑的思路一定要清晰,否则一乱全乱,就黄了.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

const int MAX_ = 10001;

int dir[4][4] = {{0,1},{-1,0},{1,0},{0,-1}};

bool svis[10][10];
bool tvis[10][10][10][10];

int n,m;
int f[10][10];

struct point {
int x,y,step;
} s,e,t;

void sbfs() {
queue<point>q;
memset(svis,0,sizeof(svis));
q.push(s);
while(!q.empty()) {
point cur = q.front(),next;
q.pop();
svis[cur.x][cur.y] = 1;
for(int i = 0; i < 4; ++i) {
next.x = cur.x + dir[i][0];
next.y = cur.y + dir[i][1];
//getchar();
if((next.x >= 1 && next.x <= n) && (next.y >= 1 && next.y <= m)) {
if(f[next.x][next.y] == 0) {
if(!svis[next.x][next.y]) {
q.push(next);
}
}
}
}
}
}

void bfs() {
queue<point>q;
memset(tvis,0,sizeof(tvis));
q.push(t);
q.push(s);
while(!q.empty()) {
point cur , next;
cur = q.front();
q.pop();
s = q.front();//自己所在的位置要记下
q.pop();

if(cur.x == e.x && cur.y == e.y){
cout<<cur.step<<endl;
return ;
}
tvis[cur.x][cur.y][s.x][s.y] = 1;
f[cur.x][cur.y] = 2;//标记为箱子的位置
sbfs();//bfs 可以到达的位置
f[cur.x][cur.y] = 0;//为了下一次换箱子位置时,归0
for(int i = 0; i < 4; ++i) {
next.x = cur.x + dir[i][0];
next.y = cur.y + dir[i][1];
next.step = cur.step + 1;
if((next.x >= 1 && next.x <= n) && (next.y >= 1 && next.y <= m)) {
if(f[next.x][next.y] == 0) {
if(svis[cur.x + dir[3-i][0]][cur.y + dir[3-i][1]]) {//反方向是否可达
if(!tvis[next.x][next.y][cur.x][cur.y]) {
q.push(next);
q.push(cur);
}
}
}
}
}
}
cout<<"-1"<<endl;
}

int main() {
int T;
cin>>T;
while(T--) {
cin>>n>>m;
memset(f,0,sizeof(f));
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
cin>>f[i][j];
if(f[i][j] == 4) {
f[i][j] = 0;
s.x = i, s.y = j;
} else if(f[i][j] == 2) {
t.x = i, t.y = j,t.step = 0;
} else if(f[i][j] == 3) {
f[i][j] = 0;
e.x = i, e.y = j;
}
}
}
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: