Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
using namespace std;
 
#define int long long
typedef vector<int>vint;
typedef pair<int,int>pint;
typedef vector<pint>vpint;
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
#define all(v) (v).begin(),(v).end()
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define pb push_back
#define fi first
#define se second
template<typename A,typename B>inline void chmin(A &a,B b){if(a>b)a=b;}
template<typename A,typename B>inline void chmax(A &a,B b){if(a<b)a=b;}
 
const int INF=1001001001;
int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};
 
int H,W;
char fld[222][222];
int lim[222][222];
int dist[222][222];
 
signed main(){
    int sy,sx,gy,gx;
 
    cin>>H>>W;
 
    queue<pint>que;
    fill_n(*lim,222*222,INF);
 
    rep(i,H)rep(j,W){
        cin>>fld[i][j];
        if(fld[i][j]=='@'){
            sy=i;sx=j;
        }
        if(fld[i][j]=='%'){
            gy=i;gx=j;
        }
        if(fld[i][j]=='$'){
            lim[i][j]=0;
            que.push(pint(i,j));
        }
    }
    while(que.size()){
        int y,x;
        tie(y,x)=que.front();
        que.pop();
 
        rep(i,4){
            int ny=y+dy[i],nx=x+dx[i];
            if(ny<0||ny>=H||nx<0||nx>=W||fld[ny][nx]=='#'||lim[ny][nx]!=INF)continue;
            lim[ny][nx]=lim[y][x]+1;
            que.push(pint(ny,nx));
        }
    }
 
    fill_n(*dist,222*222,INF);
    dist[sy][sx]=0;
    que.push(pint(sy,sx));
    while(que.size()){
        int y,x;
        tie(y,x)=que.front();
        que.pop();
 
        rep(i,4){
            int ny=y+dy[i],nx=x+dx[i];
            if(ny<0||ny>=H||nx<0||nx>=W||dist[ny][nx]!=INF||fld[ny][nx]=='#'||lim[ny][nx]<=dist[y][x]+1)continue;
            dist[ny][nx]=dist[y][x]+1;
            que.push(pint(ny,nx));
        }
    }
 
    if(dist[gy][gx]!=INF){
        cout<<"Yes"<<endl;
    }
    else{
        cout<<"No"<<endl;
    }
    return 0;
}