Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < n; i++)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef pair<ll,P> PP;
const long long int MOD = 1000000007;
const int INF = 1000000000;

int h, w;
char b[200][200];
int pri[200][200];
int sol[200][200];
queue<int> que;
int dh[4] = {0,1,0,-1};
int dw[4] = {1,0,-1,0};

int main(){
    cin >> h >> w;
    rep(i,h) rep(j,w) cin >> b[i][j];
    rep(i,h) rep(j,w){
        pri[i][j] = INF;
        sol[i][j] = INF;
    }
    rep(i,h) rep(j,w){
        if(b[i][j] == '$'){
            que.push(i*200+j);
            sol[i][j] = 0;
        }
    }
    while(!que.empty()){
        int q = que.front();
        que.pop();
        int hh = q/200, ww = q%200;
        rep(i,4){
            int y = q/200+dh[i], x = q%200+dw[i];
            if(0>y||y>=h||0>x||x>=w) continue;
            if(sol[y][x] <= sol[hh][ww]+1) continue;
            if(b[y][x] == '#') continue;
            sol[y][x] = sol[hh][ww]+1;
            que.push(y*200+x);
        }
    }
    rep(i,h) rep(j,w){
        if(b[i][j] == '@'){
            que.push(i*200+j);
            pri[i][j] = 0;
        }
    }
    while(!que.empty()){
        int q = que.front();
        que.pop();
        int hh = q/200, ww = q%200;
        rep(i,4){
            int y = hh+dh[i], x = ww+dw[i];
            if(0>y||y>=h||0>x||x>=w) continue;
            if(pri[y][x] <= pri[hh][ww]+1) continue;
            if(sol[y][x] <= pri[hh][ww]+1) continue;
            if(b[y][x] == '#') continue;
            pri[y][x] = pri[hh][ww]+1;
            que.push(y*200+x);
        }
    }
    rep(i,h) rep(j,w){
        if(b[i][j] == '%'){
            if(pri[i][j] != INF){
                cout << "Yes" << endl;
                return 0;
            }
        }
    }
    cout << "No" << endl;
}