Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define MAXN 210
#define INF 0x3f3f3f3f
using namespace std;

int R,C;
char a[MAXN][MAXN];

struct Cell {
  int r, c;
  Cell(int r, int c):r(r),c(c) {}
};

const int dr[] = {-1,1,0,0};
const int dc[] = {0,0,-1,1};
int d[MAXN][MAXN][2], vis[MAXN][MAXN][2];

queue<Cell> Q;
void bfs(int kind) {
  while(!Q.empty()) {
    Cell cell = Q.front(); Q.pop();
    int r = cell.r, c = cell.c;
    for(int dir = 0; dir < 4; dir++) {
      int nr = r + dr[dir], nc = c + dc[dir];
      if(nr >= 0 && nr < R && nc >= 0 && nc < C && a[nr][nc] == '.' && !vis[nr][nc][kind]) {
        Q.push(Cell(nr, nc));
        vis[nr][nc][kind] = 1;
        d[nr][nc][kind] = d[r][c][kind] + 1;
      }
    }
  }
}

int ans;
void check(int r, int c) {
  if(a[r][c] != '.' || !vis[r][c][0]) return;
  if(!vis[r][c][1] || d[r][c][0] < d[r][c][1]) ans = min(ans, d[r][c][0] + 1);
}

int main() {

    scanf("%d%d", &R, &C);
    int jr, jc;
    int tr,tc;
    vector<Cell> fires;
    for(int i = 0; i < R; i++) {
      scanf("%s", a[i]);
      for(int j = 0; j < C; j++)

      if(a[i][j]=='%')
      {
      	tr=i; tc=j; a[i][j]='.';
	  }
        else if(a[i][j] == '@') { jr = i; jc = j; a[i][j] = '.'; }
        else if(a[i][j] == '$') { fires.push_back(Cell(i,j)); a[i][j] = '.'; }
    }
    memset(vis, 0, sizeof(vis));
    vis[jr][jc][0] = 1; d[jr][jc][0] = 0;
    Q.push(Cell(jr, jc));
    bfs(0);
    for(int i = 0; i < fires.size(); i++) {
      vis[fires[i].r][fires[i].c][1] = 1;
      d[fires[i].r][fires[i].c][1] = 0;
      Q.push(fires[i]);
    }
    bfs(1);
    ans = INF;
    check(tr,tc);
    if(ans == INF) printf("No\n"); else printf("Yes\n");
  
  return 0;
}