Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#include <iostream>
#include <complex>
#include <string>
#include <algorithm>
#include <numeric>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>

#include <functional>
#include <cassert>

typedef long long ll;
using namespace std;

#ifndef LOCAL
#define debug(x) ;
#else
#define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl;

template <typename T1, typename T2>
ostream &operator<<(ostream &out, const pair<T1, T2> &p) {
  out << "{" << p.first << ", " << p.second << "}";
  return out;
}

template <typename T>
ostream &operator<<(ostream &out, const vector<T> &v) {
  out << '{';
  for (const T &item : v) out << item << ", ";
  out << "\b\b}";
  return out;
}
#endif

#define mod 1000000007 //1e9+7(prime number)
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18
#define SIZE 200010


int main(){
  int H, W;
  string m[200];
  int dist[200][200];

  cin >> H >> W;

  queue<pair<int,int> > que, queP;

  for (int i=0; i<H; i++) {
    cin >> m[i];
    for (int j=0; j<W; j++) {
      if (m[i][j] == '$') que.push({i, j});
      if (m[i][j] == '@') queP.push({i, j});
      dist[i][j] = INF;
    }
  }

  for(int i=0; que.size(); i++) {
    queue<pair<int,int> > que2;

    while(que.size()) {
      auto p = que.front();
      que.pop();
      int y = p.first;
      int x = p.second;

      if (m[y][x] == '#') continue;
      if (dist[y][x] < INF) continue;

      dist[y][x] = i;

      if (y > 0)   que2.push({y-1, x});
      if (x > 0)   que2.push({y, x-1});
      if (y+1 < H) que2.push({y+1, x});
      if (x+1 < W) que2.push({y, x+1});
    }

    que = que2;
  }

  for(int i=0; queP.size(); i++) {
    queue<pair<int,int> > que2;

    while(queP.size()) {
      auto p = queP.front();
      queP.pop();
      int y = p.first;
      int x = p.second;

      if (m[y][x] == '#') continue;
      if (dist[y][x] <= i) continue;
      dist[y][x] = -1;

      if (m[y][x] == '%') {
        puts("Yes");
        return 0;
      }

      if (y > 0)   que2.push({y-1, x});
      if (x > 0)   que2.push({y, x-1});
      if (y+1 < H) que2.push({y+1, x});
      if (x+1 < W) que2.push({y, x+1});
    }

    queP = que2;
  }


  puts("No");

  return 0;
}