Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<bitset>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<cmath>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int dx[]={0,0,-1,1};
const int dy[]={-1,1,0,0};
const int maxn = 205;
char maze[maxn][maxn];
bool vis[maxn][maxn];
int n,m,dp,ds,cur;

const pair<int,int> step = make_pair(-1,-1);
queue<pair<int,int> > que;
void bfs(int x,int y)
{
    while(!que.empty()) que.pop();
    cur = 0,dp = INF,ds = INF;
    memset(vis,false,sizeof vis);

    vis[y][x] = true;
    que.push(make_pair(x,y));
    que.push(step);

    while(cur <= n+m && (dp==INF||ds==INF)){
        pair<int,int> u = que.front();
        que.pop();

        if(maze[u.second][u.first] == '@') dp = min(dp,cur);
        if(maze[u.second][u.first] == '$') ds = min(ds,cur);

        if(u == step){
            ++cur;
            que.push(step);
            continue;
        }
        for(int i=0;i<4;++i){
            int nx = u.first+dx[i],ny = u.second+dy[i];
            if(!vis[ny][nx] && 0<=nx && 0<=ny && nx<m && ny<n && maze[ny][nx] != '#'){
                vis[ny][nx] = true;
                que.push(make_pair(nx,ny));
            }
        }
    }
}

int main()
{
    while(~scanf("%d%d",&n,&m)){
        for(int i=0;i<n;++i){
            scanf("%s",maze[i]);
        }
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                if(maze[i][j] == '%'){
                    bfs(j,i);
                }
            }
        }
        if(dp < ds) puts("Yes");
        else puts("No");
    }
    return 0;
}