You are given an H x W grid with black or white squares. A character named Kenus starts at (1, 1) and moves up, down, left, or right. The game ends when Kenus reaches (H, W) passing only white squares. Before the game, Snuke can change some white squares to black, except (1, 1) and (H, W). The score is the number of color changes. Find the maximum score or print -1 if Kenus can't reach (H, W). Constraints: H, W <= 50. Input format: H, W, followed by the grid. Output: maximum score or -1.

# Buggy version:
H, W = map(int, input().split())

s = ['#' * (W + 2)] + ['#' + input() + '#' for i in range(H)] + ['#' * (W + 2)]

# m : そこにたどり着くために必要な白マスの数
m = [[-1 for x in range(W+2)] for y in range(H+2)]
m[1][1] = 1


from collections import deque
qx = deque([1])
qy = deque([1])

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]


while len(qx) > 0:
    x, y = qx.popleft(), qy.popleft()
    for d in range(4):
        nx, ny = x + dx[d], y + dy[d]

        # 訪れたことがあるなら調べない
        if m[nx][ny] != -1: continue

        if s[ny][nx] == '.':
            qx.append(nx), qy.append(ny)
            m[ny][nx] = m[y][x] + 1

if m[H][W] == -1:
    print(-1)

else:
    print(sum([c.count('.') for c in s]) - m[H][W])



# Fixed version:
H, W = map(int, input().split())

s = ['#' * (W + 2)] + ['#' + input() + '#' for i in range(H)] + ['#' * (W + 2)]

# m : そこにたどり着くために必要な白マスの数
m = [[-1 for x in range(W+2)] for y in range(H+2)]
m[1][1] = 1


from collections import deque
qx = deque([1])
qy = deque([1])

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]


while len(qx) > 0:
    x, y = qx.popleft(), qy.popleft()
    for d in range(4):
        nx, ny = x + dx[d], y + dy[d]
        # 訪れたことがあるなら調べない
        if m[ny][nx] != -1: continue

        if s[ny][nx] == '.':
            qx.append(nx), qy.append(ny)
            m[ny][nx] = m[y][x] + 1

if m[H][W] == -1:
    print(-1)

else:
    print(sum([c.count('.') for c in s]) - m[H][W])

# Buggy version:
import sys
import queue

H,W = map(int,input().split())
white = 0
maze = [['#']*(W+2)]
for y in range(H):
	li = list(input())
	white += li.count('.')
	maze.append(['#'] + li + ['#'])
maze.append(['#']*(W+2))



def check(x,y,n):
	if 1 <= x < W+1 and 1 <= y < H+1:
		if x == W-1 and y == H-1:
			print (white - n - 1)
			sys.exit()
		elif maze[y][x] == '.':
			maze[y][x] = n
			q.put([x-1,y,n+1])
			q.put([x+1,y,n+1])
			q.put([x,y-1,n+1])
			q.put([x,y+1,n+1])
		else:
			return
	else:
		return

q = queue.Queue()
q.put([1,1,0])
while not q.empty():
	x,y,n = q.get()
	check(x,y,n)

print(-1)


# Fixed version:
import sys
import queue

H,W = map(int,input().split())
white = 0
maze = [['#']*(W+2)]
for y in range(H):
	li = list(input())
	white += li.count('.')
	maze.append(['#'] + li + ['#'])
maze.append(['#']*(W+2))



def check(x,y,n):
	if 1 <= x < W+1 and 1 <= y < H+1:
		if x == W and y == H:
			print (white - n - 1)
			sys.exit()
		elif maze[y][x] == '.':
			maze[y][x] = n
			q.put([x-1,y,n+1])
			q.put([x+1,y,n+1])
			q.put([x,y-1,n+1])
			q.put([x,y+1,n+1])
		else:
			return
	else:
		return

q = queue.Queue()
q.put([1,1,0])
while not q.empty():
	x,y,n = q.get()
	check(x,y,n)

print(-1)

# Buggy version:
from collections import deque
 
H,W  = map(int, input().split())
sx, sy = 1,1
gx, gy = W,H
count=-1
maze=[0]*(H+2)
maze[0] = list("#"*(W+2))
for i in range(1,H+1):
    maze[i] = list("#"+input()+"#")
    count+=maze[i].count('.')
