题意
就是一个棋盘 有一个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;
}