Problem:

  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Help the Princess!

The people of a certain kingdom make a revolution against the bad government of the princess. The revolutionary army invaded the royal palace in which the princess lives. The soldiers of the army are exploring the palace to catch the princess. Your job is writing a program to decide that the princess can escape from the royal palace or not.

 For simplicity, the ground of the palace is a rectangle divided into a grid. There are two kinds of cells in the grid: one is a cell that soldiers and the princess can enter, the other is a cell that soldiers or the princess cannot enter. We call the former an empty cell, the latter a wall. The princess and soldiers are in different empty cells at the beginning. There is only one escape hatch in the grid. If the princess arrives the hatch, then the princess can escape from the palace. There are more than or equal to zero soldiers in the palace.

The princess and all soldiers take an action at the same time in each unit time. In other words, the princess and soldiers must decide their action without knowing a next action of the other people. In each unit time, the princess and soldiers can move to a horizontally or vertically adjacent cell, or stay at the current cell. Furthermore the princess and soldiers cannot move out of the ground of the palace. If the princess and one or more soldiers exist in the same cell after their move, then the princess will be caught. It is guaranteed that the princess can reach the escape hatch via only empty cells if all soldiers are removed from the palace.

If there is a route for the princess such that soldiers cannot catch the princess even if soldiers make any moves, then the princess can escape the soldiers. Note that if the princess and a soldier arrive the escape hatch at the same time, the princess will be caught. Can the princess escape from the palace?

Input

Each dataset is formatted as follows.

$H$ $W$

$map_1$

$map_2$

...

$map_H$

The first line of a dataset contains two positive integers $H$ and $W$ delimited by a space, where $H$ is the height of the grid and $W$ is the width of the grid ($2 \leq H, W \leq 200$).

The $i$-th line of the subsequent $H$ lines gives a string $map_i$, which represents situation in the ground of palace.

$map_i$ is a string of length $W$, and the $j$-th character of $map_i$ represents the state of the cell of the $i$-th row and the $j$-th column.

'@', '\$', '%', '.', and '#' represent the princess, a soldier, the escape hatch, an empty cell, and a wall, respectively. It is guaranteed that there exists only one '@', only one '%', and more than or equal to zero '\$' in the grid.

Output

Output a line containing a word "Yes", if the princess can escape from the palace. Otherwise, output "No".

Sample Input 1

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

Output for the Sample Input 1

Yes

Sample Input 2

3 4
.%..
.##.
.@\$.

Output for the Sample Input 2

Yes

Sample Input 3

2 3
%\$@
###

Output for the Sample Input 3

No

Sample Input 4

2 3
@#\$
.%.

Output for the Sample Input 4

No

Sample Input 5

2 2
@%
..

Output for the Sample Input 5

Yes



Sample input:
2 4
%.@\$
..\$\$


Sample output:
Yes

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    h,w = LI()
    mp = [S() for _ in range(h)]

    def search(ss):
        d = collections.defaultdict(lambda: inf)
        q = []
        for s in ss:
            d[s] = 0
            heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for di,dj in dd:
                ni = u[0] + di
                nj = u[1] + dj
                if ni < 0 or ni >= h or nj < 0 or nj >= w or mp[ni][nj] == '#':
                    continue
                uv = (ni, nj)
                if v[uv]:
                    continue
                vd = k + 1
                if d[uv] > vd:
                    d[uv] = vd
                    heapq.heappush(q, (vd, uv))

        return d

    ss = []
    ps = None
    es = None
    for i in range(h):
        for j in range(w):
            if mp[i][j] == '$':
                ss.append((i,j))
            elif mp[i][j] == '@':
                ps = (i,j)
            elif mp[i][j] == '%':
                es = (i,j)
    pd = search(ss)
    d = search([ps])
    if d[es] < pd[es]:
        return 'Yes'

    return 'No'


print(main())

Submission status: Accepted

Solution code:
import queue

di = [0,1,0,-1]
dj = [1,0,-1,0]

h, w = map(int, input().split())
field = [input() for i in range(h)]
pdist = [[1000]*w for i in range(h)]
sdist = [[1000]*w for i in range(h)]

pque = queue.Queue()
sque = queue.Queue()
for i,row in enumerate(field):
    for j in range(w):
        if row[j] is '@':
            pque.put((i,j))
            pdist[i][j] = 0
            pi = i
            pj = j
        if row[j] is '$':
            sque.put((i,j))
            sdist[i][j] = 0
        if row[j] is '%':
            gi = i
            gj = j

while not sque.empty():
    i,j = sque.get()
    for k in range(4):
        ni = i+di[k]
        nj = j+dj[k]
        if ni >=0 and ni < h and nj >= 0 and nj < w:
            if (field[ni][nj] is not '#') and sdist[ni][nj] > sdist[i][j]+1:
                sdist[ni][nj] = sdist[i][j]+1
                sque.put((ni,nj))

while not pque.empty():
    i,j = pque.get()
    for k in range(4):
        ni = i+di[k]
        nj = j+dj[k]
        if ni >=0 and ni < h and nj >= 0 and nj < w:
            if (field[ni][nj] is not '#') and pdist[ni][nj] > pdist[i][j]+1 and pdist[i][j]+1 < sdist[ni][nj]:
                pdist[ni][nj] = pdist[i][j]+1
                pque.put((ni,nj))

if pdist[gi][gj] < 1000:
    print("Yes")
else:
    print("No")