Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;

#define rep(i, n) for(int i = 0; i < (n); i++)
#define repp(i, l, r) for(int i = (l); i < (r); i++)
#define per(i, n) for(int i = ((n)-1); i >= 0; i--)
#define perr(i, l, r) for(int i = ((r)-1); i >= (l); i--)
#define all(x) (x).begin(),(x).end()
#define MOD 1000000007
#define IINF 1000000000
#define LINF 1000000000000000000
#define SP <<" "<<
#define CYES cout<<"Yes"<<endl
#define CNO cout<<"No"<<endl
#define CFS cin.tie(0);ios::sync_with_stdio(false)

typedef long long LL;
typedef long double LD;



int main(){
  int h,w;
  cin >> h >> w;
  vector<string> f(h);
  queue<pair<pair<int,int>,int>> q;
  vector<vector<bool>> visited(h,vector<bool>(w,false));
  int sx,sy,gx,gy;
  rep(i,h){
    cin >> f[i];
    rep(j,w){
      if(f[i][j]=='@'){
        sx=i,sy=j;
        f[i][j]='.';
      }else if(f[i][j]=='$'){
        q.push({{i,j},0});
        visited[i][j]=true;
        f[i][j]='.';
      }else if(f[i][j]=='%'){
        gx=i,gy=j;
        f[i][j]='.';
      }
    }
  }
  vector<int> v={0,1,0,-1,0};
  int gd=IINF;
  while(!q.empty()){
    auto now = q.front();
    q.pop();
    rep(i,4){
      int nx = now.first.first+v[i];
      int ny = now.first.second+v[i+1];
      if(0<=nx&&nx<h&&0<=ny&&ny<w){
        if(f[nx][ny]=='.'&&!visited[nx][ny]){
          visited[nx][ny]=true;
          if(nx==gx&&ny==gy){
            gd=now.second+1;
            goto next;
          }
          q.push({{nx,ny},now.second+1});
        }
      }
    }
  }
  next:;
  while(!q.empty()) q.pop();
  visited=vector<vector<bool>>(h,vector<bool>(w,false));
  q.push({{sx,sy},0});
  while(!q.empty()){
    auto now = q.front();
    q.pop();
    rep(i,4){
      int nx = now.first.first+v[i];
      int ny = now.first.second+v[i+1];
      if(0<=nx&&nx<h&&0<=ny&&ny<w){
        if(f[nx][ny]=='.'&&!visited[nx][ny]){
          visited[nx][ny]=true;
          if(nx==gx&&ny==gy){
            if(now.second+1<gd){
              CYES;
            }else{
              CNO;
            }
            return 0;
          }
          q.push({{nx,ny},now.second+1});
        }
      }
    }
  }
  return 0;
}