推箱子

50 篇文章 1 订阅
#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值