Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>

using namespace std;

const int vy[] = {0, 1, 0, -1}, vx[] = {1, 0, -1, 0};

int H, W;
string S[200];
int v[200][200];

bool bfs()
{
  queue< pair< int, int > > que;
  memset(v, -1, sizeof(v));

  for(int i = 0; i < H; i++) {
    for(int j = 0; j < W; j++) {
      if(S[i][j] == '%') {
        que.emplace(j, i);
        v[j][i] = 0;
      }
    }
  }
  int me = 1 << 30, enemy = 1 << 30;

  while(!que.empty()) {
    auto p = que.front();
    que.pop();
    if(S[p.second][p.first] == '@') me = v[p.first][p.second];
    else if(S[p.second][p.first] == '$') enemy = min(enemy, v[p.first][p.second]);
    for(int i = 0; i < 4; i++) {
      int nx = p.first + vx[i], ny = p.second + vy[i];
      if(nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
      if(S[ny][nx] == '#') continue;
      if(~v[nx][ny]) continue;
      v[nx][ny] = v[p.first][p.second] + 1;
      que.emplace(nx, ny);
    }
  }
  return (me < enemy);
}

int main()
{
  cin >> H >> W;
  for(int i = 0; i < H; i++) cin >> S[i];
  if(bfs()) cout << "Yes" << endl;
  else cout << "No" << endl;
}