【搜索】训练E - Crazy Robot

题意

就是一个棋盘 有一个crazy robot ,对它下指令,robot就会朝非指令方向移动,同时robot无法越界和穿越障碍物,要求就是找出可以通过下指令使robot回到L的位置 并打上+标记

思路

因为下指令之后robot会往除了该方向以外的其他地方走,本质上相当于加了一堵墙,那么要让robot能回到L的话就需要满足条件:小于等于两条路可以走,且有一条通向L。而满足该条件的点,又可以当作新的L。所以考虑到用dfs。除此之外,通过另写一个函数wall来判断robot在该点周围的墙数会方便很多~

代码

#include<iostream>
#include<cmath>
#include<stack>
#include<map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>

#define Endl "\n"
typedef long long ll;
const int maxn=1e6+5;
const int mod=1e9+7;
using namespace std;
string a[maxn];
ll n,m;
int wall(int x,int y)
{
	int ans=0;
	if(x==0||a[x-1][y]=='#'||a[x-1][y]=='L') ans++;
	if(x==n-1||a[x+1][y]=='#'||a[x+1][y]=='L') ans++;
	if(y==0||a[x][y-1]=='#'||a[x][y-1]=='L') ans++;
	if(y==m-1||a[x][y+1]=='#'||a[x][y+1]=='L') ans++;
	return ans;
}

void dfs(int x,int y)
{
	if(wall(x,y)>=3||a[x][y]=='L')
	{
		a[x][y]='L';
		if(y!=m-1&&a[x][y+1]=='.') dfs(x,y+1);
		if(y!=0&&a[x][y-1]=='.')  dfs(x,y-1);
		if(x!=n-1&&a[x+1][y]=='.') dfs(x+1,y);
		if(x!=0&&a[x-1][y]=='.') dfs(x-1,y);
	}
	return ;
}
int main()
{
	ll t;
	cin>>t;
	ll r,q;
	while(t--)
	{
		cin>>n>>m;
		for(int i=0;i<n;i++)
			cin>>a[i];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(a[i][j]=='L')
				{
					r=i;
					q=j;
				}
			}
		}
		dfs(r,q);
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				if(a[i][j]=='L') a[i][j]='+';
				if(i==r&&j==q)	cout<<"L";
				else cout<<a[i][j];
			}
			cout<<Endl;
		}
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值