Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ll n,m;
- bool board[3000][3000];
- int parent[3000][3000];
- pl a;
- queue<pl> q;
- ll visited[3000][3000], visited1[3000][3000];
- void reconstruct_path(ll x, ll y){
- string path="";
- // cout<<"HERE"<<'\n';
- // exit(0);
- while(make_pair(x, y)!=a){
- // dbg(x, y);
- if(parent[x][y]==1){
- //we went right so go left
- path+='R';
- y--;
- }
- else if(parent[x][y]==2){
- path+='L';
- y++;
- }
- else if(parent[x][y]==3){
- x++;
- path+='U';
- }
- else if(parent[x][y]==4){
- x--;
- path+='D';
- }
- }
- reverse(all(path));
- cout<<int(path.size())<<"\n"<<path<<'\n';
- }
- int main(){setIO("");
- re(n, m);
- for(int i=1;i<=n;i++){
- for(int j=1;j<=m;j++){
- visited[i][j]=visited1[i][j]=1e9+7;
- char c;
- re(c);
- if(c=='#'){
- board[i][j]=0;
- }
- if(c=='A'){
- a={i, j};
- visited[i][j]=0;
- board[i][j]=1;
- }
- if(c=='.'){
- board[i][j]=1;
- }
- if(c=='M'){
- visited1[i][j]=0;
- q.push({i, j});
- board[i][j]=1;
- }
- }
- }
- //multisource bfs
- while(q.size()){
- ll x=q.front().f, y=q.front().s;q.pop();
- // dbg(x, y);
- int dx[]={1, -1, 0, 0};
- int dy[]={0, 0, 1, -1};
- for(int i=0;i<4;i++){
- ll x1=x+dx[i], y1=y+dy[i];
- if(x1>=1 and x1<=n and y1>=1 and y1<=m and board[x1][y1] and visited1[x][y]+1<=visited1[x1][y1]){
- visited1[x1][y1]=1+visited1[x][y];
- q.push({x1, y1});
- }
- }
- }
- q=queue<pl>();
- q.push(a);
- while(q.size()){
- ll x=q.front().f, y=q.front().s;
- // dbg(x, y);
- q.pop();
- if(x==1 or x==n or y==1 or y==m){
- cout<<"YES"<<'\n';
- reconstruct_path(x, y);
- return 0;
- }
- else{
- int dx[]={1, -1, 0, 0};
- int dy[]={0, 0, 1, -1};
- for(int i=0;i<4;i++){
- ll x1=x+dx[i], y1=y+dy[i];
- if(x1>=1 and x1<=n and y1>=1 and y1<=m and board[x1][y1] and 1+visited[x][y]<visited1[x1][y1] and 1+visited[x][y]<=visited[x1][y1]){
- visited[x1][y1]=1+visited[x][y];
- q.push({x1, y1});
- //1 for going right
- //2 for left
- //3 for up
- //4 fur down
- if(dx[i]==1 and dy[i]==0){
- //go down
- parent[x1][y1]=4;
- }
- if(dx[i]==0 and dy[i]==1){
- //right
- parent[x1][y1]=1;
- }
- if(dx[i]==-1 and dy[i]==0){
- //up
- parent[x1][y1]=3;
- }
- else if(dx[i]==0 and dy[i]==-1){
- parent[x1][y1]=2;
- }
- }
- }
- }
- }
- cout<<"NO"<<'\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement