Problem: Example

Input

2 4
%.@\$
..\$\$


Output

Yes

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
#define xx first
#define yy second
#define mp make_pair

using namespace std;
int n,m;
char ara[500][500];
int vis[500][500];

typedef pair<int,int> pp;

int fx[]={1,-1,0,0};
int fy[]={0,0,1,-1};

bool issafe(int x,int y){
    return ( x>0 && x<=n && y>0 && y<=m   );
}

void bfs(int s1,int s2){
    queue<pair<pp,int> >myq;
    myq.push(mp(mp(s1,s2),1));
    vis[s1][s2]=1;
    while(!myq.empty()){
        int x=myq.front().xx.xx;
        int y=myq.front().xx.yy;
        int d=myq.front().yy;
        myq.pop();
        for(int i=0;i<4;i++){
            int p=x+fx[i];
            int q=y+fy[i];
            if(issafe(p,q)){
                if(ara[p][q]!='#' && vis[p][q]==0){
                    vis[p][q]=vis[x][y]+1;
                    myq.push(mp(mp(p,q),vis[p][q]));
                }
            }
        }
    }
}

int main()
{
    cin>>n>>m;
    int pr1,pr2,s3,s4;

    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>ara[i][j];
            if(ara[i][j]=='%'){
                pr1=i,pr2=j;
            }
            if(ara[i][j]=='@'){
                s3=i;
                s4=j;
            }
        }
    }

    bfs(pr1,pr2);
    int val=vis[s3][s4];
    bool flag=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(ara[i][j]=='$'){
                if(vis[i][j]<=val){
                    flag=1;
                }
            }
        }
    }
    if(flag)cout<<"No"<<endl;
    else cout<<"Yes"<<endl;
}