Problem: Example

Input

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


Output

Yes

Solution (in CPP):

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

using namespace std;

using ll = long long;
using Pi = pair<int, int>;
using Pl = pair<ll, ll>;
using Ti = tuple<int, int, int>;
using Tl = tuple<ll, ll, ll>;

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define F first
#define S second
#define Get(t, i) get<(i)>((t))
#define all(v) (v).begin(), (v).end()
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define reps(i, f, n) for(int i = (int)(f); i < (int)(n); i++)
#define each(a, b) for(auto& a : b)

const int inf = 1 << 25;
const ll INF = 1LL << 55;

int main()
{
  int H, W;
  cin >> H >> W;
  char mas[202][202];
  queue<Pi> que;
  rep(i, H) rep(j, W) {
    cin >> mas[i][j];
    if(mas[i][j] == '%') que.push(Pi(i, j));
  }
  int dx[] = {0, 1, 0, -1};
  int dy[] = {1, 0, -1, 0};
  int d[202][202]; memset(d, -1, sizeof(d));
  d[que.front().F][que.front().S] = 0;
  int pri = -1; vector<int> sol;
  while(!que.empty()) {
    Pi p = que.front(); que.pop();
    if(mas[p.F][p.S] == '@') {
      pri = d[p.F][p.S];
    } else if(mas[p.F][p.S] == '$') {
      sol.push_back(d[p.F][p.S]);
    }
    rep(i, 4) {
      if(0 <= p.F+dy[i] && p.F+dy[i] < H &&
	 0 <= p.S+dx[i] && p.S+dx[i] < W &&
	 mas[p.F+dy[i]][p.S+dx[i]] != '#' &&
	 d[p.F+dy[i]][p.S+dx[i]] == -1) {
	que.push(Pi(p.F+dy[i], p.S+dx[i]));
	d[p.F+dy[i]][p.S+dx[i]] = d[p.F][p.S] + 1;
      }
    }
  }
  cout << (pri != -1 && (sol.empty() || *min_element(all(sol)) > pri) ? "Yes" : "No") << endl;
  return 0;
}