Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <queue>
using namespace std;
typedef pair<int,int> P;
typedef pair<P,int> PP;
int H,W;
int sx,sy,gx,gy;
int dx[4] = {-1,1,0,0},dy[4] = {0,0,-1,1};
int visited[210][210] = {};
char F[210][210];

bool in(int x,int y){
    return 1<=x && x<=H && 1<=y && y<=W;
}

int main(){
    cin >> H >> W;
    queue<PP> Q;
    for(int i=1;i<=H;i++){
        for(int j=1;j<=W;j++){
            cin >> F[i][j];
            if(F[i][j]=='@'){
                sx = i; sy = j;
            }else if(F[i][j]=='%'){
                gx = i; gy = j;
            }else if(F[i][j]=='$'){
                visited[i][j] = -1;
                Q.push({{i,j},-1});
            }
        }
    }
    Q.push({{sx,sy},1});
    while(!Q.empty()){
        PP pp = Q.front(); Q.pop();
        int x = pp.first.first,y = pp.first.second;
        for(int i=0;i<4;i++){
            int nx = x+dx[i],ny = y+dy[i];
            if(!in(nx,ny) || visited[nx][ny]!=0 || F[nx][ny]=='#') continue;
            visited[nx][ny] = pp.second;
            Q.push({{nx,ny},pp.second});
        }
    }
    cout << (visited[gx][gy]==1? "Yes":"No") << endl;
}