Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <tuple>
#include <queue>
#include <set>
#include <cstdio>
#include <climits>
#include <cmath>
#include <array>
#include <functional>
#include <list>
#include <iomanip>
#include <set>
const int MOD=1000000007;
const int INF=1000000000;
using namespace std;
typedef long long ll;
typedef vector<int> vi;
const double eps=1e-9;
const int inf=1e9;
typedef pair<int,int> P;
struct Point
{
  double x,y,z;
};
Point operator-(const Point& a,const Point& b)
{
  Point ret={a.x-b.x,a.y-b.y,a.z-b.z};
  return ret;
}
double dot(Point a,Point b)
{
  return a.x*b.x+a.y*b.y+a.z*b.z;
}
Point cross(Point a,Point b)
{
  Point ret={a.y*b.z-a.z*b.y,a.z*b.x-a.x*b.z,a.x*b.y-a.y*b.x};
  return ret;
}
double norm(Point a)
{
  return a.x*a.x+a.y*a.y+a.z*a.z;
}

string board[210];
int H,W;
int sx,sy;
int gx,gy;
int primin=inf;
int solmin=inf;
int d[210][210];
int dx[]={-1,0,1,0};
int dy[]={0,-1,0,1};
typedef pair<int,int> P;
void solve(int sy,int sx,char decide)
{
  queue<P> que;
  for(int i=0;i<H;i++)
    {
      for(int j=0;j<W;j++)
	{
	  d[i][j]=inf;
	}
    }
  d[sy][sx]=0;
  que.push(P(sy,sx));
  while(!que.empty())
    {
      P p=que.front();que.pop();
      gy=p.first;
      gx=p.second;
      if(board[p.first][p.second]==decide) break;
      for(int i=0;i<4;i++)
	{
	  int ny=p.first+dy[i];
	  int nx=p.second+dx[i];
	  if(ny<0 || H<=ny || nx<0 || W<=nx || board[ny][nx]=='#' || d[ny][nx]!=inf) continue;
	  que.push(P(ny,nx));
	  d[ny][nx]=d[p.first][p.second]+1;
	}
    }
  if(decide=='@') primin=min(primin,d[gy][gx]);
  else if(decide=='$') solmin=min(solmin,d[gy][gx]);
}

int main(int argc,char const* argv[])
{
  cin >> H >> W;
  for(int i=0;i<H;i++)
    {
      cin >> board[i];
    }
  bool solex=false;
  for(int i=0;i<H;i++)
    {
      for(int j=0;j<W;j++)
	{
	  if(board[i][j]=='%')
	    {
	      sy=i,sx=j;
	    }
	  if(board[i][j]=='$') solex=true;
	}
    }
  solve(sy,sx,'@');
  if(solex) solve(sy,sx,'$');
  if(primin>=solmin){cout << "No" << endl;}
  else{cout << "Yes" << endl;}
  return 0;
}