HDU 1254 搜索

用箱子的位置BFS

然后DFS查看人是否可以进行这次推动

注意特殊情况的判断

附几组测试数据

100
4 3
0 0 0
0 0 1
0 2 3
1 4 1
6 3
0 0 0
0 0 0
1 0 0
0 0 1
0 2 3
1 4 1
5 5
0 3 0 0 0
1 0 1 4 0
0 0 1 0 0
1 0 2 0 0
0 0 0 0 0
4 4
1 2 1 1
0 0 0 0
0 4 3 0
0 0 0 0
4 4
0 3 0 0
0 0 2 0
0 0 4 0
0 1 0 1
3 3
0 3 0
1 0 2
0 4 0
5 5
0 1 4 0 0
0 1 1 1 1
0 2 3 0 0
0 0 0 0 0
0 0 0 0 0
4 4
0 1 0 1
0 2 0 4
0 0 0 0
0 3 0 1


#include "queue"
#include "string"
#include "iostream"
#include "algorithm"
using namespace std;

int dir1[4][2]={1,0,-1,0,0,1,0,-1};
int dir2[4][2]={-1,0,1,0,0,-1,0,1};
struct node
{
	int x,y; //箱子位置
	int xx,yy;// 人位置
	int step;
};
int n,m,bs_x,bs_y,be_x,be_y,ps_x,ps_y,ans;
int ok;
int hash[11][11][11][11];// BFS判重
int mark[11][11];// DFS判重
int map[11][11];
void dfs(int x,int y,int xx,int yy,int xxx,int yyy)
{
	int a,b,i;
	if (x==xx && y==yy) ok=1;
	if (ok==1) return;
	for (i=0;i<4;i++)
	{
		a=x+dir1[i][0];
		b=y+dir1[i][1];
		if (a==xxx && b==yyy) continue;
		if (a<1 || a>n || b<1 || b>m) continue;
		if (map[a][b]==1) continue;
		if (mark[a][b]==1) continue;
		mark[a][b]=1;
		if (a==xx && b==yy) { ok=1; return ;}
		dfs(a,b,xx,yy,xxx,yyy);
		mark[a][b]=0;
	}
}




void bfs()
{
	queue<node>q;
	node cur,next;
	int i;


	cur.x=bs_x;
	cur.y=bs_y;
	cur.step=0;
	cur.xx=ps_x;
	cur.yy=ps_y;

	q.push(cur);
	while (!q.empty())
	{
		cur=q.front();
		q.pop();
		for (i=0;i<4;i++)
		{
			next.x=cur.x+dir1[i][0];
			next.y=cur.y+dir1[i][1];
			if (next.x<1 || next.x>n || next.y<1 || next.y>m) continue;
			if (map[next.x][next.y]==1) continue;

			next.xx=cur.x+dir2[i][0];
			next.yy=cur.y+dir2[i][1];
			if (next.xx<1 || next.xx>n || next.yy<1 || next.yy>m) continue;
			if (map[next.xx][next.yy]==1) continue;
			if (hash[next.x][next.y][next.xx][next.yy]==1) continue;

			ok=0;
			memset(mark,0,sizeof(mark));
		    dfs(cur.xx,cur.yy,next.xx,next.yy,cur.x,cur.y);
			if (ok==0) continue;
			next.step=cur.step+1;
			hash[cur.x][cur.y][cur.xx][cur.yy]=1;
			q.push(next);
			if (next.x==be_x && next.y==be_y) { ans=next.step; return ;}
		}
	}
}

int main()
{
	int T;
	int i,j;
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d%d",&n,&m);
		for (i=1;i<=n;i++)
			for (j=1;j<=m;j++)
			{
				scanf("%d",&map[i][j]);
				if (map[i][j]==2) { bs_x=i; bs_y=j;}
				if (map[i][j]==3) { be_x=i; be_y=j;}
				if (map[i][j]==4) { ps_x=i; ps_y=j;}
			}

		memset(hash,0,sizeof(hash));
		ans=-1;

		bfs();
		printf("%d\n",ans);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值