Problem:
 Score: 400 points    Problem statement  We have an H \times W grid whose squares are painted black or white. The square at the i -th row from the top and the j -th column from the left is denoted as (i, j) . Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1) . The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares. Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W) . Also, changes of color must all be carried out before the beginning of the game. When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.  The color of the squares are given to you as characters s_{i, j} . If square (i, j) is initially painted by white, s_{i, j} is . ; if square (i, j) is initially painted by black, s_{i, j} is # .      Constraints   H is an integer between 2 and 50 (inclusive).  W is an integer between 2 and 50 (inclusive).  s_{i, j} is . or #  (1 \leq i \leq H, 1 \leq j \leq W) .  s_{1, 1} and s_{H, W} are . .         Input  Input is given from Standard Input in the following format:  H  W  s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}  s_{2, 1}s_{2, 2}s_{2, 3} ... s_{2, W}  :  :  s_{H, 1}s_{H, 2}s_{H, 3} ... s_{H, W}       Output  Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.        Sample Input 1 3 3
..#
#..
...      Sample Output 1 2  The score 2 can be achieved by changing the color of squares as follows:        Sample Input 2 10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................      Sample Output 2 209

Solution (Python):
from collections import deque 
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
moves = ((1, 0), (0, 1), (0, -1), (-1, 0))
dist = [[-1]*W for _ in range(H)] 

def bfs():
    q = deque([[0, 0]])
    visited = [[0]*W for _ in range(H)]
    visited[0][0] = 1
    dist[0][0] = 0

    while q:
        y, x = q.popleft()
        for dy, dx in moves:
            ny = y + dy 
            nx = x + dx 
            if 0 <= ny < H and 0 <= nx < W and visited[ny][nx] == 0 and s[ny][nx] == '.':
                visited[ny][nx] = 1 
                dist[ny][nx] = dist[y][x] + 1 
                q += [[ny, nx]]

bfs()
ans = H * W
if dist[H-1][W-1] == -1:
    print(-1)
    exit()
for i in range(H):
    for j in range(W):
        if s[i][j] =='
            ans -= 1 

print(ans-dist[H-1][W-1]-1)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 6)

