E - 巡逻机器人

题意大概:

机器人要从一个m*n(m和n的范围都在1到20的闭区间内)的网格的左上角(1,1)走到右下角(m,n)。网格中的一些格子是空地,用0表示,其它格子是障碍,用1表示。机器人每次可以往四个方向走一格,但不能连续地穿越k( [0,20] )个障碍,求最短路长度。起点和终点保证是空地。

 

思路:用bfs搜索即可,由于不能连续地穿越k个障碍,所以在que数组中记录机器人穿越了几个障碍。

#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<cstring>
using namespace std;
const int maxn=100010;
int map[22][22],c,n,m,k,f=0,u[22][22],obstacle[22][22],que[maxn][4];
int xx[4]={1,-1,0,0},yy[4]={0,0,1,-1};
void bfs()
{
	int head=0,tail=1,i;
	f=0;
	que[1][0]=1;que[1][1]=1;que[1][2]=0;que[1][3]=0;
	while(head<tail)
	{
		head++;
		for(i=0;i<4;i++)
		{
			int tex,tey,ob;
			tex=que[head][0]+xx[i];
			tey=que[head][1]+yy[i];
			ob=que[head][2];
			if(tex>=1&&tex<=m&&tey>=1&&tey<=n)
			{
				if(map[tex][tey]==1) ob++;
				else ob=0;
				if(ob>k) continue;
				if(u[tex][tey]==0)
				{
					tail++;
					que[tail][0]=tex;que[tail][1]=tey;
					que[tail][2]=ob;
					que[tail][3]=que[head][3]+1;
					obstacle[tex][tey]=ob;
					u[tex][tey]=1;
				}
				else if(ob<obstacle[tex][tey]||ob==obstacle[tex][tey]&&u[tex][tey]<=2)
				{
					tail++;
					que[tail][0]=tex;que[tail][1]=tey;
					que[tail][2]=ob;
					que[tail][3]=que[head][3]+1;
					obstacle[tex][tey]=ob;
					u[tex][tey]++;
				}
			}
			else continue;
			if(u[m][n]==1)
			{
				f=1;
				printf("%d\n",que[tail][3]);
				break;
			}
		}
		if(f==1) break;
	}
	if(f==0)
	printf("-1\n");
	else
	return;
}
int main()
{
	int j,i;
	cin>>c;
	while(c)
	{
		cin>>m>>n>>k;
		memset(map,0,sizeof(map));
		memset(u,0,sizeof(u));
		memset(que,0,sizeof(que));
		memset(obstacle,0,sizeof(obstacle));
		for(i=1;i<=m;i++)
			for(j=1;j<=n;j++)
			cin>>map[i][j];
		u[1][1]=1;
		if(n==1&&m==1)
		{printf("0\n");}
		else
		bfs();
		c--;
	}
	return 0;
}

本题目可以因为绕路后导致穿过障碍的减少,重复走过一个格子,但是不能重复多次走,不然会凉凉,数组放不下

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值