Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define mp make_pair
#define pii pair<int,int>
#define ss second
#define ff first
using namespace std ;
int mn_dist = 100000000 ;

int row , col , hx , hy , px,  py;

char g[405][405] ;
int vis[405][405] , d[405][405] ;

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


bool valid (int x,int y) {

    if (x >= 0 and x < row and y >= 0  and y < col and vis[x][y] == 0 and g[x][y] != '#' ) return 1 ;
    return  0 ;


}

void bfs (int sx, int sy) {

    memset (vis, 0 , sizeof vis) ;


    vis[sx][sy] = 1 ;

    d[sx][sy] = 0 ;


    queue <pair<int,int > > q ;
    q.push(mp(sx,sy)) ;

    while(!q.empty()) {
        pii u = q.front() ;
        int x = u.ff , y = u.ss ;
        q.pop() ;

        for(int i = 0 ; i < 4 ; i++) {
            int x_ = x+dx[i] , y_ = y+ dy[i] ;

            if (valid(x_,y_)) {
                vis[x_][y_] = 1 ;
                d[x_][y_] = d[x][y] + 1 ;
                q.push(mp(x_,y_)) ;
            }
        }
    }
}






int main () {

    cin >> row >> col ;
    for(int i = 0 ; i < row ; i++) scanf ("%s" , g[i]) ;

    for(int i = 0 ; i < row ; i++) {
        for(int j = 0 ; j < col ; j++) {
            if (g[i][j] == '@') px = i , py = j ;
            if (g[i][j] == '%') hx = i , hy = j ;
        }
    }

    bfs(hx,hy) ;
    int p_dist = d[px][py] ;
    for(int i = 0 ; i < row ; i++) {
        for(int j = 0 ; j < col ; j++) {
            if (g[i][j] == '$' and vis[i][j] == 1) {
                mn_dist = min(d[i][j],mn_dist) ;
            }
        }
    }

    if (mn_dist <= p_dist) {
        printf ("No\n") ;
    } else {
        printf ("Yes\n" ) ;
    }
}