Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define int long long
- #define f(i,l,n) for(int i=l;i<n;i++)
- #define E "\n"
- #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
- #define MAX 1e5
- #define MIN -1e5
- #define float long double
- const int M=1e9+7;
- int n,m;
- string s[1000];
- int a[1005][1005],b[1005][1005],visited[1005][1005]; //a for moster reach time for cell {x,y} b for A
- char perent[1005][1005]; // to keep trak of path
- pair<int,int> points[]={{1,0},{-1,0},{0,1},{0,-1}}; // D U R L
- bool valid(int x,int y)
- {
- if(x>=0 && x<n && y>=0 && y<m) return true;
- else return false;
- }
- char per(int dx,int dy)
- {
- char c;
- if(dx==1) c='D';
- else if(dx==-1) c='U';
- else if(dy==1) c='R';
- else if(dy==-1) c='L';
- return c;
- }
- queue<pair<int,int>> q;
- void bfs()
- {
- memset(visited,0,sizeof visited);
- while(!q.empty())
- {
- pair<int,int> cur=q.front();
- q.pop();
- int X=cur.first,Y=cur.second;
- visited[X][Y]=1;
- for(auto it:points)
- {
- int x=X+it.first,y=Y+it.second;
- if(valid(x,y) && visited[x][y]==0 && s[x][y]=='.')
- {
- visited[x][y]=1;
- a[x][y]=1+a[X][Y];
- q.push({x,y});
- }
- }
- }
- }
- void bfs1()
- {
- memset(visited,0,sizeof visited);
- while(!q.empty())
- {
- pair<int,int> cur=q.front();
- q.pop();
- int X=cur.first,Y=cur.second;
- visited[X][Y]=1;
- if(X==n-1 || Y==m-1 || X==0 || Y==0) //if found any of boundry point then print path
- {
- cout<<"YES\n";
- string ans="";
- int x=X,y=Y;
- while(perent[x][y]!='A')
- {
- //cout<<x<<" "<<y<<E;
- ans=perent[x][y]+ans;
- if(perent[x][y]=='L') y++;
- else if(perent[x][y]=='R') y--;
- else if(perent[x][y]=='U') x++;
- else if(perent[x][y]=='D') x--;
- }
- cout<<ans.size()<<E<<ans<<E;
- exit(0);
- }
- for(auto it:points)
- {
- int x=X+it.first,y=Y+it.second;
- if(valid(x,y) && visited[x][y]==0 && s[x][y]=='.')
- {
- visited[x][y]=1;
- b[x][y]=1+b[X][Y];
- perent[x][y]=per(it.first,it.second);
- if(a[x][y]!=-1 && b[x][y]>=a[x][y]) continue;
- q.push({x,y});
- }
- }
- }
- cout<<"NO\n";
- }
- int32_t main()
- {
- fast;
- #ifndef ONLINE_JUDGE
- freopen("input.txt","r",stdin);
- freopen("output.txt","w",stdout);
- #endif
- cin >> n >> m;
- memset(a,-1,sizeof a);
- f(i,0,n) cin >> s[i];
- pair<int,int> start;
- f(i,0,n)
- {
- f(j,0,m)
- {
- if(s[i][j]=='A') start={i,j},s[i][j]='.';
- if(s[i][j]=='M') q.push({i,j}),a[i][j]=0;
- }
- }
- bfs();
- perent[start.first][start.second]='A';
- q.push(start);
- bfs1();
- return 0;
- }
Add Comment
Please, Sign In to add comment