Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repl(i,0,n)
#define mp(a,b) make_pair((a),(b))
#define pb(a) push_back((a))
#define all(x) (x).begin(),(x).end()
#define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x))
#define fi first
#define se second
#define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
void _dbg(string){cout<<endl;}
template<class H,class... T> void _dbg(string s,H h,T... t){int l=s.find(',');cout<<s.substr(0,l)<<" = "<<h<<", ";_dbg(s.substr(l+1),t...);}
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

#define INF 1120000000

int main(){
  int h,w;
  cin>>h>>w;
  vector<string> vec(h+2);
  rep(i,h) cin>>vec[i+1];
  vec[0] = string(w+2,'#');
  vec[h+1] =  string(w+2, '#');
  rep(i,h) vec[i+1] = "#" + vec[i+1] + "#";

  h+=2; w+=2;
  int sx,sy;
  rep(i,h)rep(j,w)if(vec[i][j]=='%') sx=i,sy=j;

  vector<vector<int>> d(h, vector<int>(w, -1));

  queue<int> x,y;
  x.push(sx); y.push(sy);
  while(!x.empty()){
    int i = x.front(); x.pop();
    int j = y.front(); y.pop();
    const int dx[] = {0,0,1,-1}, dy[]={1,-1,0,0};
    rep(k,4){
      int nx = i+dx[k], ny=j+dy[k];
      if(vec[nx][ny]=='#' || d[nx][ny]!=-1) continue;
      d[nx][ny] = d[i][j]+1;
      x.push(nx); y.push(ny);
    }
  }

  int p=0, s=INF;
  rep(i,h)rep(j,w){
    if(vec[i][j]=='@') p = d[i][j];
    if(vec[i][j]=='$') s = min(s,d[i][j]);
  }

  if(p < s) cout << "Yes" << endl;
  else cout << "No" << endl;

  return 0;
}