Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

queue<pair<int,int> > q;
int n,m;
int w[205][205];
int d[205][205];
int f[205][205];
char op;
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};
int sx,sy;

void bfs(int x,int y)
{
	pair<int,int> now,temp;
	now = make_pair(x,y);
	d[x][y] = 0;
	q.push(now);
	int nx,ny;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		x = now.first;
		y = now.second;
		for (int i=0;i<4;i++)
		{
			nx = x+dx[i];
			ny = y+dy[i];
			if (d[nx][ny] > d[x][y]+1 && w[nx][ny])
			{
				d[nx][ny] = d[x][y]+1;
				temp = make_pair(nx,ny);
				q.push(temp);
			}
		}
	}
}

bool solve(int x,int y)
{
	pair<int,int> now,temp;
	f[x][y] = 0;
	now = make_pair(x,y);
	q.push(now);
	int nx,ny;
	while (!q.empty())
	{
		now = q.front();
		q.pop();
		x = now.first;
		y = now.second;
		if (w[x][y] == 5) return 1;
		for (int i=0;i<4;i++)
		{
			nx = x+dx[i];
			ny = y+dy[i];
			if (w[nx][ny] == 0 || f[nx][ny] != f[0][0]) continue;
			f[nx][ny] = f[x][y]+1;
			if (f[nx][ny] < d[nx][ny])
			{
				temp = make_pair(nx,ny);
				q.push(temp);
			}
		}
	}
	return 0;
}

int main()
{
	scanf("%d%d",&n,&m);
	memset(w,0,sizeof(w));
	memset(d,0x3f,sizeof(d));
	memset(f,0x3f,sizeof(f));
	for (int i=1;i<=n;i++)
	{
		for (int j=1;j<=m;j++)
		{
			scanf(" %c",&op);
			if (op == '@')
			{
				w[i][j] = 4;
				sx = i;
				sy = j;
			}
			if (op == '%')
			{
				w[i][j] = 5;
			}
			if (op == '$')
			{
				w[i][j] = 2;
			}
			if (op == '.')
			{
				w[i][j] = 1;
			}
		}
	}
/*	printf("n=%d m=%d\n",n,m);
	for (int i=0;i<=n+1;i++)
	{
		for (int j=0;j<=m+1;j++)
			printf("%d",w[i][j]);
		printf("\n");
	}*/

	for (int i=1;i<=n;i++)
	{
		for (int j=1;j<=m;j++)
		{
			if (w[i][j] == 2)
			{
				bfs(i,j);
			}
		}
	}

	if (solve(sx,sy))
	{
		printf("Yes\n");
	}
	else
	{
		printf("No\n");
	}

	return 0;
}