Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <tuple>
#include <queue>

using namespace std;

using T3=tuple<int,int,int>;

int main(){
    int H,W;
    cin>>H>>W;
    char M[H][W];
    int dist[H][W];
    queue<T3> Q;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin>>M[i][j];
            if(M[i][j]=='%'){
                dist[i][j]=0;
                Q.push(T3(i,j,0));
            }else{
                dist[i][j]=1000000;
            }
        }
    }
    int dist_p = 1000000, dist_s=1000000;
    while(!Q.empty()){
        int i,j,d;
        tie(i,j,d)=Q.front();
        Q.pop();
        if(M[i][j]=='@') dist_p=d;
        if(M[i][j]=='$') dist_s=min(dist_s,d);
        int diff[5]={0,-1,0,1,0};
        for(int k=0;k<4;k++){
            if(i+diff[k]<0||i+diff[k]>=H||j+diff[k+1]<0||j+diff[k+1]>=W) continue;
            if(M[i+diff[k]][j+diff[k+1]]!='#'&&dist[i+diff[k]][j+diff[k+1]]==1000000){
                dist[i+diff[k]][j+diff[k+1]]=d+1;
                Q.push(T3(i+diff[k],j+diff[k+1],d+1));
            }
        }
    }
    if(dist_p<dist_s){
        cout<<"Yes"<<endl;
    }else{
        cout<<"No"<<endl;
    }

    return 0;
}