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):
h,w=map(int,input().split())
maze=[list(input()) for i in range(h)]
distance=[[-1]*w for i in range(h)]

cnt=0
for i in maze:
  cnt+=i.count('

Q=[[0,0]]
distance[0][0]=1

ans=-1

while Q:
  p=Q.pop(0)
  if p[0]==h-1 and p[1]==w-1:
    ans=h*w-cnt-distance[h-1][w-1]
    break

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

  for i in range(4):
    nx=p[0]+dx[i]
    ny=p[1]+dy[i]

    if 0<=nx<h and 0<=ny<w and distance[nx][ny]==-1 and maze[nx][ny]!='
      Q.append([nx,ny])
      distance[nx][ny]=distance[p[0]][p[1]]+1

print(ans)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
S = [input() for _ in range(H)]

dist = [[-1]*W for _ in range(H)]
dist[0][0]=1
d=deque()
d.append((0,0))

while d:
    pop = d.popleft()
    y, x = pop[0], pop[1]

    y_lst = [y+1, y-1, y, y]
    x_lst = [x, x, x+1, x-1]

    for Y, X in zip(y_lst, x_lst):
        if not (0 <= Y < H) or not (0 <= X < W) or S[Y][X]=="
            continue
        if dist[Y][X]==-1:
            dist[Y][X] = dist[y][x] + 1
            d.append((Y, X))

if dist[H-1][W-1]==-1:
    print(-1)
else:
    goaltime = dist[H-1][W-1]
    white_sum = 0
    for i in S:
        white_sum += i.count(".")
    print(white_sum-goaltime)

Solution (Python):
import sys
H,W=map(int,input().split())
L = [[0 for j in range(W)] for i in range(H)]
c=0
for i in range(H):
  a=list(input())
  c+=a.count(".")
  L[i]=a

subete=[[0,0]]
ans = [[] for i in range(H*W+1)]
ans[0].append([0,0])
for i in range(H*W+1):
  for j in range(len(ans[i-1])):
    a,b=ans[i-1][j][0],ans[i-1][j][1]
    if a+1!=H:
      if [a+1,b] not in subete and L[a+1][b]==".":
        ans[i].append([a+1,b])
        subete.append([a+1,b])
    if a!=0:
      if [a-1,b] not in subete and L[a-1][b]==".":
        ans[i].append([a-1,b])
        subete.append([a-1,b])
    if b+1!=W:
      if [a,b+1] not in subete and L[a][b+1]==".":
        ans[i].append([a,b+1])
        subete.append([a,b+1])
    if b!=0:
      if [a,b-1] not in subete and L[a][b-1]==".":
        ans[i].append([a,b-1])
        subete.append([a,b-1])
  if [H-1,W-1] in subete:
    print(c-i-1)
    sys.exit()
print(-1)

Solution (Python):
from collections import deque

H, W = map(int, input().split())

maze = "
for _ in range(H):
  maze += "
maze += "

dist = [-1] * (W+2) * (H+2)
q = deque()

dist[(W+2) * 1 + 1] = 0
q.append((W+2) * 1 + 1)

while len(q) != 0:
  v = q.popleft()
  
  udlr = (-W-2, W+2, -1, 1)
  for move in udlr:
    nv = v + move
    if maze[nv] == "
      continue
    if dist[nv] != -1:
      continue
    dist[nv] = dist[v] + 1
    q.append(nv)
if dist[(W+2) * H + W] == -1:
  print(-1)
else:
  print(W * H - maze.count("

Solution (Python):



import numpy as np

H, W = map(int, input().strip().split())
s = [input() for i in range(H)]

direction_x = [1, -1, 0, 0]
direction_y = [0, 0, 1, -1]
reached = np.zeros((H, W))
que_x = [0]
que_y = [0]
can_reach = False

for x, y in zip(que_x, que_y):
    if x == H - 1 and y == W - 1:
        can_reach = True
        break
    for i in range(4):
        next_x = x + direction_x[i]
        next_y = y + direction_y[i]
        if not(0 <= next_x < H) or not(0 <= next_y < W):
            continue
        if s[next_x][next_y] == '
            continue
        if reached[next_x][next_y] > 0:
            reached[next_x][next_y] = min(reached[next_x][next_y], reached[x][y] + 1)
            continue
        reached[next_x][next_y] = reached[x][y] + 1
        que_x.append(next_x)
        que_y.append(next_y)

res = 0
if can_reach:
    for i in range(H):
        for j in range(W):
            if s[i][j] == '.':
                res += 1
    res = res - reached[H-1][W-1] - 1
else:
    res = -1
print(int(res))

Solution (Python):
from collections import deque

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

root = [[float("inf") for _ in range(w)] for _ in range(h)]
root[0][0] = 1
D = deque([[0, 0]])
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

while D:
    p = D.popleft()

    if p == [h-1, w-1]:
        break

    for i in range(4):
        x = p[0]+dx[i]
        y = p[1]+dy[i]
        if 0<=x<=h-1 and 0<=y<=w-1 and root[x][y]==float("inf") and maze[x][y]==".":
            root[x][y] = root[p[0]][p[1]] + 1
            D.append([x, y])

white = 0
for i in range(h):
    for j in range(w):
        if maze[i][j]==".":
            white += 1

if root[h-1][w-1] ==float("inf"):
    print(-1)
else:
    print(white - root[h-1][w-1])

Solution (Python):
from collections import deque

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

maze = [list(input()) for _ in range(h)]
step = [[0] * w for _ in range(h)]
direction = [[1,0],[-1,0],[0,1],[0,-1]]

def bfs(maze,h,w):
    start = [0,0]
    
    q = deque([start])
    while q:
        x, y = q.popleft()
        for d in direction:
            nx = x + d[0]
            ny = y + d[1]
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] == "." and step[nx][ny] == 0:
                q.append([nx,ny])
                step[nx][ny] = step[x][y] + 1
        if step[h-1][w-1] != 0:
            return step[h-1][w-1]
    return -1


wall = 0
for i in maze:
    for j in i:
        if j == "
            wall += 1
if bfs(maze,h,w) >= 0:
    ans = h * w - wall - (bfs(maze,h,w) + 1)
else:
    ans = -1
print(ans)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
Map = [['
Map += [['
Map += [['

cnt = 0

for i in range(h+2):
    for j in range(w+2):
        if Map[i][j] == '.':
            cnt += 1
            
stack = deque([(1,1)])
Map[1][1] = 1
moved = [[0,1], [0,-1], [1,0], [-1,0]]

while stack:
    x, y = stack.popleft()
    for s, t in moved:
        if Map[x+s][y+t] == '.':
            stack.append((x+s, y+t))
            Map[x+s][y+t] = Map[x][y] + 1

goal = Map[-2][-2]
if goal == '.':
    print(-1)
else:
    print(cnt - goal)

Solution (Python):
from queue import deque
H, W = map(int, input().split())
matrix = []
count = 0
for i in range(H):
    matrix.append(list(input()))
    count += matrix[-1].count('.')
que = deque([(0, 0, 1)])

visited = set()

while que:
    row, col, depth = que.popleft()

    if not(0 <= row < H and 0 <= col < W) or matrix[row][col] == '
        continue
    
    if (row, col) in visited:
        continue

    visited.add((row, col))
    if (row, col) == (H-1, W-1):
        print(count - depth)
        exit()
    
    for ud, lr in ((-1, 0), (1, 0), (0, -1), (0, 1)):
        que.append((row+ud, col+lr, depth+1))
print(-1)

Solution (Python):
from collections import deque
import sys
input = sys.stdin.readline

h,w = map(int,input().split())
MAP = [list(input().rstrip()) for i in range(h)]  
sharp = 0
for i in range(h):
  sharp += MAP[i].count("



MAP[0][0]=1
MOVE = [[1,0],[-1,0],[0,1],[0,-1]]
STACK = deque([(0,0)])
while STACK:
  y, x = STACK.popleft()
  for dy,dx in MOVE:
    ny = y + dy
    nx = x + dx
    if not(0 <= ny < h) or not(0 <= nx < w) or MAP[ny][nx]!='.':
      continue
    else:
      STACK.append((ny,nx))
      MAP[ny][nx] = MAP[y][x] + 1


if type(MAP[h-1][w-1]) == int:
  ans = h*w -MAP[h-1][w-1]-sharp
else:
  ans = -1
    
print(ans)

Solution (Python):
import collections
def f(mat):
	q,vis = collections.deque([((0,0), 1)]), set([(0,0)])
	while(q):
		u,d = q.popleft()
		if u == (len(mat)-1, len(mat[0])-1): return collections.Counter(reduce(lambda x,y:x+y, mat))['.'] - d
		for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1),(u[0],u[1]-1)]:
			if 0 <= v[0] < len(mat) and 0 <= v[1] < len(mat[0]) and (v not in vis) and mat[v[0]][v[1]] == '.':
				vis.add(v)
				q.append((v, d+1))
	return -1
print f([list(raw_input()) for l in range(map(int, raw_input().split())[0])])

Solution (Python):
import collections
h,p = map(int, raw_input().split())
def f(mat, h, p):
	q = collections.deque([((0,0), 1)])
	vis = set([(0,0)])

	while(q):
		u,d = q.popleft()
		if u == (h-1, p-1): return collections.Counter(reduce(lambda x,y:x+y, mat))['.'] - d
			
		for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1),(u[0],u[1]-1)]:
			if 0 <= v[0] < len(mat) and 0 <= v[1] < len(mat[0]):
				if v not in vis and mat[v[0]][v[1]] == '.':
					vis.add(v)
					q.append((v, d+1))
	return -1
print f([list(raw_input()) for l in range(h)], h, p)

Solution (Python):

import collections
h,p = map(int, raw_input().split())
mat = [list(raw_input()) for l in range(h)]
q = collections.deque([((0,0), 1)])

vis = set([(0,0)])
r  = float('inf')

while(q):
	u,d = q.popleft()

	if u == (h-1, p-1):
		r = d
		break
	for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1),(u[0],u[1]-1)]:
		if 0 <= v[0] < len(mat) and 0 <= v[1] < len(mat[0]):
			if v not in vis and mat[v[0]][v[1]] == '.':
				vis.add(v)
				q.append((v, d+1))

cc = collections.Counter()
for l in mat:
	for e in l:
		cc[e]+=1

if r < float('inf'):
	print cc['.'] - r
else:
	print -1

Solution (Python):
from collections import deque
H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]

s = (0,0)
g = (H-1,W-1)

ans = 0
task = deque([(s,0)])
visited = [[0 for _ in range(W)] for _ in range(H)]
visited[s[0]][s[1]] = 1
flag = False
while task:
  p, c = task.popleft()
  x = p[0]
  y = p[1]
  if p == g:
    ans = c
    flag = True
    break 
  if x >= 1 and visited[x-1][y] == 0 and M[x-1][y] == ".":
    visited[x-1][y] = 1
    task.append(((x-1,y),c+1))
  if y >= 1 and visited[x][y-1] == 0 and M[x][y-1] == ".":
    visited[x][y-1] = 1
    task.append(((x,y-1),c+1))
  if x <= H-2 and visited[x+1][y] == 0 and M[x+1][y] == ".":
    visited[x+1][y] = 1
    task.append(((x+1,y),c+1))
  if y <= W-2 and visited[x][y+1] == 0 and M[x][y+1] == ".":
    visited[x][y+1] = 1
    task.append(((x,y+1),c+1))     

point = H*W -sum([M[i].count("
print(point if flag else -1)

Solution (Python):
def main():
    import sys
    from collections import deque

    def input(): return sys.stdin.readline().rstrip()

    def bfs(si, sj):
        di = [-1, 0, 1, 0]
        dj = [0, 1, 0, -1]
        que = deque([(si, sj)])
        dist[0][0] = 0
        while que:
            i, j = que.popleft()
            for k in range(4):
                ni = i+di[k]
                nj = j+dj[k]
                if (ni < 0 or ni >= h or nj < 0 or nj >= w):
                    continue
                if g[ni][nj] == '
                    continue
                if dist[ni][nj] > dist[i][j]+1:
                    dist[ni][nj] = dist[i][j]+1
                    que.append((ni, nj))
        

    h, w = map(int, input().split())
    g = []
    cnt = 0
    for i in range(h):
        g.append(input())
        cnt += g[-1].count('
    inf = 10**6
    dist = [[inf]*w for _ in range(h)]

    bfs(0, 0)
    if dist[-1][-1] == inf:
        print(-1)
    else:
        ans = h*w-cnt-dist[-1][-1]-1
        print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import queue

H, W = map(int, input().split())
S = []

for _ in range(H):
    S.append(list(input()))

SS = []
for _ in range(H):
    SSS = []
    for __ in range(W):
        SSS.append(-1)
    SS.append(SSS)

SS[0][0] = 0

sp = (0, 0, 0)
dx = (1, 0, -1, 0)
dy = (0, 1, 0, -1)

q = queue.Queue()
q.put(sp)

ans = -1
complete = False
while not q.empty():

    n = q.get()
    if n[0] == W-1 and n[1] == H-1:
        ans = n[2]
        complete = True
        break

    for d in range(4):
        nx = n[0] + dx[d]
        ny = n[1] + dy[d]

        if W > nx >= 0 and H > ny >= 0 and SS[ny][nx] == -1 and S[ny][nx] != '
            q.put((nx, ny, n[2]+1))
            SS[ny][nx] = n[2] + 1

wcnt = 0
for _ in range(H):
    for __ in range(W):
        if S[_][__] == '.':
            wcnt += 1
if complete:
    print(wcnt - ans - 1)
else:
    print(-1)

Solution (Python):

import sys
sys.setrecursionlimit(10**7)
import bisect
import heapq
import itertools
import math
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from math import gcd
from operator import add, itemgetter, mul, xor
def cmb(n,r,mod):
  bunshi=1
  bunbo=1
  for i in range(r):
    bunbo = bunbo*(i+1)%mod
    bunshi = bunshi*(n-i)%mod
  return (bunshi*pow(bunbo,mod-2,mod))%mod
mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

h,w = MI()
s = [list(input()) for _ in range(h)]
dist = [[-1]*(w) for _ in range(h)]

black_cnt = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == "
            dist[i][j] = 0
            black_cnt += 1
dist[0][0] = 0
d = deque()
d.append([0,0])
dx = [1,-1,0,0]
dy = [0,0,1,-1]
while d:
    v = d.popleft()
    x = v[0]
    y = v[1]
    for i in range(4):
        nx = x+ dx[i]
        ny = y+ dy[i]
        if nx < 0 or nx >= h or ny < 0 or ny >= w:
            continue
        if dist[nx][ny] == -1:
            dist[nx][ny] = dist[x][y] + 1
            d.append([nx,ny])
if dist[-1][-1] == -1:
    print(-1)
else:
    shortest = dist[-1][-1]
    print(h*w - black_cnt -(shortest+1))

Solution (Python):
from collections import deque

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


sx = 0
sy = 0
gx = h-1
gy = w-1

dist=[[-1 for j in range(w)] for i in range(h)]
dist[sx][sy]=0
 
que = deque([(sx,sy,0)])
 
while que:
  u,v,z = que.popleft()
  for i,j in [(-1,0),(0,-1),(1,0),(0,1)]:
    if not (0<=u+i<h and 0<=v+j<w):
      continue
    elif graph[u+i][v+j]=="
      continue
    elif dist[u+i][v+j]>0:
      continue

    dist[u+i][v+j]=z+1
    que.append([u+i,v+j,z+1])

if dist[gx][gy]==-1: 
  print(-1)
else:
  print(h*w-(dist[gx][gy]+1)-black_num)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
G = [input() for _ in range(H)]
num = 0
for i in range(H):
    for j in range(W):
        if G[i][j] == ".":
            num += 1
q = deque([(0, 0)])
done = [[-1]*W for _ in range(H)]
done[0][0] = 1
while q:
    w, h = q.popleft()
    for dw, dh in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        nw, nh = w+dw, h+dh
        if not (0 <= nw < W and 0 <= nh < H and G[nh][nw] == "." and done[nh][nw] == -1): continue
        done[nh][nw] = done[h][w]+1
        q.append((nw, nh))
if done[H-1][W-1] != -1:
    print(num-done[H-1][W-1])
else:
    print(-1)

Solution (Python):
from collections import deque
import sys
H, W = list(map(int, input().split()))

city = []

for _ in range(H):
    city.append(list(input()))

dist = [[float("inf") for _ in range(W)] for _ in range(H)]

dist_count = [0 for _ in range(H*W)]

queue = deque()
queue.append((0, 0))
dist[0][0] = 0

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

while len(queue) > 0:
    now_x, now_y = queue.popleft()

    for dx_, dy_ in zip(dx, dy):

        adj_x = now_x + dx_
        adj_y = now_y + dy_

        if (not 0 <= adj_x < W) or (not 0 <= adj_y < H):
            continue

        if city[adj_y][adj_x] == "
            continue

        if dist[adj_y][adj_x] > H*W:
            dist[adj_y][adj_x] = dist[now_y][now_x] + 1
            queue.append((adj_x, adj_y))
            dist_count[dist[adj_y][adj_x]] += 1


if dist[H-1][W-1] > H**W:
    print(-1)
    sys.exit()


route_grids = dist[H-1][W-1] + 1

white_all = 0
for i in range(H):
    for j in range(W):
        if city[i][j] == ".":
            white_all += 1
ans = white_all - route_grids
print(ans)

Solution (Python):
from collections import deque
h, w = map(int, input().split())
ss = [input() for _ in range(h)]
q = deque([(0, 0, 0)])
cost = 0
visited = [[False for _ in range(w)] for _ in range(h)]


def find():
    while len(q) > 0:
        y, x, cost = q.popleft()
        if (y, x) == (h - 1, w - 1):
            return cost
        if 0 <= y < h and 0 <= x < w and ss[y][x] != '
            visited[y][x] = True
            q.append((y + 1, x, cost + 1))
            q.append((y - 1, x, cost + 1))
            q.append((y, x + 1, cost + 1))
            q.append((y, x - 1, cost + 1))
    return -1


c = find()
if c < 0:
    print(-1)
else:
    dots = 0
    for i in range(h):
        for j in range(w):
            if ss[i][j] != '
                dots += 1
    print(dots - c - 1)

Solution (Python):
class Grid:
    def __init__(self, H, W, grid, road_wall=(".", "
        self.road, self.wall = road_wall
        self.H = H
        self.W = W
        self.destroy = destroy
        self.grid = grid
        self.parent = [[-1] * self.W for _ in range(self.H)]
        self.move = [(1, 0), (-1, 0), (0, 1), (0, -1)]     

    def bfs(self, start=(0,0), goal=-3, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if save:
            parent = self.parent
        else:
            parent = [[-1] * self.W for _ in range(self.H)]
        p, t = start, time
        parent[p[0]][p[1]] = -2
        next_set = deque([(p, t)])
        while next_set:
            p, t = next_set.popleft()
            h, w = p
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         
                    continue
                if parent[q[0]][q[1]] != -1:
                    continue
                
                
                
                if q == goal:
                    return t + 1
                parent[q[0]][q[1]] = p
                next_set.append((q, t + 1))
        return -1

    def connection_counter(self):
        """
        :return: 連結成分の個数。有効グラフではあまり意味がない。
        """
        cnt = 0
        self.parent = [[-1] * self.W for _ in range(self.H)]
        for h in range(self.H):
            for w in range(self.W):
                if self.parent[h][w] == -1:
                    cnt += 1
                    self.bfs(start=(h,w), save=True)
        return cnt

    def distance_list(self, start=(0,0), save=False):
        """
        :param start: スタート地点
        :return: スタート地点から各点への距離のリスト
        """
        dist = [[-1] * self.W for _ in range(self.H)]
        if save:
            parent = self.parent
        else:
            parent = [[-1] * self.W for _ in range(self.H)]
        p, t = start, 0
        parent[p[0]][p[1]] = -2
        dist[p[0]][p[1]] = 0
        next_set = deque([(p, t)])

        while next_set:
            p, t = next_set.popleft()
            h, w = p
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         
                    continue
                if parent[q[0]][q[1]] != -1:
                    continue
                dist[q[0]][q[1]] = t + 1
                parent[q[0]][q[1]] = p
                next_set.append((q, t + 1))
        return dist

    def most_distant_point(self, start=(0, 0), save=False):
        """
        :param start:
        :return: start 地点から最も遠い点を ((h,w), 距離) として出力
        """
        res = (start, 0)
        temp = 0
        dist = self.distance_list(start, save=save)
        for h in range(self.H):
            for w in range(self.W):
                if dist[h][w] > temp:
                    temp = dist[h][w]
                    res = ((h, w), temp)
        return res

    def diameter(self, start=(0,0), save=False):
        """
        :return:　木の直系（最も離れた二頂点間の距離）を返す
        """
        p = self.most_distant_point(start, save=False)
        res = self.most_distant_point(start=p[0], save=save)
        return res[1]

    def diameter2(self):
        """
        :return:　連結ではない時に、最大の直系を返す
        """
        res = 0
        for h in range(self.H):
            for w in range(self.W):
                if self.grid[h][w] == self.road and self.parent[h][w] == -1:
                    temp = self.diameter(start=(h, w), save=False)
                    if temp > res:
                        res = temp
        return res

    def dfs(self, start=(0, 0), goal=-3, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: ゴール地点までの距離。存在しなければ -1。ループがある時は最短距離とは限らないため注意。
        """

        if save:
            parent = self.parent
        else:
            parent = [[-1] * self.W for _ in range(self.H)]
        move2 = [[marshal.loads(marshal.dumps(self.move)) for _ in range(self.W)] for _ in range(self.H)]

        p, t = start, time
        parent[p[0]][p[1]] = -2
        while True:
            if move2[p[0]][p[1]]:
                h, w = p
                dh, dw = move2[p[0]][p[1]].pop()
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         
                    continue
                if q == parent[p[0]][p[1]]:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if parent[q[0]][q[1]] != -1:
                    """ サイクルで同一点を訪れた時の処理 """
                    """"""""""""""""""""
                    continue
                
                
                
                
                if q == goal:
                    """ ゴール時の処理"""
                    """"""""""""""""""""
                    return t + 1
                """ p から q への引継ぎ"""
                """"""""""""""""""""
                parent[q[0]][q[1]] = p
                p, t = q, t + 1
            else:
                if p == start and t == time:
                    break
                p_temp = p
                p, t = parent[p[0]][p[1]], t-1
                """ p から進める点がもう無い時の点 p における処理 """
                
                
                """"""""""""""""""""
                """ 点 p から親ノードに戻ってきた時の親ノードにおける処理 """
                """"""""""""""""""""
        return -1

    def dfs2(self, start=(0, 0), goal=-3, time=0):
        visited = [[-1] * self.W for _ in range(self.H)]
        p, t = start, time
        res = 0
        def rec(p, past_p, t, visited, res):
            h, w = p
            visited[p[0]][p[1]] = 1
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if grid[q[0]][q[1]] == self.wall:
                    continue
                if q == past_p:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if visited[q[0]][q[1]] == 1:
                    """ サイクルで同一点を訪れた時の処理 """
                    """"""""""""""""""""
                    continue
                """ (debug code) """
                
                
                """"""""""""""""""""
                if q == goal:
                    """ ゴール時の処理"""
                    """"""""""""""""""""
                    return t+1
                res = max2(rec(q, p, t + 1, visited, res), t + 1)
            """ 帰り際の処置（壊した道を元に戻す等)"""
            
            """"""""""""""""""""
            return res
        return rec(p, -1, t, visited, res)

    def debug(self, start, goal, p, t):
        player = p
        debug_grid = list(list(self.grid[h]) for h in range(self.H))
        if start != (None, None):
            debug_grid[start[0]][start[1]] = "S"
        if goal != -3:
            debug_grid[goal[0]][goal[1]] = "G"
        debug_grid[player[0]][player[1]] = "P"
        print("~~~~~~~~~ t = " + str(t + 1) + "  ~~~~~~~~")
        for debug_h in range(self.H):
            print("".join(str(debug_grid[debug_h][debug_w]) for debug_w in range(self.W)))

    def show_visited(self, start, goal, p, t, parent):
        player = p
        debug_grid = list(list(self.grid[h]) for h in range(self.H))
        for h in range(H):
            for w in range(W):
                if parent[h][w] != -1:
                    debug_grid[h][w] = "V"
        if start != (None, None):
            debug_grid[start[0]][start[1]] = "S"
        if goal != -3:
            debug_grid[goal[0]][goal[1]] = "G"
        debug_grid[player[0]][player[1]] = "P"
        print("~~~~~~~~~ t = " + str(t + 1) + "  ~~~~~~~~")
        for debug_h in range(self.H):
            print("".join(str(debug_grid[debug_h][debug_w]) for debug_w in range(self.W)))



from collections import deque
import sys
import marshal
input = sys.stdin.readline



road, wall = ".", "

H, W = map(int,input().split())                

grid = []
cnt = 0
for h in range(H):
    grid.append(input().rstrip())
    cnt += grid[-1].count(".")
start = (0,0)
goal = (H-1, W-1)

g = Grid(H, W, grid, (road, wall), destroy=False)
res = g.bfs(start, goal, save=True)
if res == -1:
    print(-1)
else:
    print(cnt - res - 1)