Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define ll long long
#define INF 1000000005
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;--i)
#define srep(i,s,t) for(int i=(int)(s);i<(int)(t);++i)
#define each(a,b) for(auto (a): (b))
#define all(v) (v).begin(),(v).end()
#define len(v) (int)(v).size()
#define zip(v) sort(all(v)),v.erase(unique(all(v)),v.end())
#define cmx(x,y) x=max(x,y)
#define cmn(x,y) x=min(x,y)
#define fi first
#define se second
#define pb push_back
#define show(x) cout<<#x<<" = "<<(x)<<endl
#define spair(p) cout<<#p<<": "<<p.fi<<" "<<p.se<<endl
#define svec(v) cout<<#v<<":";rep(kbrni,v.size())cout<<" "<<v[kbrni];cout<<endl
#define sset(s) cout<<#s<<":";each(kbrni,s)cout<<" "<<kbrni;cout<<endl
#define smap(m) cout<<#m<<":";each(kbrni,m)cout<<" {"<<kbrni.first<<":"<<kbrni.second<<"}";cout<<endl

using namespace std;

typedef pair<int,int> P;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<P> vp;
typedef vector<string> vs;

const int MAX_N = 2001;
const int dx[] = {1,0,0,-1};
const int dy[] = {0,1,-1,0};

int d[MAX_N][MAX_N];
int e[MAX_N][MAX_N];

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    int h,w;
    cin >> h >> w;
    vs fd(h);
    int si,sj;
    vp vec;
    rep(i,h){
        cin >> fd[i];
        rep(j,w){
            if(fd[i][j] == '@'){
                si = i,sj = j;
            }else if(fd[i][j] == '$'){
                vec.pb(P(i,j));
            }
        }
    }
    rep(i,h){
        rep(j,w){
            d[i][j] = INF;
        }
    }
    queue<P> que;
    rep(i,len(vec)){
        que.push(P(vec[i]));
        d[vec[i].fi][vec[i].se] = 0;
    }
    while(!que.empty()){
        P p = que.front();
        que.pop();
        rep(i,4){
            int nx = p.fi+dx[i],ny = p.se+dy[i];
            if(0 <= nx && nx < h && 0 <= ny && ny < w && fd[nx][ny] != '#'){
                if(d[nx][ny] > d[p.fi][p.se]+1){
                    d[nx][ny] = d[p.fi][p.se]+1;
                    que.push(P(nx,ny));
                }
            }
        }
    }
    queue<P> q;
    q.push(P(si,sj));
    rep(i,h){
        rep(j,w){
            e[i][j] = INF;
        }
    }
    e[si][sj] = 0;
    while(!q.empty()){
        P p = q.front();
        q.pop();
        rep(i,4){
            int nx = p.fi+dx[i],ny = p.se+dy[i];
            if(0 <= nx && nx < h && 0 <= ny && ny < w && fd[nx][ny] != '#' && d[nx][ny] > e[p.fi][p.se]+1){
                if(e[nx][ny] > e[p.fi][p.se]+1){
                    if(fd[nx][ny] == '%'){
                        cout << "Yes\n";
                        return 0;
                    }
                    e[nx][ny] = e[p.fi][p.se]+1;
                    q.push(P(nx,ny));
                }
            }
        }
    }
    cout << "No\n";
    return 0;
}