Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <utility>
using namespace std;

int dx[4]={1, 0, 0, -1};
int dy[4]={0, 1, -1, 0};

int main(){
  int h,w;
  cin >> h >> w;

  int sx,sy;
  vector<vector<char> > map(h+2, vector<char>(w+2, '#'));
  for(int i=1; i<=h; i++){
    for(int j=1; j<=w; j++){
      cin >> map[i][j];
      if(map[i][j]=='%'){
        sy=i;
        sx=j;
      }
    }
  }

  queue<pair<int,pair<int,int> > > q;
  q.push(make_pair(0, make_pair(sy,sx)));
  map[sy][sx]='#';
  int princess=1e9;
  int soldier=1e9;
  while(!q.empty()){
    int step=q.front().first;
    int y=q.front().second.first;
    int x=q.front().second.second;
    q.pop();
    for(int i=0; i<4; i++){
      int nx=x+dx[i];
      int ny=y+dy[i];
      if(map[ny][nx]!='#'){
        if(map[ny][nx]=='@') princess = step;
        if(map[ny][nx]=='$') soldier = min(step, soldier);
        map[ny][nx] = '#';
        q.push(make_pair(step+1, make_pair(ny,nx)));
      }
    }
  }

  if(princess<soldier){
    cout << "Yes" << endl;
  }else{
    cout << "No" << endl;
  }
  return 0;
}