Problem link : CSES Labyrinth
My solution:
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define f first
#define s second
#define mp make_pair
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define mod 1000000007
#define pi acos(-1)
typedef long long int ll;
typedef long double ld;
typedef vector<ld> vld;
typedef vector<ll> vll;
typedef pair<ll,ll> pll;
typedef vector<bool> vb;
bool isValid(ll x,ll y,vector<char> maze[],vector<vector<bool>> visited,ll n,ll m)
{
if(x<0 || y<0 || x>=n || y>=m) return false;
if(visited[x][y]==true) return false;
if(maze[x][y]=='#') return false;
return true;
}
void bfs(ll x1,ll y1,ll x2,ll y2,vector<char> maze[],ll n,ll m,
vector<vector<bool>> &visited,vector<vector<pll>> &parent,vector<pll> moves,ll &flag)
{
queue<pll> q;
q.push(mp(x1,y1));
visited[x1][y1]=true;
ll cx=x1,cy=y1;
while(true)
{
for(auto x:moves)
{
ll a,b;
a=x.f;
b=x.s;
if(isValid(cx+a,cy+b,maze,visited,n,m)==true)
{
parent[cx+a][cy+b]=mp(cx,cy);
visited[cx+a][cy+b]=true;
q.push(mp(cx+a,cy+b));
if(maze[cx+a][cy+b]=='B')
{
flag=1;
return;
}
}
}
if(q.empty()==1) return;
else
{
pll next;
next=q.front();
q.pop();
cx=next.f;
cy=next.s;
}
}
}
void solve()
{
ll n,m;
cin>>n>>m;
char a;
vector<char> maze[n];
vector<bool> v;
ll x1,y1,x2,y2;
for(ll i=0;i<n;i++)
{
for(ll j=0;j<m;j++)
{
cin>>a;
maze[i].pb(a);
if(a=='A')
{
x1=i;
y1=j;
}
if(a=='B')
{
x2=i;
y2=j;
}
}
}
vector<vector<bool>> visited(n,vector<bool> (m,false));
vector<vector<pll>> parent(n,vector<pll> (m,mp(-1,-1)));
vector<pll> moves;
moves.pb(mp(-1,0));
moves.pb(mp(1,0));
moves.pb(mp(0,-1));
moves.pb(mp(0,1));
ll flag=0;
bfs(x1,y1,x2,y2,maze,n,m,visited,parent,moves,flag);
if(flag==0)
{
cout<<"NO\n";
return;
}
else
{
cout<<"YES\n";
string s="";
ll x=x2,y=y2;
while(true)
{
ll px,py;
px=parent[x][y].f;
py=parent[x][y].s;
if(x-1==px)
{
s+='D';
}
else if(x+1==px)
{
s+='U';
}
else if(y-1==py)
{
s+='R';
}
else if(y+1==py)
{
s+='L';
}
x=px;
y=py;
if(maze[x][y]=='A') break;
}
cout<<s.length()<<"\n";
for(ll i=s.length()-1;i>=0;i--) cout<<s[i];
}
}
int main()
{
fast;
ll t=1;
//cin>>t;
while(t--)
{
solve();
}
}
I am getting TLE in 5 test cases, the ones which have large matrices and a path does exist. What’s wrong in my solution?