I have been solving the CSES problem set and I am stuck on the following problem : CSES-Labyrinth

Here is my solution :

`#include <bits/stdc++.h> using namespace std; int main() { int n,m,distance=0,x=0,y=0; string str1="NO",str2=""; cin>>n>>m; char grid[n+1][m+1]; int vis[n+1][m+1]; int dis[n+1][m+1]; string path[n+1][m+1]; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; char dz[]={'R','L','D','U'}; queue<pair<int,int>>s; for(int i=0;i<n;i++) for(int j=0;j<m;j++){ cin>>grid[i][j]; if(grid[i][j]=='A'){ x=i; y=j; } vis[i][j]=0; dis[i][j]=0; path[i][j]=""; } s.push({x,y}); while(!s.empty()){ pair<int,int>a=s.front(); s.pop(); if(grid[a.first][a.second]=='B'){ distance=dis[a.first][a.second]; str1="YES"; x=a.first; y=a.second; break; } if(vis[a.first][a.second]==1) continue; else{ vis[a.first][a.second]=1; for(int i=0;i<4;i++){ if(a.first+dx[i]<n && a.first+dx[i]>=0 && a.second+dy[i]<m && a.second+dy[i]>=0 && (grid[a.first+dx[i]][a.second+dy[i]]=='.' || grid[a.first+dx[i]][a.second+dy[i]]=='B')){ s.push({a.first+dx[i], a.second+dy[i]}); dis[a.first+dx[i]][ a.second+dy[i]]=dis[a.first][a.second]+1; path[a.first+dx[i]][ a.second+dy[i]]=path[a.first][a.second]+dz[i]; } } } } if(str1=="YES"){ cout<<str1<<endl<<distance<<endl<<path[x][y]; } else cout<<str1; } `

I am getting a Runtime error on 3/15 test cases and this was the best result I could reach (other 12 cases are accepted). How do I avoid runtime errors? What is wrong with my solution?