Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;
vector<int> dy = {1, 0, -1, 0};
vector<int> dx = {0, 1, 0, -1};
int INF = 100000;
int main(){
  int H, W;
  cin >> H >> W;
  vector<vector<char>> A(H + 2, vector<char>(W + 2, '#'));
  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      cin >> A[i][j];
    }
  }
  int ey, ex;
  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      if (A[i][j] == '%'){
        ey = i;
        ex = j;
      }
    }
  }
  vector<vector<int>> d(H + 2, vector<int>(W + 2, INF));
  d[ey][ex] = 0;
  queue<pair<int, int>> Q;
  Q.push(make_pair(ey, ex));
  while (!Q.empty()){
    int y = Q.front().first;
    int x = Q.front().second;
    Q.pop();
    for (int i = 0; i < 4; i++){
      int y2 = y + dy[i];
      int x2 = x + dx[i];
      if (d[y2][x2] == INF && A[y2][x2] != '#'){
        d[y2][x2] = d[y][x] + 1;
        Q.push(make_pair(y2, x2));
      }
    }
  }
  int p;
  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      if (A[i][j] == '@'){
        p = d[i][j];
      }
    }
  }
  bool ok = true;
  for (int i = 1; i <= H; i++){
    for (int j = 1; j <= W; j++){
      if (A[i][j] == '$' && d[i][j] <= p){
        ok = false;
      }
    }
  }
  if (ok){
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
}