Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include "bits/stdc++.h"

using namespace std;

typedef pair<int, int> P;
const int INF = numeric_limits<int>::max() / 2;

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

    int h,w;cin>>h>>w;
    vector<string> v(h);
    int sx,sy,px,py;
    for(int i=0;i<h;i++){
        cin>>v[i];
        for(int j=0;j<w;j++){
            if(v[i][j]=='%'){
                sx=i;sy=j;
            }
            else if(v[i][j]=='@'){
                px=i;py=j;
            }
        }
    }
    vector<vector<int> > dis(300,vector<int>(300,INF));
    dis[sx][sy]=0;
    int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
    queue<P> q;
    q.push(P(sx,sy));
    while(!q.empty()){
        P p=q.front();q.pop();
        int x=p.first,y=p.second;
        for(int i=0;i<4;i++){
            int nx=x+dx[i],ny=y+dy[i];
            if(nx<0 || h<=nx || ny<0 || w<=ny) continue;
            if(v[nx][ny]=='#') continue;
            if(dis[nx][ny]!=INF) continue;
            dis[nx][ny]=dis[x][y]+1;
            q.push(P(nx,ny));
        }
    }
    int pdis=dis[px][py];
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            if(v[i][j]!='$') continue;
            if(dis[i][j]<=pdis){
                cout<<"No"<<endl;
                return 0;
            }
        }
    }
    cout<<"Yes"<<endl;
    return 0;
}