maze[H+1] = list("#"*(W+2))
ans = [[-1 for i in range(W+2)] for j in range(H+2)]
q = deque()
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
q.append((sx, sy))
ans[sx][sy] = 0
 
while q:
    cx, cy = q.popleft()
    if cx == gx and cy == gy:
        print(count-ans[gx][gy])
        break
    for i in range(2):
        nx, ny = cx + dx[i], cy + dy[i]
        if ans[nx][ny] == -1 and maze[nx][ny] != "#":
            q.append((nx, ny))
            ans[nx][ny] = ans[cx][cy] + 1

# Fixed version:
from collections import deque
import sys

H,W  = map(int, input().split())
sx, sy = 1,1
gx, gy = W,H
count=-1
maze=[0]*(H+2)
maze[0] = list("#"*(W+2))
for i in range(1,H+1):
    maze[i] = list("#"+input()+"#")
    count+=maze[i].count('.')
maze[H+1] = list("#"*(W+2))
ans = [[-1 for i in range(W+2)] for j in range(H+2)]
q = deque()
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
q.append((sx, sy))
ans[sx][sy] = 0
 
while q:
    cx, cy = q.popleft()
    if cx == gx and cy == gy:
        print(count-ans[gy][gx])
        sys.exit()
    for i in range(4):
        nx, ny = cx + dx[i], cy + dy[i]
        if ans[ny][nx] == -1 and maze[ny][nx] != "#":
            q.append((nx, ny))
            ans[ny][nx] = ans[cy][cx] + 1
print(-1)

# Buggy version:
from collections import deque
H, W = map(int, input().split())
area = [['#']*(W+2)]
space = 0
for i in range(H):
    temp = ['#']+list(input())+['#']
    for t in temp:
        if t=='.': space+=1 
    area.append(temp)
area.append(['#']*(W+2))
move = ((1, 0), (-1, 0), (0, 1), (0, -1))

dq = deque([(1,1)])
dist = [[-1]*(W+2) for _ in range(H+2)]
dist[1][1] = 0

max_dist = 0
while dq:
    nowx, nowy = dq.popleft()
    if (nowx, nowy) == (W, H): break
    for dx, dy in move:
        nxtx, nxty = nowx+dx, nowy+dy
        if not 0<=nxtx<W+2 and 0<=nxty<H+2: continue
        if dist[nxty][nxtx]>=0 or area[nxty][nxtx]=='#': continue
        nxtd = dist[nowy][nowx]+1
        dist[nxty][nxtx] = nxtd
        max_dist = max(max_dist, nxtd)
        dq.append((nxtx, nxty))
print(space-(max_dist+1))

# Fixed version:
from collections import deque
H, W = map(int, input().split())
area = [['#']*(W+2)]
space = 0
for i in range(H):
    temp = ['#']+list(input())+['#']
    for t in temp:
        if t=='.': space+=1 
    area.append(temp)
area.append(['#']*(W+2))
move = ((1, 0), (-1, 0), (0, 1), (0, -1))

dq = deque([(1,1)])
dist = [[-1]*(W+2) for _ in range(H+2)]
dist[1][1] = 1

while dq:
    nowx, nowy = dq.popleft()
    # if (nowx, nowy) == (W, H): break
    for dx, dy in move:
        nxtx, nxty = nowx+dx, nowy+dy
        if not 0<=nxtx<W+2 and 0<=nxty<H+2: continue
        if dist[nxty][nxtx]>=0 or area[nxty][nxtx]=='#': continue
        dist[nxty][nxtx] = dist[nowy][nowx]+1
        dq.append((nxtx, nxty))
if dist[H][W]==-1: print(-1)
else: print(space-dist[H][W])

# Buggy version:
from collections import deque
MAX_VAL = 10 ** 9
H, W = map(int, input().split())



border_row = "#"*(W+2)
field = [border_row]
num_blacks = 0
for i in range(H):
    line = input()
    for c in line:
        if c == "#":
            num_blacks += 1
    field.append("#"+line+"#")
field.append(border_row)

cost = [[MAX_VAL]*(W+2) for _ in range(H+2)]

if field[1][1] == ".":
    cost[1][1] = 1
else:
    cost[1][1] = MAX_VAL

