Problem: Example

Input

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


Output

Yes

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
using namespace std;
char pal[207][207];
int sol[207][207];
int pri[207][207];
int h, w;
bool flag;

void rec_sol(int i, int j)
{
	if (j+1 < w) if (sol[i][j+1] > sol[i][j]+1 && (pal[i][j+1]=='.'||pal[i][j+1]=='%'||pal[i][j+1]=='@')) {
		sol[i][j+1] = sol[i][j]+1;
		rec_sol(i, j+1);
	}
	if (j-1 > -1) if (sol[i][j-1] > sol[i][j]+1 && (pal[i][j-1]=='.'||pal[i][j-1]=='%'||pal[i][j-1]=='@')) {
		sol[i][j-1] = sol[i][j]+1;
		rec_sol(i, j-1);
	}
	if (i+1 < h) if (sol[i+1][j] > sol[i][j]+1 && (pal[i+1][j]=='.'||pal[i+1][j]=='%'||pal[i+1][j]=='@')) {
		sol[i+1][j] = sol[i][j]+1;
		rec_sol(i+1, j);
	}
	if (i-1 > -1) if (sol[i-1][j] > sol[i][j]+1 && (pal[i-1][j]=='.'||pal[i-1][j]=='%'||pal[i-1][j]=='@')) {
		sol[i-1][j] = sol[i][j]+1;
		rec_sol(i-1, j);
	}
}

void rec_pri(int i, int j)
{
	if (pal[i][j]=='%'&&pri[i][j] < sol[i][j]) flag = 1;
	if (j+1 < w) if (pri[i][j+1] > pri[i][j]+1 && (pal[i][j+1]=='.'|| pal[i][j+1]=='%')) {
		pri[i][j+1] = pri[i][j]+1;
		rec_pri(i, j+1);
	}
	if (j-1 > -1) if (pri[i][j-1] > pri[i][j]+1 && (pal[i][j-1]=='.'|| pal[i][j-1]=='%')) {
		pri[i][j-1] = pri[i][j]+1;
		rec_pri(i, j-1);
	}
	if (i+1 < h) if (pri[i+1][j] > pri[i][j]+1 && (pal[i+1][j]=='.'|| pal[i+1][j]=='%')) {
		pri[i+1][j] = pri[i][j]+1;
		rec_pri(i+1, j);
	}
	if (i-1 > -1) if (pri[i-1][j] > pri[i][j]+1 && (pal[i-1][j]=='.'|| pal[i-1][j]=='%')) {
		pri[i-1][j] = pri[i][j]+1;
		rec_pri(i-1, j);
	}
	
}

int main(void)
{
	int i, j, p, q;
	scanf("%d %d", &h, &w);
	for (i = 0; i < h; i++) scanf("%s", pal[i]);
	for (i = 0; i < h; i++) 
		for (j = 0; j < w; j++) {
			sol[i][j] = 1000;
			pri[i][j] = 1000;
		}
	for (i = 0; i < h; i++) {
		for (j = 0; j < w; j++) {
			if (pal[i][j]=='$') {
				sol[i][j] = 0;
				rec_sol(i, j);
			}
			if (pal[i][j]=='@') {
				p = i; q = j;
			}
		}
	}
	flag = 0;
	pri[p][q] = 0;
	rec_pri(p, q);
	/* for (i = 0; i < h; i++) {
		for (j = 0; j < w; j++) printf(" %d", sol[i][j]);
		printf("\n"); 
	}
	for (i = 0; i < h; i++) {
		for (j = 0; j < w; j++) printf(" %d", pri[i][j]);
		printf("\n"); 
	} */
	if (flag) printf("Yes\n");
	else printf("No\n");
	
	
	return 0;
}