Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
#define mk make_pair
using namespace std;
int dx[]={0,0,1,-1},dy[]={1,-1,0,0};
int main(){
  int h,w,x,y,sol=0,pri=0;
  cin>>h>>w;
  bool b[h][w];
  string s[h];
  r(i,h)cin>>s[i];
  r(i,h)r(j,w)if(s[i][j]=='%')x=j,y=i;
  r(i,h)r(j,w)b[i][j]=0;
  queue<pair<int,int> >Q;
  queue<int>q1;
  q1.push(0);
  Q.push(mk(y,x));
  b[y][x]=1;
  while(!Q.empty()){
    pair<int,int >a=Q.front();Q.pop();
    int xx=a.second,yy=a.first,cc=q1.front();q1.pop();
    if(pri&&pri<cc)break;
    if(s[yy][xx]=='$'){sol=cc;break;}
    if(s[yy][xx]=='@'){pri=cc;}
    r(i,4){
      int x1=xx+dx[i],y1=yy+dy[i];
      if(x1<0||x1>=w||y1<0||y1>=h||b[y1][x1]||s[y1][x1]=='#')continue;
      Q.push(mk(y1,x1));b[y1][x1]=1;
      q1.push(cc+1);
    }
  }
  if(sol==0)cout<<"Yes"<<endl;
  else cout<<"No"<<endl;
}