#include<queue>
#include<string>
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int n,m;
#define MAXN 10
#define MAXM 10
char map1[MAXN][MAXM];
int H[4]={0,1,0,-1};
int V[4]={-1,0,1,0};
int vis[MAXN][MAXM][MAXN][MAXM];
int boxx,boxy,personx,persony,endx,endy;
struct NodeType{
int px,py;
int bx,by;
int step;
};
bool Bound(int x,int y){
if(x<0||y<0||x>=n||y>=m||map1[x][y]=='#') return true;
else return false;
}
int BFS(){
NodeType rnode,curnode,subnode;
queue<NodeType> qu;
rnode.px=personx;
rnode.py=persony;
rnode.bx=boxx;
rnode.by=boxy;
rnode.step=0;
qu.push(rnode);
vis[personx][persony][boxx][boxy]=1;
while(!qu.empty()){
curnode=qu.front();
qu.pop();
if(curnode.bx==endx&&curnode.by==endy){
return curnode.step;
}
for(int k=0;k<4;k++){
int px=curnode.px+H[k];
int py=curnode.py+V[k];
if(Bound(px,py)) continue;
if(px==curnode.bx&&py==curnode.by){
if(Bound(curnode.bx+H[k],curnode.by+V[k])) continue;
subnode.px=px;
subnode.py=py;
subnode.bx=curnode.bx+H[k];
subnode.by=curnode.by+V[k];
subnode.step=curnode.step+1;
vis[px][py][curnode.bx][curnode.by]=1;
qu.push(subnode);
}
else {
if(vis[px][py][curnode.bx][curnode.by]){
continue;
}
subnode.px=px;
subnode.py=py;
subnode.bx=curnode.bx;
subnode.by=curnode.by;
subnode.step=curnode.step+1;
vis[px][py][curnode.bx][curnode.by]=1;
qu.push(subnode);
}
}
}
}
int main(){
while(true){
cin>>n;
if(n==0) break;
cin>>m;
for(int i=0;i<n;i++) cin>>map1[i];
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(map1[i][j]=='*') {
boxx=i;
boxy=j;
}
else if(map1[i][j]=='X'){
personx=i;
persony=j;
}
else if(map1[i][j]=='@'){
endx=i;
endy=j;
}
}
}
printf("%d\n",BFS());
}
}
推箱子
最新推荐文章于 2023-10-03 09:51:33 发布