推箱子

时限:1000ms 内存限制:10000K 总时限:3000ms

描述:

绝大多数人都玩过推箱子的游戏,控制一个人将箱子推动到目标位置即获得胜利。现请你编写一个程序,判断将箱子推到目标位置至少需要多少步。

输入:

推箱子的平面区域为固定大小(10*10),使用10行10列输入推箱子的初始局面。其中,0代表空格,1代表墙,2代表箱子,3代表目标位置,4代表人。
注:游戏中只有一个箱子,一个目标位置,一个人。

输出:

输出将箱子推到目标位置的最小步数;若箱子不可能被推到目标位置,输出-1。

输入样例:

0000000000
0000000300
0100000000
0100000000
0101111100
0000010000
0000010000
0020010040
0000010000
0000010000

输出样例:

34

#include<iostream>
#include<queue>

using namespace std;

char maze[10][10];
int vis[10][10][10][10];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int px,py,tx,ty,fx,fy;

struct node{
   int px;
   int py;
   int tx;
   int ty;
   node(int px = 0,int py = 0,int tx = 0,int ty = 0)
   :px(px),py(py),tx(tx),ty(ty){};
};

int bfs();

int main()
{
	int i,j;
	for(i=0;i<10;i++)
	{
		for(j=0;j<10;j++)
		{
			cin >> maze[i][j];
			if(maze[i][j] == '2')
			{
				tx = i;
				ty = j;
				maze[i][j] = '0';
			}
			if(maze[i][j] == '3')
			{
				fx = i;
				fy = j;
				maze[i][j] = '0';
			}
			if(maze[i][j] == '4')
			{
				px = i;
				py = j;
				maze[i][j] = '0';
			}
		}
	}
	cout << bfs() << endl;
	return 0;
}

int bfs()
{
	queue<node>q;
	node s = node(px,py,tx,ty);
	q.push(s);
	vis[px][py][tx][ty] = 0;
	while(!q.empty())
	{
		s = q.front();
		if(s.tx == fx && s.ty == fy)
		{
			return vis[s.px][s.py][s.tx][s.ty];
		}
		q.pop();
		for(int i = 0;i < 4;i++)
		{
			int npx = s.px + dir[i][0];
			int npy = s.py + dir[i][1];
			if(npx == s.tx && npy == s.ty)
			{
				int ntx = s.tx + dir[i][0];
				int nty = s.ty + dir[i][1];
				if(ntx >= 0&&ntx < 10&&nty >= 0&&nty < 10&&!vis[npx][npy][ntx][nty]&&maze[ntx][nty] == '0')
				{
					q.push(node(npx,npy,ntx,nty));
					vis[npx][npy][ntx][nty] = vis[s.px][s.py][s.tx][s.ty] + 1;
				}
			}
			else if(npx >= 0&&npx < 10&&npy >= 0&&npy < 10&&!vis[npx][npy][s.tx][s.ty]&&maze[npx][npy] == '0')
			{
				q.push(node(npx,npy,s.tx,s.ty));
				vis[npx][npy][s.tx][s.ty] = vis[s.px][s.py][s.tx][s.ty] + 1;
			}

		}
	}
	return -1;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值