visited = [[False]*(W+2) for _ in range(H+2)] 
dxdy = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def bfs():
    q = deque()
    q.append((1, 1))
    while len(q):
        x, y = q.popleft()
        for dx, dy in dxdy:
            nx = x + dx
            ny = y + dy
            if field[ny][nx] == ".":
                cost[ny][nx] = min(cost[ny][nx], cost[y][x]+1)
                if not visited[ny][nx]:
                    q.append((nx, ny))
        visited[y][x] = True

bfs()
print(H*W-num_blacks-cost[H][W]) if cost[H][W] < MAX_VAL else print(-1)




# Fixed version:
from collections import deque
MAX_VAL = 10 ** 9
H, W = map(int, input().split())
 
 
 
border_row = "#"*(W+2)
field = [border_row]
num_blacks = 0
for i in range(H):
    line = input()
    num_blacks += line.count(".")
    field.append("#"+line+"#")
field.append(border_row)
 
cost = [[MAX_VAL]*(W+2) for _ in range(H+2)]
 
if field[1][1] == ".":
    cost[1][1] = 1
else:
    cost[1][1] = MAX_VAL
 
visited = [[False]*(W+2) for _ in range(H+2)]
dxdy = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def bfs():
    q = deque()
    q.append((1, 1))
    visited[1][1] = True
    while len(q):
        x, y = q.popleft()
        for dx, dy in dxdy:
            nx = x + dx
            ny = y + dy
            if field[ny][nx] == "." and not visited[ny][nx]:
                cost[ny][nx] = cost[y][x]+1
                visited[ny][nx] = True
                q.append((nx, ny))
    return 
bfs()
print(num_blacks - cost[H][W]) if cost[H][W] < MAX_VAL else print(-1)

# Buggy version:
from queue import Queue


def main():
    H, W = map(int, input().split())

    black = 0

    grid = [[-1 for _ in range(W + 2)]]
    for _ in range(H):
        line = input()
        black += line.count("#")
        grid.append([-1] + [-1 if char == "#" else -2 for char in line] + [-1])
    grid.append([-1 for _ in range(W + 2)])

    grid[1][1] = 0

    tosearch = Queue()
    tosearch.put((1, 1))

    movement = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    while not tosearch.empty():
        y, x = tosearch.get()

        if (y, x) == (H, W):
            break

        for move in movement:
            ny, nx = y + move[0], x + move[1]

            if grid[ny][nx] == -2:
                grid[ny][nx] = grid[y][x] + 1
                tosearch.put((ny, nx))

    print(H * W - (grid[H][W] + 1) - black)


if __name__ == '__main__':
    main()


# Fixed version:
from queue import Queue


def main():
    H, W = map(int, input().split())

    white = 0

    grid = [[-1 for _ in range(W + 2)]]
    for _ in range(H):
        line = input()
        white += line.count(".")
        grid.append([-1] + [-1 if char == "#" else -2 for char in line] + [-1])
    grid.append([-1 for _ in range(W + 2)])

    grid[1][1] = 0

    tosearch = Queue()
    tosearch.put((1, 1))

    movement = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    while not tosearch.empty():
        y, x = tosearch.get()

        if (y, x) == (H, W):
            print(white - (grid[H][W] + 1))
            break

        for move in movement:
            ny, nx = y + move[0], x + move[1]

            if grid[ny][nx] == -2:
                grid[ny][nx] = grid[y][x] + 1
                tosearch.put((ny, nx))
    else:
        print(-1)



if __name__ == '__main__':
    main()

# Buggy version:
a=['#'*(w+2)]
for i in range(h):
    b='#'+input()+'#'
    a.append(b)
a.append('#'*(w+2))
#print(a)

from collections import Counter

n=[(1,1)]
route={(1,1):0}
p=[[1,0],[0,1],[-1,0],[0,-1]]
count=1
while route.get((h,w),0)==0 and count != 10000:
    n2=[]
    #print(n,route)
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                if route.get(np,1000)>count:
                    route[np]=count
    n=n2
    #print(n,route)
    count+=1

    
a2=[]
for i in a:
    for j in range(len(i)):
        a2.append(i[j])
con=Counter(a2)


if count==10000:
    print('-1')
else:
    print(con['.']-route[(h,w)]-1)

