Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<cmath>
#include<vector>
#include<cstdio>
#include<queue>

using namespace std;

#define maxn 215
#define ll long long

char s[maxn][maxn];
bool vis[maxn][maxn];

struct node{
int x,y;
int k;
};

vector<node> sol;
node pr;
node sa;
queue<node> Q;

int main(){
    int h,w;
    scanf("%d%d",&h,&w);
    getchar();
    for(int i=0;i<h;i++)
        scanf("%s",s+i);
    for(int i=0;i<h;i++)
    for(int j=0;j<w;j++){
        if(s[i][j]=='@') {
            pr.x=i;pr.y=j;pr.k=0;
        }
        if(s[i][j]=='$'){
            node so;
            so.x=i;so.y=j;
            so.k=1;
            sol.push_back(so);
        }
        if(s[i][j]=='%'){
            sa.x=i;
            sa.y=j;
            sa.k=0;
        }
    }
    memset(vis,false,sizeof(vis));
    for(int i=0;i<sol.size();i++){
        Q.push(sol[i]);
        vis[sol[i].x][sol[i].y]=true;
    }
    Q.push(pr);
    vis[pr.x][pr.y]=true;
    bool flag=false;
    while(!Q.empty()){
            node now=Q.front();
            Q.pop();
            int x=now.x;
            int y=now.y;
            if(x==sa.x&&y==sa.y){
                if(now.k==0) flag=true;
                else flag=false;
                break;
            }
            if(x+1<h&&!vis[x+1][y]&&s[x+1][y]!='#'){
                node ny=now;
                ny.x++;
                vis[x+1][y]=true;
                Q.push(ny);
            }
            if(x-1>=0&&!vis[x-1][y]&&s[x-1][y]!='#'){
                node ny=now;
                ny.x--;
                vis[x-1][y]=true;
                Q.push(ny);
            }
            if(y-1>=0&&!vis[x][y-1]&&s[x][y-1]!='#'){
                node ny=now;
                ny.y--;
                vis[x][y-1]=true;
                Q.push(ny);
            }
            if(y+1<w&&!vis[x][y+1]&&s[x][y+1]!='#'){
                node ny=now;
                ny.y++;
                vis[x][y+1]=true;
                Q.push(ny);
            }
    }
    if(flag) printf("Yes\n");
    else printf("No\n");
    return 0;
}