题解 | #走迷宫#
走迷宫
https://ac.nowcoder.com/acm/contest/72177/H
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define int long long
#define double long double
const int N=0x3f3f3f3f,mod=1e9+7;
struct node
{
int x;
int y;
string path;
};
signed main()
{
IOS;
int n,m;
cin>>n>>m;
char mp[1010][1010];
char k[4]={'D','L','R','U'};
int dir[4][2]={{1,0},{0,-1},{0,1},{-1,0}};
int vis[1010][1010];
for(int i=0;i<n;i++)
{
cin>>mp[i];
}
node start;
int a,b;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mp[i][j]=='$')
{
a=i;
b=j;
break;
}
}
}
start.x=a;
start.y=b;
start.path="";
vis[a][b]=1;
queue<node>q;
q.push(start);
while(!q.empty())
{
node now=q.front();
q.pop();
if(now.x==n-1||now.y==m-1||now.x==0||now.y==0)
{
cout<<now.path.size()<<endl;
return 0;
}
for(int i=0;i<4;i++)
{
node next;
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
if(next.x<0||next.x>=n||next.y<0||next.y>=m)
continue;
if(vis[next.x][next.y]==1||mp[next.x][next.y]=='#')
continue;
vis[next.x][next.y]=1;
next.path=now.path+k[i];
q.push(next);
}
}
cout<<"-1"<<endl;
return 0;
}