Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a) (a).begin(),(a).end()
#define vi vector<int>
#define pb push_back
#define INF 999999999
//#define INF (1LL<<59(
 
 
#define GRID_Y 300
#define GRID_X 300
#define WALL '#'
int h,w;
string data[GRID_Y];
void grid_bfs(int sy,int sx,int d[GRID_Y][GRID_X]){
    bool used[GRID_Y][GRID_X];
    rep(i,GRID_Y)rep(j,GRID_X)used[i][j]=false;
    
    rep(i,GRID_Y)rep(j,GRID_X)d[i][j]=INF;
    d[sy][sx]=0;
    
    queue<pii> que;
    que.push(pii(sy,sx));
    while(que.size()){
        int y=que.front().first, x=que.front().second;
        que.pop();
        if(used[y][x])continue;
        used[y][x]=true;
        
        int dy[]={1,0,-1,0},dx[]={0,1,0,-1};
        rep(i,4){
            int ddy=y+dy[i],ddx=x+dx[i];
            if(ddx<0||ddy<0||ddx>=w||ddy>=h||used[ddy][ddx]||data[ddy][ddx]==WALL)continue;
            d[ddy][ddx]=d[y][x]+1;
            que.push(pii(ddy,ddx));
        }
    }
}
 
 
 
int main(){
    cin>>h>>w;
    rep(i,h) cin>>data[i];
    
    pii goal,pr;
    vector<pii> arm;
    rep(i,h){
        rep(j,w){
            if( data[i][j]=='@' )pr   = pii(i,j);
            if( data[i][j]=='%' )goal = pii(i,j);
            if( data[i][j]=='$' )arm.pb( pii(i,j) );
        }
    }
    int d[300][300];
    grid_bfs(goal.first,goal.second,d);
    
 
    int prt = d[pr.first][pr.second];
    int armt= INF;
    
    rep(i,arm.size()){
        armt = min(armt, d[arm[i].first][arm[i].second] );
    }
 
    if(prt<armt)cout<<"Yes"<<endl;
    else cout<<"No"<<endl;
    
//    cout<<prt<<" "<<armt<<endl;
    
}