TLE in Labyrinth(CSES) problem

Problem Link:(
My solution:(

I use BFS to solve this problem, but in some test cases, it is giving TLE. I have no idea why it is showing TLE, as Time Complexity of my solution is O(n*m) where 1<=n<=1000,1<=m<=1000. I try to make my code more readable and clean. Can anyone help me, what I am missing here?

Bro, you are getting a TLE cause you are using maps for storing distances instead of 2-D arrays try replacing it, that’ll work.
Just a suggestion, in case you are not aware you can implement your solution in a more elegant and efficient fashion by using a standard trick for grid problems used in the code attached you can check it out if you want

#include <bits/stdc++.h>
#define ar array
using namespace std;
const int mxN =1e3+2;
const int di[4]={1,0,-1,0},dj[4]={0,1,0,-1};
const char dc[4]={'D','R','U','L'} ;
int n,m,si,sj,ti,tj,d[mxN][mxN];
string s[mxN],p[mxN] ;
bool e(int i,int j){
  return (i<n&&i>=0&&j<m&&j>=0&&s[i][j]=='.') ;
signed main() {
  cin >> n >> m ;
  for(int i=0;i<n;i++)
    cin >> s[i] ; 
  for(int i=0;i<n;i++){
    for(int j=0;j<m;j++){
    p[i]=string(m,0) ;
  queue<ar<int,2>>qu ;
  qu.push({si,sj}) ;
    ar<int,2>u = qu.front();
    qu.pop() ;
    for(int k=0;k<4;k++){
      int ni=u[0]+di[k],nj=u[1]+dj[k];
        continue ;
      d[ni][nj]=k ;
      p[ni][nj]=dc[k] ;
    string t ;
    cout << "YES"<< endl ;
    while(si^ti || sj^tj){
      t+=p[ti][tj] ;
      int dd=d[ti][tj]^2;
    cout << t.size() <<"\n";
    cout << t ;
    cout << "NO";
1 Like

Thankyou so much, yeah it’s work and thanks for suggestion : ).
But I have a doubt, Is map of (pair<int,int>,int) is too slow? Isn’t it just O(logn) for lookup? or am i missing something?

1 Like

Yeah, it is O(logn) theoretically but in my opinion it the data stored in each node of the BST is comparatively higher may that’s why the map under performs in these situations though I am not sure somebody can correct me if I’m wrong. So its recommended going with 2-D arrays as far as possible

1 Like

Okay, thank u so much bro : )

What’s wrong with this solution? Giving WA for few test cases. Can anyone help please?