#include<iostream>
#include<queue>
#include<cstdio>
using namespace std;
int M, N;
char map[10][10];
int x, y, bx, by, ex, ey;
int a[] = { 0,0,1,-1 };
int b[] = { 1,-1,0,0 };
struct State
{
int x, y, bx, by;
State(int x=0, int y=0, int bx=0, int by=0)
{
this->x = x;
this->y = y;
this->bx = bx;
this->by = by;
}
};
int vis[10][10][10][10] = {0};
int bfs()
{
queue<State> que;
State start(x,y,bx,by);
vis[x][y][bx][by] = 0;
que.push(start);
State temp;
while (!que.empty())
{
//cout << ".. "<< endl;
temp = que.front();
que.pop();
if ((temp.bx == ex) && (temp.by == ey))
{
//cout << "666" <<endl;
return vis[temp.x][temp.y][temp.bx][temp.by];
}
for (int i = 0; i < 4; i++)
{
int nx, ny;
nx = temp.x + a[i]; ny = temp.y + b[i];
if (nx < 0 || ny < 0 || nx >= M || ny >= N || map[nx][ny] == '#') { continue; };
//cout << "[" << nx << "," << ny << endl;
if (nx == temp.bx && ny == temp.by)
{
if (temp.bx + a[i] < 0 || temp.bx + a[i] >= M || temp.by + b[i] < 0 || temp.by + b[i] >= N || map[temp.bx + a[i]][temp.by + b[i]] == '#')
continue;
if (vis[nx][ny][temp.bx][temp.by]) continue;
State state(nx,ny,temp.bx+a[i], temp.by+b[i]);
que.push(state);
vis[nx][ny][temp.bx + a[i]][temp.by + b[i]]=vis[temp.x][temp.y][temp.bx][temp.by] + 1;
//cout << "** "<<nx<<" "<<ny<<" "<< temp.bx + a[i]<<" "<< temp.by + b[i] << endl;
}
else
{
if (vis[nx][ny][temp.bx][temp.by]) continue;
State state(nx, ny, temp.bx , temp.by);
que.push(state);
vis[nx][ny][temp.bx ][temp.by ] = vis[temp.x][temp.y][temp.bx][temp.by] + 1;
//cout << "** " << endl;
}
}
}
return -1;
}
int main()
{
cin >> M >> N;
cin.ignore();
for (int i = 0; i < M; i++)
cin.getline(map[i],10);
for(int i=0;i<M;i++)
for (int j = 0; j < N; j++)
{
if (map[i][j] == 'X')
{
x = i;
y = j;
}
else if (map[i][j] == '@')
{
ex = i;
ey = j;
}
if (map[i][j] == '*')
{
bx = i;
by = j;
}
}
cout << bfs() << endl;
//system("pause");
return 0;
}
推箱子
最新推荐文章于 2023-10-03 09:51:33 发布