Problem: Example

Input

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


Output

Yes

Solution (in CPP):

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

#define int long long
#define pb push_back 
#define pf push_front 
#define mp make_pair
#define fr first
#define sc second
#define Rep(i, n) for ( int i = 0 ; i < (n); i++ )
#define All(v) v.begin(), v.end()

typedef pair<int, int> Pii; typedef pair<int, Pii> Pip;
const int INF = 1107110711071107;
const int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};

int H, W;
int ey, ex;
char maps[201][201];

int bfs1() {
  bool used[201][201] = {{0}};
  queue<Pip> q;
  q.push(Pip(0, Pii(ey, ex)));
  while ( !q.empty() ) {
    Pip p = q.front(); q.pop();
    int c = p.fr,  y = p.sc.fr, x = p.sc.sc;    

    if ( maps[y][x] == '@' ) {
      return c;
    }

    if ( used[y][x] ) continue;
    used[y][x] = true;

    Rep(i, 4) {
      int ny = y + dy[i], nx = x + dx[i];
      if ( ny < 0 || nx < 0 || ny >= H || nx >= W || maps[ny][nx] == '#' || maps[ny][nx] == '$' ) continue;
      q.push(Pip(c+1, Pii(ny, nx)));
    }
  }

  return INF;
}

int bfs2() {
  bool used[201][201] = {{0}};
  queue<Pip> q;
  q.push(Pip(0, Pii(ey, ex)));
  while ( !q.empty() ) {
    Pip p = q.front(); q.pop();
    int c = p.fr,  y = p.sc.fr, x = p.sc.sc;    

    if ( maps[y][x] == '$' ) {
      return c;
    }

    if ( used[y][x] ) continue;
    used[y][x] = true;

    Rep(i, 4) {
      int ny = y + dy[i], nx = x + dx[i];
      if ( ny < 0 || nx < 0 || ny >= H || nx >= W || maps[ny][nx] == '#' ) continue;
      q.push(Pip(c+1, Pii(ny, nx)));
    }
  }

  return INF;
}

signed main() {
  cin >> H >> W;
  Rep(i, H) Rep(j, W) {
    cin >> maps[i][j];
    if ( maps[i][j] == '%' ) ey = i, ex = j;
  }

  if ( bfs1() < bfs2() ) cout << "Yes" << endl;
  else cout << "No" << endl;
}