Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
using namespace std;


#define ll long long
#define ull unsigned long long
#define pb push_back
#define mem(arr,val)    memset(arr,val,sizeof(arr))
#define mp make_pair
#define pii pair<int,int>
#define F first
#define S second
#define sz(x) (int)(x).size()
#define nopos string::npos
#define fr(i,a,b) for(i=a;i<=b;i++)
#define frn(i,a,b) for(i=a;i>=b;i--)
bool visited[500][500];
int level[500][500],r,c,i,j,eR,eC,dx[]= {+1,-1,+0,+0},dy[]= {0,0,+1,-1};
char grid[500][500];
int pR,pC;

int bfs(int sr,int sc)
{
    int in;
    queue<pii > q;
    q.push({sr,sc});
    level[sr][sc]=0;
    visited[sr][sc]=1;

    while(!q.empty())
    {
        pii u=q.front();
        q.pop();

        fr(in,0,3)
        {
            int vr=u.first+dx[in], vc=u.second+dy[in];
            if(vr<0 || vr>=r || vc<0 || vc>=c)
                continue;

            if(!visited[vr][vc] && grid[vr][vc]!='#')
            {
                visited[vr][vc]=1;
                q.push({vr,vc});
                level[vr][vc]=level[u.first][u.second]+1;
            }
        }

    }

    return level[eR][eC];
}

int main()
{
    //freopen("d://i.txt","r",stdin);
    //freopen("d://o.txt","w",stdout);
    cin>>r>>c;

    vector<pii > pos;

    fr(i,0,r-1)
    {
        getchar();
        fr(j,0,c-1)
        {
            scanf("%c",&grid[i][j]);
            if(grid[i][j]=='%')
                eR=i, eC=j;
            else if(grid[i][j]=='@')
                pR=i, pC=j;
        }
    }
//    fr(i,0,r-1)
//    {
//        fr(j,0,c-1)
//        printf("%c ",grid[i][j]);
//
//        cout<<'\n';
//    }
    int tim1=bfs(pR,pC),tim2=10000;

    memset(visited,0,sizeof(visited));

    bfs(eR,eC);

    fr(i,0,r-1)
     fr(j,0,c-1)
      {
          if(grid[i][j]=='$')
          tim2=min(tim2,level[i][j]);
      }

    //cout<<tim1<<' '<<tim2<<'\n';

    printf(tim1<tim2?"Yes\n":"No\n");

    return 0;
}