# Fixed version:
h, w =map(int, input().split())

a=['#'*(w+2)]
for i in range(h):
    b='#'+input()+'#'
    a.append(b)
a.append('#'*(w+2))
#print(a)

from collections import Counter

n=[(1,1)]
route={(1,1):0}
p=[[1,0],[0,1],[-1,0],[0,-1]]
count=1
while route.get((h,w),0)==0 and count != 10000:
    n2=[]
    #print(n,route)
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                if route.get(np,1000)>count:
                    route[np]=count
    n=n2
    #print(n,route)
    count+=1

    
a2=[]
for i in a:
    for j in range(len(i)):
        a2.append(i[j])
con=Counter(a2)


if count==10000:
    print('-1')
else:
    print(con['.']-route[(h,w)]-1)

# Buggy version:
import queue

H, W = map(int, input().split())
s, count = [], 0
for _ in range(H):
    h = list(input())
    count += h.count('.')
    s.append(['#'] + h + ['#'])
s = [['#'] * (W+2)] + s + [['#'] * (W+2)]
around = [[-1, 0], [0, -1], [1, 0], [0, 1]]

ans, que, already = count + 1, queue.Queue(), set([1 + H])
que.put([1, 1, 1])
while not que.empty():
    q = que.get()
    if q[0] == W and q[1] == H:
        ans = q[2]
        Goal = True
        break
    elif q[0] + H*q[1] not in already:
        for a in around:
            nextx, nexty = q[0] + a[0], q[1] + a[1]
            if s[nexty][nextx] == '.':
                que.put([nextx, nexty, q[2] + 1])
                already.add(nextx + H*nexty)

print(count - ans)

# Fixed version:
import queue

H, W = map(int, input().split())
s, count = [], 0
for _ in range(H):
    h = list(input())
    count += h.count('.')
    s.append(['#'] + h + ['#'])
s = [['#'] * (W+2)] + s + [['#'] * (W+2)]
around = [[-1, 0], [0, -1], [1, 0], [0, 1]]

ans, que, already = count + 1, queue.Queue(), set([1 + W])
que.put([1, 1, 1])
while not que.empty():
    q = que.get()
    if q[0] == W and q[1] == H:
        ans = q[2]
        break
    else:
        for a in around:
            nextx, nexty = q[0] + a[0], q[1] + a[1]
            if nextx + W*nexty not in already and s[nexty][nextx] == '.':
                que.put([nextx, nexty, q[2] + 1])
                already.add(nextx + W*nexty)

print(count - ans)

# Buggy version:
from collections import deque

import numpy as np
import sys
#input = sys.stdin.readline

sys.setrecursionlimit(5000)

def bfs(point, field, target, H, W):
    visited = [[-1 for _ in range(W+2)] for _ in range(H+2)]
    visited[point[0]][point[1]] = 1
    que = deque()
    que.append(point)

    while True:
        v = que.popleft()
        depth = visited[v[0]][v[1]]
        for a in [(v[0]-1, v[1]), (v[0]+1, v[1]), (v[0], v[1]-1), (v[0], v[1]+1)]:
            if field[a[0]][a[1]] == 0 and visited[a[0]][a[1]] == -1:
                visited[a[0]][a[1]] = 1 + depth
                if a == target:
                    print(visited)
                    return visited[a[0]][a[1]]
                else:
                    que.append(a)
        if len(que) == 0:
            return 0

H, W = list(map(int, input().split()))
target = (H, W)
field = [[-1] * (W+2)]
number_of_whites = 0
for _ in range(H):
    s = input()
    number_of_whites += s.count('.')
    field.append([-1] + [0 if c=='.' else -1 for c in s] + [-1])
field += [[-1] * (W+2)]

shortest_path = bfs((1, 1), field, target, H, W)
if shortest_path > 0:
    print(number_of_whites - shortest_path)
else:
    print(-1)

# Fixed version:
from collections import deque

import numpy as np
import sys
#input = sys.stdin.readline

sys.setrecursionlimit(5000)

