Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main(){
  int H, W;
  cin >> H >> W;
  string M[H];
  for(int i = 0; i < H; ++i){
    cin >> M[i];
  }
  int s_x, s_y, g_x, g_y;
  for(int i = 0; i < H; ++i){
    for(int j = 0; j < W; ++j){
      if(M[i][j] == '%'){
        s_x = i;
        s_y = j;
      }
      if(M[i][j] == '@'){
        g_x = i;
        g_y = j;
      }
    }
  }
  int d[H][W];
  for(int i = 0; i < H; ++i) fill(d[i],d[i]+W,-1);
  d[s_x][s_y] = 0;
  queue< pair<int,int> > que;
  que.push(make_pair(s_x, s_y));
  int dx[] = {1,0,-1,0}, dy[] = {0,1,0,-1};
  while(!que.empty()){
    int x = que.front().first, y = que.front().second;
    que.pop();
    for(int i = 0; i < 4; ++i){
      int next_x = x + dx[i], next_y = y + dy[i];
      if(next_x >= 0 && next_x < H && next_y >= 0 && next_y < W && d[next_x][next_y] < 0 && M[next_x][next_y] != '#'){
        d[next_x][next_y] = d[x][y] + 1;
        que.push(make_pair(next_x, next_y));
      }
    }
  }
  int princess = 100000000, soldier = princess;
  for(int i = 0; i < H; ++i){
    for(int j = 0; j < W; ++j){
      if(M[i][j] == '@') princess = min(princess, d[i][j]);
      if(M[i][j] == '$') soldier = min(soldier, d[i][j]);
      
    }
  }
  if(princess < soldier) cout << "Yes" << endl;
  else cout << "No" << endl;
  return 0;
}