H,W=map(int, input().split())  
S=[]
initB=0
for i in range(H):
    s=[0 if j=='.' else 1 if j=='
    initB+=sum(s)
    S.append(s)

from collections import deque
que=deque([(0,0)])
di=[-1,1,0,0]
dj=[0,0,-1,1]
S[0][0]=1
while que:
    h,w=que.popleft()
    for i,j in zip(di,dj):
        if 0<=h+i<H and 0<=w+j<W and S[h+i][w+j]==0:
            S[h+i][w+j]= S[h][w]+1
            que.append((h+i,w+j))

if S[H-1][W-1]<2:
    print(-1)
else:
    print(H*W-S[H-1][W-1]-initB)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
S = []
for _ in range(h):
    s = str(input())
    S.append(s)

deque = deque()
deque.append([0,0])
Visited=[[-1 for _ in range(w)] for _ in range(h)]
Visited[0][0] = 0

while deque:
    now = deque.popleft()
    x_now = now[0]
    y_now = now[1]

    Cands = []
    For_cands = [-1,0,1]
    for i in For_cands:
        for j in For_cands:
            if i == j or i == j*-1:
                continue
            if x_now + i < w and x_now +i >=0 and y_now +j < h and y_now + j >=0:
                if S[y_now+j][x_now+i] == '.':
                    Cands.append([x_now+i, y_now+j])
    for cands in Cands:
        if Visited[cands[1]][cands[0]] != -1:
            continue
        deque.append(cands)
        Visited[cands[1]][cands[0]] = Visited[y_now][x_now] + 1

goal_dist = Visited[h-1][w-1]

white = 0
for i in range(h):
    white += S[i].count('.')

ans = white - goal_dist -1
if goal_dist == -1:
    ans = -1
print(ans)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
S = []
for _ in range(h):
    s = str(input())
    S.append(s)

deque = deque()
deque.append([0,0])
Visited=[[-1 for _ in range(w)] for _ in range(h)]
Visited[0][0] = 0

while deque:
    now = deque.popleft()
    x_now = now[0]
    y_now = now[1]

    Cands = []
    For_cands = [-1,0,1]
    for i in For_cands:
        for j in For_cands:
            if i == j or i == j*-1:
                continue
            if x_now + i < w and x_now +i >=0 and y_now +j < h and y_now + j >=0:
                if S[y_now+j][x_now+i] == '.':
                    Cands.append([x_now+i, y_now+j])
    for cands in Cands:
        if Visited[cands[1]][cands[0]] != -1:
            continue
        deque.append(cands)
        Visited[cands[1]][cands[0]] = Visited[y_now][x_now] + 1

goal_dist = Visited[h-1][w-1]

white = 0
for i in range(h):
    white += S[i].count('.')

ans = white - goal_dist -1
if goal_dist == -1:
    ans = -1
print(ans)

Solution (Python):
import queue
H, W = map(int, input().split())
S = [input() for _ in range(H)]
white = sum(map(lambda x: x.count("."), S))
dxs = (0,1,0,-1)
dys = (1,0,-1,0)

goal = False
reached = [[None for _ in range(W)] for _ in range(H)]
reached[0][0] = 0

q = queue.Queue()
q.put((0,0))
while not q.empty():
    now = q.get()
    now_val = reached[now[1]][now[0]]
    
    for dx,dy in zip(dxs,dys):
        x = now[0] + dx
        y = now[1] + dy
        
        if x < 0 or y < 0 or x >= W or y >= H: continue
        
        if reached[y][x] is not None: continue
        
        if S[y][x] == "
            reached[y][x] = -1
            continue
        
        else:
            if x == W-1 and y == H-1: goal = True
            reached[y][x] = now_val + 1
            q.put((x, y))

print((white - reached[H-1][W-1] -1) if goal else -1)

Solution (Python):
from collections import deque

h, w = map(int, input().split())

l = [input() for i in range(h)]
memo = [[-1]*w for i in range(h)]

black_cells = deque()
memo[0][0] = 0
black_cells.append((0, 0))
for i in range(h):
    for j in range(w):
        if l[i][j] == "
            memo[i][j] = -2

count = 0
while black_cells:
    nh, nw = black_cells.popleft()
    count = memo[nh][nw]
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_nh = nh + dy
        new_nw = nw + dx
        if new_nh < 0 or h <= new_nh or new_nw < 0 or w <= new_nw:
            continue
        if memo[new_nh][new_nw] == -1:
            memo[new_nh][new_nw] = count + 1
            black_cells.append((new_nh, new_nw))
        if new_nh == h-1 and new_nw == w-1:
            count += 1
            break
    if new_nh == h-1 and new_nw == w-1:
        break

if new_nh == h-1 and new_nw == w-1:
    sc = 0
    for i in l:
        sc += i.count("
    print(h*w-sc - count - 1)
else:
    print(-1)

Solution (Python):
from collections import deque
def mbfs(S,H,W,sh,sw):
    dist=[[-1]*W for i in range(H)]
    dist[sh][sw]=0

    d=deque()
    d.append([sh,sw])
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    while(len(d)!=0):
        h=d[0][0]
        w=d[0][1]
        d.popleft()
        for dir in range(4):
            nh=h+dx[dir]
            nw=w+dy[dir]
            if(nh>H-1 or nh<0 or nw>W-1 or nw<0):
                continue
            if(dist[nh][nw]!=-1 or S[nh][nw]=='
                continue
            dist[nh][nw]=dist[h][w]+1
            S[nh][nw]=='
            d.append([nh,nw])
    return dist

H,W=map(int,input().split())
S=[]
for i in range(H):
    S.append(input())
cnt=0
for i in range(H):
    for j in range(W):
        if(S[i][j]=='
            cnt+=1


li=mbfs(S,H,W,0,0)
if(li[H-1][W-1]!=-1):
    print(H*W-cnt-(li[H-1][W-1]+1))
else:
    print(-1)

Solution (Python):
H,W = map(int,input().split())
S = [input() for i in range(H)]
T = [[False]*W for i in range(H)]
Q = [(1,0,0)]
cnt = 0
while Q:
    q = Q.pop(0)
    if min(q)<0 or q[1]>=H or q[2]>=W:continue
    if S[q[1]][q[2]]=="
    if q[1]==H-1 and q[2]==W-1:
        cnt = q[0]
        break
    T[q[1]][q[2]]=True
    Q.append((q[0]+1,q[1]+1,q[2]))
    Q.append((q[0]+1,q[1]-1,q[2]))
    Q.append((q[0]+1,q[1],q[2]+1))
    Q.append((q[0]+1,q[1],q[2]-1))
ans = 0
for s in S:ans+=s.count(".")
print(ans-cnt if cnt else -1)

Solution (Python):
h,w=map(int,input().split())
a=['*'*(w+2)]+['*'+input()+'*' for _ in range(h)]+['*'*(w+2)]
s=0
for i in range(1,h+1):
  s+=a[i].count('.')
from collections import deque
d=deque()
d.append([1,1])
c=[[10000]*w for _ in range(h)]
c[0][0]=1
di=[[0,1],[1,0],[-1,0],[0,-1]]
while d:
  g=d.popleft()
  for i in di:
    x=g[0]+i[0]
    y=g[1]+i[1]
    if a[x][y]=='.':
      if c[x-1][y-1]==10000:
        d.append([x,y])
        c[x-1][y-1]=c[g[0]-1][g[1]-1]+1
if c[h-1][w-1]==10000:
  print(-1)
else:
  print(s-c[h-1][w-1])

Solution (Python):
import sys
from collections import deque

H, W = map(int, sys.stdin.readline().strip().split())
grid = [[]] * H
movable = 0
for i in range(H):
    grid[i] = list(sys.stdin.readline().strip())
    for j in grid[i]:
        if j == ".":
            movable += 1


q = deque()
q.append((0, 0, 0))
visited = set()
goal = False

while q:
    x, y, c = q.popleft()
    for dx, dy in ((-1, 0), (0, 1), (1, 0), (0, -1)):
        if 0 <= x+dx < W and 0 <= y+dy < H:
            if x+dx == W-1 and y+dy == H-1:
                goal = True
                c += 1
                break
            elif grid[y+dy][x+dx] == "." and (x+dx, y+dy) not in visited:
                q.append((x+dx, y+dy, c+1))
                visited.add((x+dx, y+dy))

    if goal:
        break

if goal:
    print(movable - (c + 1))
else:
    print(-1)

Solution (Python):
import sys
import queue
input = sys.stdin.readline

h,w = map(int,input().split())
maze = [input() for _ in range(h)]
black = sum(x.count('
count = [[0 for _ in range(w)] for _ in range(h)]

count[0][0] = 1
q = queue.Queue()
q.put((0,0))

while not q.empty():
    y, x = q.get()
    for dy, dx in ((1,0),(0,1),(-1,0),(0,-1)):
        ny = y + dy
        nx = x + dx
        if 0 <= ny < h and 0 <= nx < w:
            if maze[ny][nx] == '.' and count[ny][nx] == 0:
                count[ny][nx] = count[y][x] + 1
                q.put((ny,nx))
if count[h-1][w-1] == 0:
    print (-1)
else:
    print (h*w - black - count[h-1][w-1])

Solution (Python):
from collections import deque
from collections import defaultdict
import sys

H,W=map(int,input().split())
maze=[[0]*W for _ in range(H)]
b=0                  
for i in range(H):
  a=str(input())
  for j in range(W):
    if a[j]=='
      b+=1
    maze[i][j]=a[j]
def BFS(maze,s,g):
  que=deque()
  sy,sx=s[0],s[1]
  gy,gx=g[0],g[1]
  que.append([sx,sy])
  dist=[[0]*W for _ in range(H)]
  seen=[]
  seen.append([sx,sy])   
  Next=[[-1,0],[1,0],[0,1],[0,-1]]
  while len(que)!=0:
    l=que.popleft()
    for n in Next:
      x,y=l[0]+n[0],l[1]+n[1]
      if (x<0 or x>=W or y<0 or y>=H) or maze[y][x]=='
        pass
      else:
        if [x,y] not in seen:
          seen.append([x,y])
          que.append([x,y])
          dist[y][x]=dist[l[1]][l[0]]+1
  return dist[gy][gx]

d=BFS(maze,[0,0],[H-1,W-1])
if d==0:
  print(-1)   
else:
  print(H*W-(d+1)-b)

Solution (Python):
from collections import deque


h,w=map(int,input().split())
s=[list(input()) for i in range(h)]
dist=[[0 for i in range(w)] for j in range(h)]
que=deque([])
que.append([0,0])
dyx=[[1,0],[0,-1],[-1,0],[0,1]]
ndot=0
for i in range(h):
  for j in range(w):
    if s[i][j]==".":
      ndot+=1
s[0][0]="

while que:
  y,x=que.popleft()
  for dy,dx in dyx:
    nx=x+dx
    ny=y+dy
    if (nx<0 or nx>w-1 or ny<0 or ny>h-1):
      continue
    if s[ny][nx]==".":
      dist[ny][nx]=dist[y][x]+1
      que.append([ny,nx])
      s[ny][nx]="

ans=ndot-dist[h-1][w-1]-1
if dist[h-1][w-1]==0:
  ans=-1
print(ans)

Solution (Python):



h, w = map(int, input().split())
table = [[] for _ in range(h)]
for y in range(h):
    table[y] = list(input())

my_table = [[-1 for _ in range(w)] for _ in range(h)]
my_table[0][0] = 0
yo = [(0, 0)]
steps = [0, -1, 0, 1, 0]
while len(yo) > 0:
    p = yo[0]
    yo = yo[1:]
    for i in range(4):
        next_x, next_y = steps[i + 1] + p[1], steps[i] + p[0]
        if next_x < 0 or w <= next_x or next_y < 0 or h <= next_y:
            continue
        if table[next_y][next_x] == "
            continue
        if my_table[next_y][next_x] >= 0:
            continue
        my_table[next_y][next_x] = my_table[p[0]][p[1]] + 1
        yo.append((next_y, next_x))
if my_table[h - 1][w - 1] == -1:
  print(-1)
  exit()
  

restore_table = [["o" for _ in range(w)] for _ in range(h)]
restore_table[h - 1][w - 1] = "x"
now = my_table[h - 1][w - 1]
cur = (h - 1, w - 1)
while now != 0:
    for i in range(4):
        next_y, next_x = steps[i] + cur[0], steps[i + 1] + cur[1]
        if next_x < 0 or w <= next_x or next_y < 0 or h < next_y:
            continue
        if my_table[next_y][next_x] == now - 1:
            restore_table[next_y][next_x] = "x"
            cur = (next_y, next_x)
            now -= 1
            break


ans = 0
for y in range(h):
    for x in range(w):
        if restore_table[y][x] == "o" and table[y][x] == ".":
            ans += 1
print(ans)

Solution (Python):


from collections import deque

h, w = map(int, input().split())
table =[]
default_dot = 0
for _ in range(h):
  line = list(input())
  default_dot+=line.count(".")
  table.append(line)

default_dot-=2  
table[0][0] = 0

cur = [0, 0]   
queue = deque()
queue.append(cur)
steps = [0, 1, 0, -1, 0]

minimum_step = 0

while True:
  if len(queue)==0:
    print(-1)
    exit()
  now = queue.popleft()
  if now[0] == w-1 and now[1] == h-1:
    minimum_step = table[now[1]][now[0]]-1
    break
  for i in range(4):
    next_y, next_x = now[1]+steps[i], now[0]+steps[i+1]
    if 0<=next_y<h and 0<=next_x<w and table[next_y][next_x] == ".":
      table[next_y][next_x] = table[now[1]][now[0]]+1
      queue.append([next_x, next_y])


print(default_dot-minimum_step)

Solution (Python):
from collections import deque
INFTY = 10**4
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
cnt = 0
for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            cnt += 1
dist = [[INFTY for _ in range(W)] for _ in range(H)]
hist = [[0 for _ in range(W)] for _ in range(H)]
dist[0][0] = 0
que = deque([(0,0)])
while que:
    i,j = que.popleft()
    if j+1<W and hist[i][j+1]==0 and S[i][j+1]==".":
        dist[i][j+1] = dist[i][j]+1
        que.append((i,j+1))
        hist[i][j+1] = 1
    if i-1>=0 and hist[i-1][j]==0 and S[i-1][j]==".":
        dist[i-1][j] = dist[i][j]+1
        que.append((i-1,j))
        hist[i-1][j] = 1
    if j-1>=0 and hist[i][j-1]==0 and S[i][j-1]==".":
        dist[i][j-1] = dist[i][j]+1
        que.append((i,j-1))
        hist[i][j-1] = 1
    if i+1<H and hist[i+1][j]==0 and S[i+1][j]==".":
        dist[i+1][j] = dist[i][j]+1
        que.append((i+1,j))
        hist[i+1][j] = 1
if dist[H-1][W-1]==INFTY:
    print(-1)
else:
    print(cnt-2-dist[H-1][W-1]+1)

Solution (Python):
def ABC106_B():
    def make_divisors(n):
        divisors = []
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                divisors.append(i)
                if i != n // i:
                    divisors.append(n // i)
        
        return divisors
    N = I()
    ans = 0
    for i in range((N+1)//2):
        cur = i*2+1
        if len(make_divisors(cur))==8:
            ans += 1
    print(ans)
    return

def ABC122_B():
    S = SI()
    ans = 0
    cur = 0
    d = {"A","C","G","T"}
    for s in S:
        if s in d:
            cur += 1
        else:
            ans = max(ans,cur)
            cur = 0
    ans = max(ans,cur)
    print(ans)
    return

def paken2019_C():
    N, M = LI()
    A = [LI()for _ in range(N)]
    T = [i for i in range(M)]
    ans = 0
    for t1,t2 in itertools.permutations(T,2):
        cur = 0
        for i in range(N):
            cur += max(A[i][t1],A[i][t2])
        ans = max(ans,cur)
    print(ans)
    return

def ABC95_C():
    A, B, C, X, Y = LI()
    if A+B<=C*2:
        ans = A*X+B*Y
    else:
        if X>Y:
            ans = Y*C*2 + min(A,C*2)*(X-Y)
        else:
            ans = X*C*2 + min(B,C*2)*(Y-X)
    print(ans)
    return

def SMTB_D():
    def flag(n,s):
        for l in range(n,N):
            if S[l]==str(s):
                return l
        return N
    N = I()
    S = SI()
    ans = 0
    for i in range(10):
        L1 = flag(0,i)
        for j in range(10):
            L2 = flag(L1+1,j)
            for k in range(10):
                L3 = flag(L2+1,k)
                if L3<N:
                    ans += 1
                    
    print(ans)
    return

def JOI2007_3():
    N = I()
    V = [LI() for _ in range(N)]
    D = set()
    for vx,vy in V:
        D.add((vx,vy))
    ans = 0
    for i in range(N):
        a1, b1 = V[i]
        for j in range(i+1,N):
            a2, b2 = V[j]
            va, vb = a2 - a1, b2 - b1
            if (a1 + vb, b1 - va) in D and (a2 + vb, b2 - va) in D:
                ans = max(ans, va ** 2 + vb ** 2)
            if (a1 - vb, b1 + va) in D and (a2 - vb, b2 + va) in D:
                ans = max(ans, va ** 2 + vb ** 2)
    print(ans)
    return
"""
10
9 4
4 3
1 1
4 2
2 4
5 8
4 0
5 3
0 5
5 2
"""

def square869120Contest():
    def length(a,b,x,y):
        if x>y:
            x,y = y,x
        rep = 0
        if a<x:
            rep += (x-a)*2
        if y<b:
            rep += (b-y)*2
        rep += (y-x)
        return rep
    N = I()
    AB = [LI()for _ in range(N)]
    ans = inf
    for i in range(N):
        s = AB[i][0]
        for j in range(N):
            g = AB[j][1]
            cur = 0
            for k in range(N):
                cur += length(AB[k][0],AB[k][1],s,g)
            ans = min(ans,cur)
    print(ans)
    return

def JOI7_D():
    M = I()
    S = [LI()for _ in range(M)]
    Ss = [(0,0)]
    curx,cury = S[0]
    for sx,sy in S[1:]:
        Ss.append((sx-curx,sy-cury))
        curx = sx; cury = sy
    
    N = I()
    X = [LI()for _ in range(N)]
    D = set()
    for i in range(N):
        cur = (X[i][0],X[i][1])
        D.add(cur)
    for i in range(N):
        flag = True
        curx, cury = X[i]
        for k in range(M):
            curx += Ss[k][0]
            cury += Ss[k][1]
            
            if not (curx, cury) in D:
                flag = False
                break
        if flag:
            
            ansx = X[i][0] - S[0][0]
            ansy = X[i][1] - S[0][1]
            print(ansx,ansy)
            return
    return

def ABC128_C():
    N, M = LI()
    S = [[]for _ in range(N)]
    for i in range(M):
        s = LI()
        for j in s[1:]:
            S[j-1].append(i)
    P = LI()
    
    loop = 2**N
    ans = 0
    for i in range(loop):
        p = [0]*M
        cur = []
        for j in range(N):
            if (1<<j)&i==(1<<j):
                cur.append(j)
        for k in cur:
            for l in S[k]:
                p[l] += 1
        flag = True
        for j in range(M):
            if p[j]%2!=P[j]:
                flag = False
        if flag:
            ans += 1
    print(ans)
    return

def ABC2_D():
    N, M = LI()
    V = set()
    for _ in range(M):
        x,y = LI()
        V.add((x,y))
    loop = 2**N
    ans = 0
    
    for i in range(loop):
        cur = []
        for j in range(N):
            if (1<<j)&i==(1<<j):
                cur.append(j+1)
        flag = True
        for k1,k2 in itertools.permutations(cur,2):
            if not ((k1,k2) in V or (k2,k1) in V):
                flag = False
                break
        if flag:
            ans = max(ans,len(cur))
    print(ans)
    return

def JOI7_E():
    R, C = LI()
    A = [LI()for _ in range(R)]
    loop = 2**R
    ans = 0
    for i in range(loop):
        rev = set()
        for j in range(R):
            if (1<<j)&i==(1<<j):
                rev.add(j)
        cur = 0
        for j in range(C):
            s = 0
            for k in range(R):
                if k in rev and A[k][j]==0:
                    s += 1
                elif (not k in rev) and A[k][j]==1:
                    s += 1
            cur += max(s,R-s)
        ans = max(ans,cur)
    print(ans)
    return

def square869120Contest4_B():
    N, K = LI()
    A = LI()
    ans = inf
    loop = 2**(N-1)
    for i in range(loop):
        look = set()
        for j in range(N-1):
            if (1<<j)&i==(1<<j):
                look.add(j+1)
        if len(look)<K-1:
            continue
        high = A[0]
        cur = 0
        flag = True
        for j in range(1,N):
            if not (j in look):
                if A[j]>high:
                    flag = False
                    break
            else:
                if high >= A[j]:
                    cur += (high - A[j] + 1)
                    high += 1
                else:
                    high = A[j]
        
        if not flag:
            continue
        ans = min(ans,cur)
    print(ans)
    return

def ABC145_C():
    N = I()
    X = [LI()for _ in range(N)]
    ans = 0
    c = 0
    for x in itertools.permutations(X):
        cur = 0
        c += 1
        for i in range(N-1):
            cur += ((x[i+1][0]-x[i][0])**2 + (x[i+1][1]-x[i][1])**2)**0.5
        ans += cur
    ans /= c
    print(ans)
    return

def ABC150_C():
    N = I()
    T = [i+1 for i in range(N)]
    P = LI()
    Q = LI()
    for i,t in enumerate(itertools.permutations(T)):
        flag_P = True
        flag_Q = True
        for j in range(N):
            if t[j]!=P[j]:
                flag_P = False
            if t[j]!=Q[j]:
                flag_Q = False
        if flag_P:
            a = i
        if flag_Q:
            b = i
    ans = abs(a-b)
    print(ans)
    return

def JOI2009_2():
    d = I()
    N = I()
    M = I()
    D = [I()for _ in range(N-1)]
    K = [I()for _ in range(M)]
    D.append(0)
    D.sort()
    D.append(d)
    ans = 0
    for i in range(M):
        cur = bisect.bisect_right(D,K[i])
        ans += min(K[i]-D[cur-1],D[cur]-K[i])
    print(ans)
    return
"""
20 
4 
4 
12
8 
16 
7 
7 
11 
8
"""

def ARC37_C():
    N, K = LI()
    A = LI()
    B = LI()
    B.sort()
    l = 0; r = inf
    while(r-l>1):
        cur = 0
        now = (l+r)//2
        for a in A:
            if a==0:
                cur += N
            else:
                cur += bisect.bisect_right(B,now//a)
        if cur<K:
            l =now
        else:
            r = now
    ans = r
    print(ans)
    return

def ABC27_D():
    def judge(h):
        D = [0]*N
        for i in range(N):
            if h<H[i][0]:
                return False
            cur = (h-H[i][0])//H[i][1]
            if cur>=N:
                cur = N-1
            D[cur] += 1
        s = 0
        
        for i in range(N):
            s += D[i]
            if s>i+1:
                return False
        return True
    N = I()
    H = [LI()for _ in range(N)]
    l = 0; r = inf
    while(r-l>1):
        now = (l+r)//2
        if judge(now):
            r = now
        else:
            l = now
    ans = r
    print(ans)
    return

def JOI2008_3():
    N, M = LI()
    P = [I()for _ in range(N)]
    P_2 = set()
    for i in range(N+1):
        if i==N:
            p1 = 0
        else:
            p1 = P[i]
        for j in range(N+1):
            if j==N:
                p2 = p1
            else:
                p2 = p1+P[j]
            P_2.add(p2)
    P_2 = list(P_2)
    P_2.sort()
    ans = 0
    for p2 in P_2:
        if M<p2:
            continue
        cur = P_2[bisect.bisect_right(P_2,M-p2)-1]+p2
        ans = max(ans,cur)
    print(ans)
    return
"""
3 21 
16 
11 
2
"""

def ABC138_D():
    def bfs(n,edges,s,C):
        W = [-1]*n
        que = deque()
        que.append(s)
        W[s] = C[s]
        rep = W[s]
        while(que):
            now = que.pop()
            nowW = W[now]
            for i in edges[now]:
                if W[i]==-1:
                    que.append(i)
                    W[i] = nowW + C[i]
                    rep += W[i]
        return W
    N, Q = LI()
    V = [[]for _ in range(N)]
    for _ in range(N-1):
        a,b = LI()
        a -= 1; b -= 1
        V[a].append(b)
        V[b].append(a)
    C = [0]*N
    for _ in range(Q):
        p,x = LI()
        C[p-1] += x
    ans = bfs(N,V,0,C)
    print(" ".join(map(str,ans)))
    return

def JOI8_D():
    def dfs(s, n ,rep):
        y, x = s[0],s[1]
        S[y][x] = 0
        if rep < n:
            rep = n
        for i in range(4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
            if ny>=H or ny<0 or nx>=W or nx<0:
                continue
            if S[ny][nx]==1:
                rep = dfs([ny,nx], n + 1, rep)
                
        S[y][x] = 1
        
        return rep
    W = I()
    H = I()
    S = [LI()for _ in range(H)]
    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j]==0:
                continue
            ans = max(ans,dfs((i,j),1,1))
    print(ans)
    return
"""
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
""" 

def ABC7_C():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]
        def bfsg():
            queue = deque()
            queue.append(s)
            distance[s[0]][s[1]] = 0
            while len(queue):
                y, x = queue.popleft()
                for i in range(4):
                    nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                    if (0 <= nx < w and 0 <= ny < h and maze[ny][nx] != '
                        if distance[ny][nx] <= distance[y][x] + 1:
                            continue
                        queue.append((ny, nx))
                        distance[ny][nx] = distance[y][x] + 1
            return distance

        return bfsg()
    h, w = LI()
    Sy,Sx = LI()
    Gy,Gx = LI()
    C = [SI()for _ in range(h)]
    L = bfs_grid(h,w,[Sy-1,Sx-1],C)
    
    ans = L[Gy-1][Gx-1]
    print(ans)
    return

def JOI10_E():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]
        def bfsg():
            queue = deque()
            queue.append(s)
            distance[s[0]][s[1]] = 0
            while len(queue):
                y, x = queue.popleft()
                for i in range(4):
                    nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                    if (0 <= nx < w and 0 <= ny < h and maze[ny][nx] != 'X'):
                        if distance[ny][nx] <= distance[y][x] + 1:
                            continue
                        queue.append((ny, nx))
                        distance[ny][nx] = distance[y][x] + 1
            return distance

        return bfsg()
    H, W, N = LI()
    S = [SI()for _ in range(H)]
    G = defaultdict(set)
    for i in range(H):
        for j in range(W):
            G[S[i][j]] = (i,j)
    ans = 0
    for i in range(N):
        if i==0:
            g = G["1"]
            L = bfs_grid(H,W,G["S"],S)
            ans += L[g[0]][g[1]]
        else:
            g = G[str(i+1)]
            L = bfs_grid(H, W, G[str(i)], S)
            ans += L[g[0]][g[1]]
    print(ans)
    return

def JOI11_E():
    def grid_dfs(s, visited):
        rep = 0
        que = deque()
        que.append(s)
        while(que):
            y, x = que.pop()
            if visited[y][x]:
                continue
            visited[y][x] = True
            cur = y % 2
            for i in range(6):
                ny, nx = y + move[cur][i][0], x + move[cur][i][1]
                if ny >= H + 2 or ny < 0 or nx >= W + 4 or nx < 0:
                    continue
                if S[ny][nx] == 1:
                    rep += 1
                    continue
                que.append([ny, nx])
        return rep
    W, H = LI()
    S = [[0] * (W+4) for _ in range(H+2)]
    for i in range(H):
        S[i+1][2:W+2] = LI()
    move = [[] for _ in range(2)]
    move[0] = [[-1, -1], [-1, 0], [0, -1], [0, 1], [1, -1], [1, 0]]
    move[1] = [[-1, 0], [-1, 1], [0, -1], [0, 1], [1, 0], [1, 1]]

    visited = [[False] * (W + 4) for _ in range(H + 2)]
    ans = grid_dfs((0,0),visited)
    print(ans)
    return

"""
8 5
0 1 1 1 0 1 1 1
0 1 0 0 1 1 0 0
1 0 0 1 1 1 1 1
0 1 0 1 1 0 1 0
0 1 1 0 1 1 0 0
"""

def ABC88_D():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]
        def bfsg():
            queue = deque()
            queue.append(s)
            distance[s[0]][s[1]] = 0
            while len(queue):
                y, x = queue.popleft()
                for i in range(4):
                    nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                    if (0 <= nx < w and 0 <= ny < h and maze[ny][nx] != '
                        if distance[ny][nx] <= distance[y][x] + 1:
                            continue
                        queue.append((ny, nx))
                        distance[ny][nx] = distance[y][x] + 1
            return distance

        return bfsg()
    H, W = LI()
    S = [SI()for _ in range(H)]
    B = 0
    for s in S:
        for i in range(W):
            if s[i]=="
                B += 1
    L = bfs_grid(H,W,(0,0),S)
    if L[H-1][W-1]==inf:
        print(-1)
    else:
        ans = H*W-B-L[H-1][W-1]-1
        print(ans)
    return


import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    ABC88_D()

"""

"""

Solution (Python):
import sys
import numpy as np
H,W = map(int, input().split())
read = sys.stdin.read
grid = np.array(list(map(str,read()))).reshape(H,-1)[:,:-1]

black_ind = np.where(grid == '

C = np.zeros([H,W],np.int32)
C[black_ind] = 1

num_orig_black = np.count_nonzero(C)

q = [[0,0,1]]

minimum_pass = -1
while q:
	ch,cw,cd = q.pop(0)
	if ch == H-1 and cw == W-1:
		minimum_pass = cd
		break
	if C[ch,cw] == 1:
		continue
	
	C[ch,cw] = 1

	for nh,nw in [[ch+1,cw],[ch-1,cw],[ch,cw+1],[ch,cw-1]]:
		if 0 <= nh < H and 0 <= nw < W:
			if C[nh,nw] == 0:
				q.append([nh,nw,cd+1])

if minimum_pass == -1:
	print(-1)
else:
	print(W*H - minimum_pass - num_orig_black)