Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <queue>
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;
  for(int i = 0; i < H; ++i){
    for(int j = 0; j < W; ++j){
      if(M[i][j] == '%'){
	s_x = i;
	s_y = j;
      }
    }
  }
  queue< pair<int,int> > que;
  que.push(make_pair(s_x, s_y));
  vector< vector<int> > D(H, vector<int>(W,-1));
  D[s_x][s_y] = 0;
  int d[] = {1,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 x_next = x + d[i], y_next = y + d[i+1];
      if(x_next >= 0 && x_next < H && y_next >= 0 && y_next < W && M[x_next][y_next] != '#' && D[x_next][y_next] < 0){
	  D[x_next][y_next] = D[x][y] + 1;
	  que.push(make_pair(x_next, y_next));
	}
	}
    }
    int p = 1000000000, s = 1000000000;
    for(int i = 0; i < H; ++i){
      for(int j = 0; j < W; ++j){
	if(M[i][j] == '@')
	  p = D[i][j];
	if(M[i][j] == '$')
	  s = min(D[i][j],s);
      }
    }
    cout << ((p < s) ? "Yes" : "No") << endl;
    return 0;
}