Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;
const int INF=1e9;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int H,W; cin >> H >> W;
    vector<string> f(H);
    for (int i=0;i<H;++i) cin >> f[i];
    int sx,sy;
    for (int i=0;i<H;++i)
        for (int j=0;j<W;++j)
            if (f[i][j]=='%')
                sx=i,sy=j;
    vector<vector<int>> dist(H,vector<int>(W,-1));
    queue<pair<int,int>> que;
    dist[sx][sy]=0; que.emplace(sx,sy);
    int princess,soldiar=INF;
    while(!que.empty()){
        auto p=que.front(); que.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 (f[nx][ny]=='#') continue;
            if (dist[nx][ny]!=-1) continue;
            dist[nx][ny]=dist[x][y]+1;
            que.emplace(nx,ny);
            if (f[nx][ny]=='@') princess=dist[nx][ny];
            if (f[nx][ny]=='$') soldiar=min(soldiar,dist[nx][ny]);
        }
    }
    cout << (princess<soldiar?"Yes":"No") << '\n';
}