def bfs(point, field, target, H, W):
    visited = [[-1 for _ in range(W+2)] for _ in range(H+2)]
    visited[point[0]][point[1]] = 1
    que = deque()
    que.append(point)

    while True:
        v = que.popleft()
        depth = visited[v[0]][v[1]]
        for a in [(v[0]-1, v[1]), (v[0]+1, v[1]), (v[0], v[1]-1), (v[0], v[1]+1)]:
            if field[a[0]][a[1]] == 0 and visited[a[0]][a[1]] == -1:
                visited[a[0]][a[1]] = 1 + depth
                if a == target:
                    return visited[a[0]][a[1]]
                else:
                    que.append(a)
        if len(que) == 0:
            return 0

H, W = list(map(int, input().split()))
target = (H, W)
field = [[-1] * (W+2)]
number_of_whites = 0
for _ in range(H):
    s = input()
    number_of_whites += s.count('.')
    field.append([-1] + [0 if c=='.' else -1 for c in s] + [-1])
field += [[-1] * (W+2)]

shortest_path = bfs((1, 1), field, target, H, W)
if shortest_path > 0:
    print(number_of_whites - shortest_path)
else:
    print(-1)

# Buggy version:
H, W = list(map(int, input().split()))
M = [[-1]*(W+2)]
ans = 0
for _ in range(H):
  s = input()
  ans += s.count('.')
  M.append([-1]+[0 if c=='.' else -1 for c in s]+[-1])
  M += [[-1]*(W+2)]

  queue = [(1,1)]
  M[1][1] = 1
  dr = [(+1,0),(-1,0),(0,+1),(0,-1)]
  turn = 1
  while len(queue)>0:
    turn += 1
    queue_new = []
    for qx, qy in queue:
      for dx, dy in dr:
        x, y = qx+dx, qy+dy
        if M[y][x]==0:
          M[y][x] = turn
          queue_new.append((x,y))
          queue = queue_new

          print(ans-M[H][W] if M[H][W]>0 else -1)

# Fixed version:
H, W = list(map(int, input().split()))
M = [[-1]*(W+2)]
ans = 0
for _ in range(H):
    s = input()
    ans += s.count('.')
    M.append([-1]+[0 if c=='.' else -1 for c in s]+[-1])
M += [[-1]*(W+2)]

queue = [(1,1)]
M[1][1] = 1
dr = [(+1,0),(-1,0),(0,+1),(0,-1)]
turn = 1
while len(queue)>0:
    turn += 1
    queue_new = []
    for qx, qy in queue:
        for dx, dy in dr:
            x, y = qx+dx, qy+dy
            if M[y][x]==0:
                M[y][x] = turn
                queue_new.append((x,y))
    queue = queue_new

print(ans-M[H][W] if M[H][W]>0 else -1)

# Buggy version:
from collections import deque

H, W = map(int, input().split())
S = []
white_num = 0
for _ in range(H):
    s = input()
    white_num += s.count('.')
    S.append(s)

C = [[-1]*W for _ in range(H)]
C[0][0] = 0
q = deque()
q.append((0, 0, 0))
xlist = [0, 0, 1, -1]
ylist = [1, -1, 0, 0]
while len(q) > 0:
    x, y, c = q.popleft()
    C[x][y] = c + 1
    for i in range(4):
        mx = x + xlist[i]
        my = y + ylist[i]
        if mx < 0 or my < 0 or mx >= H or my >= W or S[mx][my] == '#' or C[mx][my] >= 0:
            continue
        q.append((mx, my, c+1))
if C[H-1][W-1] == -1:
    print(-1)
else:
    print(white_num - C[H-1][W-1])


# Fixed version:
from collections import deque

H, W = map(int, input().split())
S = ['#'*(W+2)]
white_num = 0
for _ in range(H):
    s = input()
    white_num += s.count('.')
    S.append('#'+s+'#')
S.append('#'*(W+2))

C = [[-1]*(W+2) for _ in range(H+2)]
C[1][1] = 1
q = deque()
q.append((1, 1))
xlist = [0, 0, 1, -1]
ylist = [1, -1, 0, 0]
while len(q) > 0:
    x, y = q.popleft()
    for i in range(4):
        mx = x + xlist[i]
        my = y + ylist[i]
        if S[mx][my] == '#' or C[mx][my] >= 0:
            continue
        C[mx][my] = C[x][y] + 1
        q.append((mx, my))
if C[H][W] == -1:
    print(-1)
else:
    print(white_num - C[H][W])