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 #.



Difficulty: interview

Starter code:

Solutions:
import copy
h,w =list(map(int,input().split()))

s = [[]*w for _ in range(h)]
white =0
for i in range(h):
    t = input()
    for j in range(w):
        if t[j] == ".":
            white += 1
            s[i].append(10**5)
        elif t[j] == "#":
            s[i].append(t[j])
now = [0,0]
steps =[]
steps.append(now)
direction = []
s[0][0] =0
a = [2]
while len(steps) >0:
    now = copy.copy(steps[0])
    if s[now[0]][now[1]] =="#":
        continue
    for k in [[0,1],[1,0],[-1,0],[0,-1]]:
        now = copy.copy(steps[0])
        if now[0] + k[0] >=0 and now[0] + k[0] < h:
            now[0] += k[0]
            if now[1] + k[1] >=0 and now[1] + k[1] <w:
                now[1] += k[1]
                if s[now[0]][now[1]] == 10**5:
                    if not [now[0],now[1]] in steps:
                        steps.append([now[0],now[1]])
            else:
                continue
        else:
            continue
    # if s[steps[0][0]][steps[0][1]] ==0:
    #     steps.pop(0)
    #     continue
    if s[steps[0][0]][steps[0][1]] >10**4:
        direction =[]
        for l in [[0,1],[1,0],[-1,0],[0,-1]]:
            if steps[0][0]+l[0]>=0 and steps[0][0]+l[0]<h and steps[0][1]+l[1]< w and steps[0][1]+l[1] >=0 and s[steps[0][0]+l[0]][steps[0][1]+l[1]] != "#":
                s[steps[0][0]][steps[0][1]]=min(s[steps[0][0]+l[0]][steps[0][1]+l[1]]+1,s[steps[0][0]][steps[0][1]])
    steps.pop(0)
if s[h-1][w-1] == "#" or s[h-1][w-1] == 10**5:
    print((-1))
else:
    print((white-1 - s[h-1][w-1]))









from collections import deque

def bfs():
    # たどり着くまでにかかった回数をいれる多重リスト。
    d = [[float("inf")] * w for i in range(h)]
    # 1ノード降りるときにforで回せるようリスト化しておく
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    # 接したポイントを取り込む用のqueを定義
    que = deque([])
    # スタート地点をqueに加える。探索の際はqueから取り出すループを回すので最初だけ先に入れておく
    que.append((sx,sy))
    # スタートからスタートにかかる距離は0なのでinfを0にかえる。
    d[sx][sy] = 0
    # queがあるかぎり続ける
    while que:
        p = que.popleft()
        # 取り出した点がゴールなら終了
        if p[0] == gy and p[1] == gx:
            break
        #　それ以外の時は，接している点を4方向順に取得。一つずつ処理する。
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            # 新しく取得した座標に対しての処理
            # 迷路内に存在する座標であり，壁ではなく，まだ通ったことがなくdがinfの点なら処理する = 新しく取得した道候補の1つ
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                # 道候補をqueに加える。
                que.append((nx, ny))
                # その道候補への経路までにかかった経路をdに加える。
                d[nx][ny] = d[p[0]][p[1]] + 1
    return d[gx][gy]

h, w = list(map(int, input().split()))
maze = [list(input()) for i in range(h)]
sx, sy = 0, 0
gx, gy = h - 1, w - 1

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

res = bfs()
if 0 < res < float("inf"):
    # 白いマスの数から最短経路でかかるコスト分を引く
    # ゴールを黒いマスに変えることはできないためその分も引く
    print((white - res - 1))
else:
    print((-1))


from collections import deque
import sys
h,w = map(int,input().split())
mp = [list(input()) for _ in range(h)]

visited = [[0]*w for _ in range(h)]

dxdy = [[1,0],[0,1],[-1,0],[0,-1]]

queue = deque()
queue.append([0,0,1])
visited[0][0]=1

while queue:
    x,y,d = queue.popleft()
    for dx,dy in dxdy:
        nx,ny = x+dx,y+dy
        if -1<nx<h and -1<ny<w and visited[nx][ny]==0 and mp[nx][ny]!="#":
            visited[nx][ny]=d+1
            queue.append([nx,ny,d+1])
            #[print(*visited[l]) for l in range(h)]
            #print("---------------")            

if visited[-1][-1]==0:
    print(-1)
    return

cnt = 0
for i in range(h):
    for j in range(w):
        if mp[i][j]!="#":
            cnt += 1

print(cnt-visited[-1][-1])

from collections import deque

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

q = deque([(0, 0)])
dists = [[10000] * w for _ in range(h)]
dists[0][0] = 0
prev = [[-1] * w for _ in range(h)]

while q:
    x, y = q.popleft()

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

    for xo, yo in nei:
        nextx, nexty = x+xo, y+yo

        if nextx < 0 or nextx >= w or nexty < 0 or nexty >= h:
            continue
        if grid[nexty][nextx] == "#":
            continue

        dist = dists[y][x]+1

        if dist < dists[nexty][nextx]:
            dists[nexty][nextx] = dist
            prev[nexty][nextx] = (x, y)
            q.append((nextx, nexty))

if prev[h-1][w-1] != -1:
    path = []
    cur = (w-1, h-1)

    while cur != -1:
        path.append(cur)
        cur = prev[cur[1]][cur[0]]

    cnt = 0
    for i in range(w):
        for j in range(h):
            if grid[j][i] == "." and (i, j) not in path:
                cnt += 1

    print(cnt)
else:
    print(-1)

from collections import deque

Y, X = map(int, input().split())
Map = list(input() for _ in range(Y))

def bfs(sy, sx, gy, gx):
    seen = list([-1]*X for _ in range(Y))
    queue = deque()
    queue.append((sy, sx))
    seen[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        search_around(y, x, seen, queue)
        if seen[gy][gx] > 0:
            return seen[gy][gx]

def search_around(y, x, seen, queue):
    count = seen[y][x]
    for u,t in [(y-1,x), (y+1,x), (y,x-1), (y,x+1)]:
        if u < 0 or t < 0 or u >= Y or t >= X:
            continue
        elif Map[u][t] == '#' or seen[u][t] != -1:
            continue
        queue.append((u, t))
        seen[u][t] = count + 1
        
cnt = 0
for M in Map:
    for m in M:
        if m == '#':
            cnt += 1

b = bfs(0,0,Y-1,X-1)
if b == None:
    print(-1)
else:
    print(Y*X - cnt - b - 1)

H,W=map(int,input().split())
MAP=[list(input()) for _ in range(H)]
cnt=0
for l in MAP:
  cnt+=l.count("#")
FLAG=[[-1]*W for _ in range(H)]
FLAG[0][0]=1
q=[(0,0)]
d=[(1,0),(0,1),(-1,0),(0,-1)]
while q:
  y,x=q.pop(0)
  for dy,dx in d:
    if 0<=y+dy<H and 0<=x+dx<W and FLAG[y+dy][x+dx]==-1 and MAP[y+dy][x+dx]==".":
      FLAG[y+dy][x+dx]=FLAG[y][x]+1
      q.append((y+dy,x+dx))

if FLAG[H-1][W-1]==-1:
  print(-1)
else:
  print(H*W-FLAG[H-1][W-1]-cnt)

from collections import deque

h,w=map(int,input().split())
w_sum=0
maze=[]
inf=10000000
for _ in range(h):
  s=list(input())
  for i in range(w):
    if s[i]=='.':
      s[i]=inf
      w_sum+=1
  maze.append(s)
  
def solve(maze,h,w):
  qu=deque([[0,0]])
  maze[0][0]=0
  while qu:
    y,x=qu.popleft()
    t=maze[y][x]
    for i in ([1,0],[-1,0],[0,1],[0,-1]):
      ny=y+i[0]
      nx=x+i[1]
      if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!='#':
        if maze[ny][nx]>t+1:
          maze[ny][nx]=t+1
          qu.append([ny,nx])
          
  return maze[h-1][w-1]
  
if solve(maze,h,w)==inf:
  print(-1)
else:
  print(w_sum-solve(maze,h,w)-1)

from collections import deque
H, W = list(map(int, input().split()))
route = []
n_black = 0
for _ in range(H):
  tmp_ls = input()
  n_black += tmp_ls.count("#")
  route.append(tmp_ls)
visited = [[False]*W for _ in range(H)]
dist = [[-1]*W for _ in range(H)]
dist[0][0] = 0
tmp = [0,0]
goal = [H-1, W-1]
kouho = deque()
def rinsetsu(ls):
  x, y = ls[0], ls[1]
  ans = []
  if x-1 >= 0:
    ans.append([x-1, y])
  if x+1 <= H-1:
    ans.append([x+1, y])
  if y-1 >= 0:
    ans.append([x, y-1])
  if y+1 <= W-1:
    ans.append([x, y+1])
  return ans
for ls in rinsetsu([0,0]):
  if route[ls[0]][ls[1]] == ".":
    kouho.append([ls[0], ls[1], 0, 0])
def bfs():
  while True:
    while True:
      if len(kouho) == 0:
        return
      tmp = kouho.popleft()
      if not visited[tmp[0]][tmp[1]]:
        break
    x, y = tmp[0], tmp[1]
    visited[x][y] = True
    dist[x][y] = dist[tmp[2]][tmp[3]] + 1
    if [x, y] == goal:
      return
    for ls in rinsetsu([x,y]):
      if not visited[ls[0]][ls[1]] and route[ls[0]][ls[1]] == ".":
        kouho.append(ls + [x, y])
bfs()
if dist[H-1][W-1] == -1:
  print((-1))
else:
  white = dist[H-1][W-1] + 1
  print((H*W - white - n_black))



from collections import deque

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

mazo = [list(input()) for _ in range(H)]

cnt = 0 #初期状態の黒の数を数える
for i in range(H):
    for j in range(W):
        if mazo[i][j] == "#":
            cnt += 1

d = deque()
d.append((0,0))

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

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

flg = False
while d:
    y, x = d.popleft()
    if (y==H-1) and (x==W-1):
        flg = True
        break

    for u, v in move:
        t = y + u
        s = x + v
        if 0 <= t and t<H and 0<=s and s<W and mazo[t][s]=="." and visited[t][s]==0:
            visited[t][s] = visited[y][x] + 1
            d.append((t, s))

if flg:
    print((H*W - cnt - visited[H-1][W-1] -1))
else:
    print((-1))


def __starting_point():
    from collections import deque
    H, W = map(int,input().split())
    s = []
    black = 0
    for _ in range(H):
        t = list(input())
        for c in t:
            if c == "#":
                black += 1
        s.append(t)
    q = deque([(0,0,1)])
    s[0][0] = "#"
    while q:
        x,y,d = q.popleft()
        if x == H-1 and y == W-1:
            print(H*W-d-black)
            return
        for nx,ny in [(x+1,y), (x,y+1), (x-1,y), (x,y-1)]:
            if 0 <= nx < H and 0<= ny < W and s[nx][ny] == ".":
                s[nx][ny] = "#"
                q.append((nx,ny,d+1))
    print(-1)
__starting_point()

H, W = map(int, input().split())
import numpy as np
Grid = np.array([[0 if x == '.' else -1 for x in input()] for _ in range(H)],dtype='int64')

def solveMase(Grid, start, goal): #bfsで迷路を解き、スタート-ゴール間の最低必要白マス数を返す
    seen = {start}
    V = [start]
    while len(V) != 0: #bfs
        v = V.pop(0)
        if v == goal:
            return Grid[goal]
        #移動先nvをリストにまとめる
        y,x = v
        nV = []
        if x > 0: nV.append((y,x-1))
        if y > 0: nV.append((y-1,x))
        if x < W-1: nV.append((y,x+1))
        if y < H-1: nV.append((y+1,x))
        #bfs
        for nv in nV:
            if Grid[nv] == -1 or nv in seen:
                continue
            Grid[nv] = Grid[v] + 1
            V.append(nv)
            seen.add(nv)
    return 0

white = len(Grid[Grid == 0])-1
nes_white = solveMase(Grid, (0,0), (H-1,W-1))
print(white-nes_white if nes_white > 0 else -1)

from collections import deque

def bfs(sy,sx):
  queue = deque([[sy,sx]])
  d[sy][sx] = 0
  while queue:
    y,x = queue.popleft()
    for i,j in [(-1,0),(1,0),(0,-1),(0,1)]:
      dy,dx = y+i,x+j
      if dy < 0 or h <= dy: continue
      elif dx < 0 or w <= dx: continue
      elif s[dy][dx] == "#": continue
      elif d[dy][dx] != -1: continue
      d[dy][dx] = d[y][x] + 1
      queue.append([dy,dx])

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

if s[0][0] == "#" or s[h-1][w-1] == "#":
  print(-1)
  return

d = [[-1]*w for _ in range(h)]
bfs(0,0)
if d[h-1][w-1] == -1: print(-1)
else:
  t = 0
  for i in s: t += i.count("#")
  print(h*w - t - d[h-1][w-1] -1)

from queue import Queue
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

H, W = list(map(int, input().split()))
S = [input() for _ in range(H)]
dist = [[-1] * W for _ in range(H)]
que = Queue()

# 初期条件
dist[0][0] = 0
que.put((0, 0))

# 幅優先探索
while not que.empty():
    x, y = que.get()
    for dir in range(4):
        x2, y2 = x + dx[dir], y + dy[dir]
        if x2 < 0 or x2 >= H or y2 < 0 or y2 >= W or S[x2][y2] == '#':
            continue
        if dist[x2][y2] != -1:
            continue
        dist[x2][y2] = dist[x][y] + 1
        que.put((x2, y2))

# 白マス数
white = sum(sum(1 if S[x][y] == '.' else 0 for y in range(W)) for x in range(H))

# 答え
print((white - dist[H-1][W-1] - 1 if dist[H-1][W-1] != -1 else -1))


from _collections import deque


def bfs():  # 最短経路を求める　→　白マスの数から最短経路を引く
    que = deque([])
    que.append((0, 0))
    dh = [-1, 0, 1, 0]
    dw = [0, -1, 0, 1]
    d = [[float("inf")] * w for _ in range(h)]
    d[0][0] = 0
    while que:
        p = que.popleft()
        if p[0] == h-1 and p[1] == w-1:
            break
        for i in range(4):
            nh = p[0] + dh[i]
            nw = p[1] + dw[i]
            if 0 <= nh < h and 0 <= nw < w and d[nh][nw] == float("inf") and c[nh][nw] == '.':
                que.append((nh, nw))
                d[nh][nw] = 1 + d[p[0]][p[1]]
    return d[h-1][w-1]


h, w = list(map(int, input().split()))
c = [list(input()) for _ in range(h)]
count = 0  # 白マスの数
for i in range(h):
    for j in range(w):
        if c[i][j] == '.':
            count += 1

mi = bfs()

if 0 < mi < float("inf"):
    print((count - mi -1))
else:
    print((-1))


from collections import deque
import sys

H,W=map(int,input().split())
S=[[x for x in input()] for _ in range(H)]

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

d=deque([(0,0)])
distance=[[-1]*W for _ in range(H)]
distance[0][0]=0
goal_distance=0

while d:
  h,w=d.popleft()
  if h==H-1 and w==W-1:
    goal_distance=distance[h][w]
    break
  
  if h-1>=0 and S[h-1][w]=='.':
    d.append((h-1,w))
    distance[h-1][w]=distance[h][w]+1
    S[h-1][w]='#'
    
  if h+1<=H-1 and S[h+1][w]=='.':
    d.append((h+1,w))
    distance[h+1][w]=distance[h][w]+1
    S[h+1][w]='#'
    
  if w-1>=0 and S[h][w-1]=='.':
    d.append((h,w-1))
    distance[h][w-1]=distance[h][w]+1
    S[h][w-1]='#'
    
  if w+1<=W-1 and S[h][w+1]=='.':
    d.append((h,w+1))
    distance[h][w+1]=distance[h][w]+1
    S[h][w+1]='#'
else:
  if distance[H-1][W-1]==-1:
    print(-1)
    return

print(count-(goal_distance+1))

def main():
	H, W = [int(n) for n in input().split(" ")]
	iniBlack = 0
	S = []
	S.append(["X"] * (W + 2))
	for i in range(H):
		row = list(input())
		iniBlack += row.count("#")
		S.append(["X"] + row + ["X"])
	S.append(["X"] * (W + 2))

	to_visit = [{"row": 1, "col": 1, "step": 1}]
	checked = [[0] * (W + 2) for i in range(H + 2)]
	checked[1][1] = 1

	while len(to_visit) > 0:
		visiting = to_visit.pop(0)
		r0 = visiting["row"]
		c0 = visiting["col"]
		s0 = visiting["step"]
		for d in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
			r = r0 + d[0]
			c = c0 + d[1]
			if S[r][c] == "." and checked[r][c] == 0:
				to_visit.append({"row": r, "col": c, "step": s0 + 1})
				checked[r][c] = s0 + 1

	if checked[H][W] == 0:
		print(-1)
		return 0
	print(H * W - iniBlack - checked[H][W])

main()

import queue
h, w = list(map(int, input().split()))
s = []
black_num = 0
for i in range(h):
    s_ij = input()
    s.append(s_ij)
    for j in range(w):
        if s_ij[j] == "#":
            black_num += 1

already_pass = set()
already_pass.add((1, 1))
q = queue.Queue()
q.put([(1, 1), 1])

while not q.empty():
    x_y, l = q.get()
    x = x_y[0]
    y = x_y[1]
    if x == h and y == w:
        print((h * w - black_num - l))
        break
    next_xy = [(max(1, x - 1), y), (min(h, x + 1), y),
               (x, max(1, y - 1)), (x, min(w, y + 1))]
    for i in next_xy:
        if i not in already_pass and s[i[0] - 1][i[1] - 1] != "#":
            q.put([i, l + 1])
            already_pass.add(i)
else:
    print((-1))


from collections import deque


def bfs(start, goal):
    q = deque([[start]])
    visited = set()
    while q:
        path = q.popleft()
        i, j = path[-1]
        if (i, j) == goal:
            return path
        for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ni, nj = i + di, j + dj
            if not (0 <= ni < H and 0 <= nj < W and field[ni][nj] == "."):
                continue
            if (ni, nj) not in visited:
                q.append(path + [(ni, nj)])
                visited.add((ni, nj))
    return []


H, W = list(map(int, input().split()))
field = [input() for _ in range(H)]
shortest_path = bfs((0, 0), (H - 1, W - 1))
if shortest_path:
    print((sum(v == "." for row in field for v in row) - len(shortest_path)))
else:
    print((-1))


from collections import *
H,W = map(int,input().split())
S = [input() for h in range(H)]
V = [W*[0] for h in range(H)]
V[0][0] = 1
Q = deque([(0,0)])
while Q:
  x,y = Q.popleft()
  for dx,dy in ((-1,0),(0,-1),(1,0),(0,1)):
    if 0<=x+dx<H and 0<=y+dy<W and V[x+dx][y+dy]==0 and S[x+dx][y+dy]==".":
      V[x+dx][y+dy] = V[x][y]+1
      Q.append((x+dx,y+dy))

if V[H-1][W-1]==0:
  print(-1)
else:
  print(H*W-sum(s.count("#") for s in S)-V[H-1][W-1])

H, W = map(int, input().split())
MAP = [ list(input()) for _ in range(H) ]
cnt = 0
for l in MAP:
    cnt += l.count("#")
FLAG = [[-1] * W for _ in range(H)]
FLAG[0][0] = 1
q = [(0, 0)]
d = [(1, 0), (0, 1), (-1, 0), (0, -1)]

while q:
    y, x = q.pop(0)
    for dy, dx in d:
        if 0 <= y + dy < H and 0 <= x + dx < W and FLAG[y + dy][x + dx] == -1 and MAP[y + dy][x + dx] == ".":
            FLAG[y + dy][x + dx] = FLAG[y][x] + 1
            q.append((y + dy, x + dx))

if FLAG[H - 1][W - 1] == -1:
    print(-1)
else:
    print(H * W - FLAG[H - 1][W - 1] - cnt)

#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
  return int(readline())
h,w = readInts()
block = [input() for _ in range(h)]

allcnt = 0
for i in range(w):
    for j in range(h):
        if block[j][i] == '.':
            allcnt += 1
INF = float('inf')
AR = [[INF] * w for _ in range(h)]
dy = [1,0,0,-1]
dx = [0,-1,1,0]
def bfs():
    d = deque()
    d.append([0,0])
    while d:
        y,x = d.popleft()
        if y == 0 and x == 0:
            AR[y][x] = 0
        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if (not 0 <= ny < h) or (not 0 <= nx < w):
                continue
            if AR[ny][nx] == INF and block[ny][nx] != '#':
                AR[ny][nx] = AR[y][x] + 1
                d.append([ny,nx])
bfs()
if AR[h-1][w-1] == INF:
    print((-1))
else:
    print((allcnt - (AR[h-1][w-1]+1))) # start地点の分


from collections import deque
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = sum([i.count("#") for i in s])
s = [["#"]*(w+2)] + [["#"]+i+["#"] for i in s] + [["#"]*(w+2)]
d = deque([[1, 1, 1]])
while len(d) > 0:
    x, y, cnt = d.popleft()
    if x == h and y == w:
        print(h*w-cnt-ans)
        return
    s[x][y] = "#"
    if s[x-1][y] == ".":
        d.append([x-1, y, cnt+1])
        s[x-1][y] = "#"
    if s[x+1][y] == ".":
        d.append([x+1, y, cnt+1])
        s[x+1][y] = "#"
    if s[x][y-1] == ".":
        d.append([x, y-1, cnt+1])
        s[x][y-1] = "#"
    if s[x][y+1] == ".":
        d.append([x, y+1, cnt+1])
        s[x][y+1] = "#"
print(-1)

H, W = map(int, input().split())
import numpy as np
Grid = np.array([[0 if x == '.' else -1 for x in input()] for _ in range(H)],dtype='int64')

def solveMase(Grid, start, goal):
    seen = {start}
    V = [start]
    while len(V) != 0:
        v = V.pop(0)
        if v == goal:
            return Grid[goal]

        y,x = v
        nV = []
        if x > 0: nV.append((y,x-1))
        if y > 0: nV.append((y-1,x))
        if x < W-1: nV.append((y,x+1))
        if y < H-1: nV.append((y+1,x))

        for nv in nV:
            if Grid[nv] == -1 or nv in seen:
                continue
            Grid[nv] = Grid[v] + 1
            V.append(nv)
            seen.add(nv)
    return 0

white = len(Grid[Grid == 0])-1
nes_white = solveMase(Grid, (0,0), (H-1,W-1))
if nes_white > 0:
    ans = white - nes_white
else:
    ans = -1
print(ans)

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

H,W = map(int,input().split())
sy, sx = 0,0
gy, gx = H-1,W-1
D = [list(input()) for i in range(H)]
Bs = 0
for i in range(H):
    Bs += D[i].count("#")

Q = deque()
Q.append((sy,sx))
dist = [[-1]*W for i in range(H)]
dist[sy][sx] = 0
dx = [1,0,-1,0]
dy = [0,-1,0,1]

while Q:
    x,y = Q.popleft()
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]
        if 0<=nx<=W-1 and 0<=ny<=H-1 and D[ny][nx]!="#" and dist[ny][nx] == -1:
            Q.append((nx,ny))
            dist[ny][nx] = dist[y][x]+1

print(H*W-Bs-1-dist[gy][gx] if dist[gy][gx]!=-1 else -1)

from collections import deque
h,w = map(int,input().split())
maze = [['#'] * (w+2) for i in range(h+2)]
wall = 0
for i in range(1,h+1):
    s = input()
    for j in range(1,w+1):
        if s[j-1] == '#':
            wall += 1
        maze[i][j] = s[j-1]
queue = deque([[1,1]])
maze[1][1] = 0
while queue:
    x,y = queue.popleft()
    if [x,y] != [h,w]:
        for n,m in ([0,-1],[0,1],[-1,0],[1,0]):
            new_h,new_w = x+n,y+m
            if maze[new_h][new_w] == '.':
                maze[new_h][new_w] = maze[x][y] + 1
                queue.append([new_h,new_w])
            elif maze[new_h][new_w] != "#":
                maze[new_h][new_w] = min(maze[new_h][new_w],maze[x][y]+1)
            else:
                pass
if maze[h][w] == '.' or maze[h][w] == '#':
    print(-1)
else:
    print(h*w-(maze[h][w]+1)-wall)

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

def get_next(x, y, costs, S, cost):
    ans = list()
    if x != 0 and costs[x-1][y] == -1 and S[x-1][y] == ".":
        ans.append([x-1, y])
        costs[x-1][y] = cost + 1

    if x != H-1 and costs[x+1][y] == -1 and S[x+1][y] == ".":
        ans.append([x+1, y])
        costs[x+1][y] = cost + 1

    if y != 0 and costs[x][y-1] == -1 and S[x][y-1] == ".":
        ans.append([x, y-1])
        costs[x][y-1] = cost + 1

    if y != W-1 and costs[x][y+1] == -1 and S[x][y+1] == ".":
        ans.append([x, y+1])
        costs[x][y+1] = cost + 1

    return ans

costs = [[-1 for _ in range(W)] for _ in range(H)]
costs[0][0] = 0
q = deque()
q.append([0, 0])
while len(q) and costs[H-1][W-1] == -1:
    now = q.popleft()
    nxt = get_next(now[0], now[1], costs, S, costs[now[0]][now[1]])
    for dot in nxt:
        q.append([dot[0], dot[1]])
    
fin_cost = costs[H-1][W-1]
if fin_cost == -1:
    print((-1))
else:
    w_cnt = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == ".":
                w_cnt += 1
    print((w_cnt - fin_cost - 1))


import sys
from collections import deque


def IN_I(): return int(sys.stdin.readline().rstrip())
def IN_LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def IN_S(): return sys.stdin.readline().rstrip()
def IN_LS(): return list(sys.stdin.readline().rstrip().split())


H, W = IN_LI()
s = [IN_S() for _ in range(H)]

dh = [-1, 0, 1, 0]
dw = [0, -1, 0, 1]

dist = [[-1] * W for j in range(H)]
dist[0][0] = 0

q = deque()
q.append([0, 0])

while q:
    now = q.popleft()
    now_h = now[0]
    now_w = now[1]

    for i in range(4):
        next_h = now_h + dh[i]
        next_w = now_w + dw[i]

        if not (0 <= next_h < H and 0 <= next_w < W):
            continue
        if s[next_h][next_w] == '#':
            continue

        if dist[next_h][next_w] == -1:
            q.append([next_h, next_w])
            dist[next_h][next_w] = dist[now_h][now_w] + 1

if dist[-1][-1] == -1:
    print((-1))
    return

black = sum([i.count('#') for i in s])
ans = (H * W - black) - (dist[-1][-1] + 1)
print(ans)


def abc088d_grid_repainting():
    import heapq
    h, w = map(int, input().split())
    maze = []
    cnt = h * w
    for _ in range(h):
        s = input()
        maze.append(s)
        cnt -= s.count('#')
    q = [(1, 0, 0)]
    heapq.heapify(q)
    check = [[False] * w for _ in range(h)]
    while len(q) != 0:
        dis, x, y = heapq.heappop(q)
        if (x, y) == (h - 1, w - 1):
            print(cnt - dis)
            return
        for dx, dy in zip([0, 0, 1, -1], [1, -1, 0, 0]):
            if 0 <= x + dx < h and 0 <= y + dy < w and maze[x + dx][y + dy] != '#' and not check[x + dx][y + dy]:
                check[x + dx][y + dy] = True
                heapq.heappush(q, (dis+1, x + dx, y + dy))
    print('-1')
abc088d_grid_repainting()

h,w = map(int,input().split())
w_cnt = 0
L = []
for i in range(h):
    s = input()
    w_cnt += s.count(".")
    L.append(s)

from collections import deque
visited = [[0]*w for _ in range(h)]

q = deque([[0,0]])
li = [[1,0],[0,1],[-1,0],[0,-1]]

while q:
    y,x = q.popleft()
    for dy,dx in li:
        ny,nx = y+dy,x+dx
        if ny < 0 or ny >= h or nx < 0 or nx >= w or visited[ny][nx] > 0 or L[ny][nx] == "#" :
            continue
        visited[ny][nx] = visited[y][x] + 1
        if [ny,nx] == [h-1,w-1]:
            print(w_cnt-visited[ny][nx]-1)
            return
        q.append([ny,nx])
        
print(-1)

from collections import deque


def bfs():
    d = [[float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


h, w = map(int, input().split())
maze = [list(input()) for i in range(h)]
sx, sy = 0, 0
gx, gy = h - 1, w - 1

# 白いマスを数える
white = 0
for i in range(h):
    for j in range(w):
        if maze[i][j] == ".":
            white += 1

res = bfs()
if 0 < res < float("inf"):
    # 白いマスの数から最短経路でかかるコスト分を引く
    # ゴールを黒いマスに変えることはできないためその分も引く
    print(white - res - 1)
else:
    print(-1)

from collections import deque
h,w=list(map(int,input().split()))
num=[list(input()) for _ in range(h)]
seen=[[False]*w for _ in range(h)]
queue=deque()
queue.append([0,0])
ans=[[0]*w for _ in range(h)]
seen[0][0]=True
for i in range(h*w*100):
    if len(queue)==0:
        break
    cnt=queue.popleft()
    if num[max(0,cnt[0]-1)][cnt[1]]=="." and seen[max(0,cnt[0]-1)][cnt[1]]==False:
        queue.append([cnt[0]-1,cnt[1]])
        seen[max(0,cnt[0]-1)][cnt[1]]=True
        ans[max(0,cnt[0]-1)][cnt[1]]=ans[cnt[0]][cnt[1]]+1
    if num[min(h-1,cnt[0]+1)][cnt[1]]=="." and seen[min(h-1,cnt[0]+1)][cnt[1]]==False:
        queue.append([cnt[0]+1,cnt[1]])
        seen[min(h-1,cnt[0]+1)][cnt[1]]=True
        ans[min(h-1,cnt[0]+1)][cnt[1]]=ans[cnt[0]][cnt[1]]+1
    if num[cnt[0]][max(cnt[1]-1,0)]=="." and seen[cnt[0]][max(cnt[1]-1,0)]==False:
        queue.append([cnt[0],cnt[1]-1])
        seen[cnt[0]][max(cnt[1]-1,0)]=True
        ans[cnt[0]][max(cnt[1]-1,0)]=ans[cnt[0]][cnt[1]]+1
    if num[cnt[0]][min(w-1,cnt[1]+1)]=="." and seen[cnt[0]][min(w-1,cnt[1]+1)]==False:
        queue.append([cnt[0],cnt[1]+1])
        seen[cnt[0]][min(w-1,cnt[1]+1)]=True
        ans[cnt[0]][min(w-1,cnt[1]+1)]=ans[cnt[0]][cnt[1]]+1
if seen[-1][-1]==False:
    print((-1))
else:
    cnt3=0
    for i in range(h):
        cnt3+=num[i].count(".")
    print((cnt3-ans[-1][-1]-1))


from collections import deque


def bfs(start, goal):
    q = deque([[start]])
    visited = set()
    while q:
        path = q.popleft()
        i, j = path[-1]
        if (i, j) == goal:
            return path
        for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ni, nj = i + di, j + dj
            if not (0 <= ni < H and 0 <= nj < W and field[ni][nj] == "."):
                continue
            if (ni, nj) not in visited:
                q.append(path + [(ni, nj)])
                visited.add((ni, nj))
    return []


H, W = list(map(int, input().split()))
field = [input() for _ in range(H)]
shortest_path = bfs((0, 0), (H - 1, W - 1))
if shortest_path:
    print((sum(v == "." for row in field for v in row) - len(shortest_path)))
else:
    print((-1))


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

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

while Q:
    h, w = Q.popleft()

    for nh, nw in [[h+1,w],[h-1,w],[h,w-1],[h,w+1]]:
        if 0 <= nh < H and 0 <= nw < W and S[nh][nw] == "." and dist[nh][nw] == -1:
            dist[nh][nw] = dist[h][w] + 1
            Q.append([nh,nw])

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








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


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

S=[input() for i in range(H)]
S_check = [[False]*W for _ in range(H)]

start = (0, 0, 1)
goal = (H-1, W-1)

Q = []
Q.append(start)

step = 0
is_reached = False

while Q:
    current = Q.pop(0)
    step = current[2]
    
    for i in range(4):
        next_pos = (current[0]+dx[i], current[1]+dy[i])

        if next_pos[0] < 0 or next_pos[0] > H-1 or next_pos[1] < 0 or next_pos[1] > W-1:
            continue
        elif S_check[next_pos[0]][ next_pos[1]]:
            continue
        elif next_pos == goal:
            is_reached = True
            break
        elif S[next_pos[0]][ next_pos[1]] == "#":
            continue
        else:
            S_check[next_pos[0]][ next_pos[1]] = True
            Q.append((next_pos[0], next_pos[1], step+1))

    if is_reached:
        break

cnt = 0
for i in range(H):
    for j in range(W):
       if S[i][j] == "#":
           cnt += 1
ans = -1
if is_reached:
    ans = H * W - step -1 - cnt
print(ans)




from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
dots = sum([v.count('.') for v in s]) # count the number of all dots('.')

visited = [[-1] * w for _ in range(h)] 
# visited shows the number of dots in the path up to there

q = deque([[0, 0]])
visited[0][0] = 1

while q:
    y, x = q.popleft()
    if y == h - 1 and x == w - 1:
        break
    for i, j in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        ny, nx = y + i, x + j
        if (not 0 <= ny < h) or (not 0 <= nx < w) or s[ny][nx] == '#':
            continue
        elif visited[ny][nx] == -1:
            visited[ny][nx] = visited[y][x] + 1
            q.append([ny, nx])
if visited[h - 1][w - 1] != -1:
    # in the case one can reach the goal
    print(dots - visited[h - 1][w - 1])
else: # otherwise
    print(-1)

H, W = list(map(int, input().split()))
grid = [input() for _ in range(H)]
checked = [[False]*W for _ in range(H)]


def solve(arr, count):
    next_arr = set()
    count += 1
    for a in arr:
        y, x = a[0], a[1]
        checked[y][x] = True
        if y == H-1 and x == W-1:
            return count
        if y < H-1:
            if not checked[y+1][x] and grid[y+1][x] == '.':
                next_arr.add((y+1, x))
        if 0 < y:
            if not checked[y-1][x] and grid[y-1][x] == '.':
                next_arr.add((y-1, x))
        if x < W-1:
            if not checked[y][x+1] and grid[y][x+1] == '.':
                next_arr.add((y, x+1))
        if 0 < x:
            if not checked[y][x-1] and grid[y][x-1] == '.':
                next_arr.add((y, x-1))
    if len(next_arr) == 0:
        return -1
    return solve(next_arr, count)


min_steps = solve([(0, 0)], 0)
if min_steps == -1:
    print((-1))
else:
    w_c = 0
    for i in grid:
        w_c += i.count('.')
    print((w_c - min_steps))


import sys
read = sys.stdin.read
from collections import deque
def main():
    h, w = map(int, input().split())
    wall_cnt = 0
    gg = list()
    gg.append([1] * (w + 2))
    for _ in range(h):
        row = tuple(input())
        wall_cnt += row.count('#')
        gg.append([1] + [c == '#' for c in row] + [1])
    gg.append([1] * (w + 2))

    g2 = [[0] * (w + 2) for _ in range(h + 2)]
    g2[1][1] = 1
    vs = deque()
    vs.append((1, 1))
    move_y = (0, 1, 0, -1)
    move_x = (1, 0, -1, 0)
    while vs:
        y, x = vs.popleft()
        ys = [y + i for i in move_y]
        xs = [x + i for i in move_x]
        for yse, xse in zip(ys, xs):
            if not gg[yse][xse]:
                vs.append((yse, xse))
                gg[yse][xse] = 1
                g2[yse][xse] = g2[y][x] + 1
    if g2[h][w] == 0:
        print(-1)
    else:
        ans = (h * w) - g2[h][w] - wall_cnt
        print(ans)

def __starting_point():
    main()
__starting_point()

from collections import deque

inf = 10**10

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

length = [[inf for j in range(w)]for i in range(h)]
visited = [[0 for j in range(w)]for i in range(h)]

move = [[-1,0],[1,0],[0,-1],[0,1]]

que = deque([])
que.append([0,0])
length[0][0] = 1 # １スタート
visited[0][0] = 1

white = 0

for i in range(h):
    white += field[i].count(".")

while que:
    y,x = que.popleft()

    for i,j in move:
        ny,nx = y+i,x+j

        if ny < 0 or ny >= h or nx < 0 or nx >= w:
            continue
        elif field[ny][nx] == "#":
            continue
        elif visited[ny][nx] == 1:
            continue
        
        visited[ny][nx] = 1
        que.append([ny,nx])
        length[ny][nx] = length[y][x] + 1

if length[h-1][w-1] == inf:
    print(-1)
else:
    print(white-length[h-1][w-1]) # 白の総数から最小距離分引く

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

matrix = [list('#' * (w + 2))]
count_sharp = 0
for _ in range(h):
    C = list(input())
    count_sharp += C.count('#')
    matrix.append(['#'] + C + ['#'])
matrix.append(list('#') * (w + 2))

B = [[] for _ in range(10000)]


for i in range(h+2):
    for j in range(w+2):
        if matrix[i][j] == '.':
            if matrix[i-1][j] == '.':
                B[100*i+j].append(100*(i-1) + j)
            if matrix[i][j-1] == '.':
                B[100*i+j].append(100*i + j - 1)
            if matrix[i][j+1] == '.':
                B[100*i+j].append(100*i + j + 1)
            if matrix[i+1][j] == '.':
                B[100*i+j].append(100*(i+1) + j)

# print(matrix)
def solver(matrix, h, w, count_):
    path = [10000000] * 10000
    depth = 0
    path[101] = 0
    reached = [101]
    stack = []
    stack.append(101)
    while len(stack) > 0:
        depth += 1
        for _ in range(len(stack)):
            val = stack.pop(0)
            for j in matrix[val]:
                if j not in set(reached):
                    path[j] = min(depth, path[j])
                    reached.append(j)
                    stack.append(j)

    if path[h*100 + w] == 10000000:
        print((-1))
    else:
        print((h * w - path[h*100+w] - 1 - count_))
solver(B, h, w, count_sharp)


from collections import deque

H, W = map(int, input().split())
S = [input() for _ in range(H)]

s = 0
for c in S:
    s += c.count('.')

que = deque()
dist = [[-1 for j in range(W)] for i in range(H)]
dist[0][0] = 0
st = (0, 0)
que.append(st)
dydx = [(1, 0), (0, 1), (-1, 0), (0, -1)]

while que:
    p, q = que.popleft()

    for dy, dx in dydx:
        if 0 <= p+dy and p+dy < H and 0 <= q+dx and q+dx < W:
            if dist[p+dy][q+dx] != -1 or S[p+dy][q+dx] != '.':
                continue

            dist[p+dy][q+dx] = dist[p][q] + 1
            que.append((p+dy, q+dx))

if dist[H-1][W-1] == -1:
    print(-1)
else:
    print(s-dist[H-1][W-1]-1)

from collections import deque
H,W=map(int,input().split())
mp=[['#']*(W+2)]
count=0
for _ in range(H):
    l=list(input())
    mp.append(['#']+l+['#'])
    count+=l.count('.')
mp.append(['#']*(W+2))

dist=[[-1]*(W+2)for _ in range(H+2)]
Q=deque()
Q.append((1,1))
dist[1][1]=1
f=False

while Q:
    y,x=Q.popleft()
    if (y,x)==(H,W):
        f=True
        break
    for dy,dx in [(1,0),(-1,0),(0,1),(0,-1)]:
        ny=y+dy
        nx=x+dx
        if 0<=ny<H+2 and 0<=nx<W+2:
            if mp[ny][nx]=='.' and dist[ny][nx]==-1:
                Q.append((ny,nx))
                dist[ny][nx]=dist[y][x]+1

if f:
    print(count-dist[H][W])
else:
    print(-1)

def getval():
    h,w = map(int,input().split())
    s = [input() for i in range(h)]
    return h,w,s

def main(h,w,s):
    #Find numbers of whites 
    whites = 0
    for i in s:
        for j in range(w):
            if i[j]==".":
                whites += 1

    #Find the shortest path
    d = [[-1 for i in range(w)] for j in range(h)]
    q = [[0,0,0]]
    d[0][0] = 0
    while q:
        idx = q.pop(0)
        adj = [[idx[0]+1,idx[1],idx[2]+1],[idx[0]-1,idx[1],idx[2]+1],[idx[0],idx[1]+1,idx[2]+1],[idx[0],idx[1]-1,idx[2]+1]]
        for i in adj:
            if i[0]<0 or i[1]<0 or i[0]>=h or i[1]>=w:
                continue
            if d[i[0]][i[1]]!=-1:
                continue
            if s[i[0]][i[1]]=="#":
                continue
            q.append(i)
            d[i[0]][i[1]] = i[2]

    dist = d[h-1][w-1]
    
    #Compute the score
    if dist==-1:
        print(-1)
    else:
        print(whites-dist-1)

def __starting_point():
    h,w,s = getval()
    main(h,w,s)
__starting_point()

from collections import deque

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

sx,sy=0,0
gx,gy=H-1,W-1

def bfs():
    d=[[float('inf')]*W for i in range(H)]
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]

    que=deque([])
    que.append((sx,sy))
    d[sx][sy]=0

    while que:
        p=que.popleft()
        if p[0]==gx and p[1]==gy:
            break
        for i in range(4):
            nx=p[0]+dx[i]
            ny=p[1]+dy[i]
            if 0<=nx<H and 0<=ny<W and maze[nx][ny]!="#" and d[nx][ny]==float("inf"):
                que.append((nx,ny))
                d[nx][ny]=d[p[0]][p[1]]+1
        
    return d[gx][gy]

ans=0
cnt=0
res=bfs()
for i in range(H):
    for j in range(W):
        if maze[i][j]=='.':
            cnt+=1
if res==float('inf'):
    ans=-1
else:
    ans=cnt-res-1
print(ans)

H, W = map(int, input().split())
G = [input() for _ in range(H)]
sy, sx, gy, gx = 0, 0, H - 1, W - 1
seen = [[-1] * W for _ in range(H)]

if G[sy][sx] == '#' or G[gy][gx] == '#':
    print(-1)
    return

from collections import deque
que = deque()
que.append([sy, sx])
seen[sy][sx] = 0
while que:
    y, x = que.popleft()
    for d in [-1, 0], [1, 0], [0, -1], [0, 1]:
        dy = y + d[0]
        dx = x + d[1]
        if dy < 0 or H <= dy or dx < 0 or W <= dx:
            continue
        if G[dy][dx] == '#':
            continue
        if seen[dy][dx] > -1:
            continue
        que.append([dy, dx])
        seen[dy][dx] = seen[y][x] + 1

count = 0
bunpu = [0] * (H * W + 1)
if seen[gy][gx] == -1:
    print(-1)
    return
else:
    all = H * W
    black = 0
    for i in range(H):
        for j in range(W):
            if G[i][j] == '#':
                black += 1
    #start point = 0,0 
    ans = all - black - seen[gy][gx] - 1
print(ans)

from collections import deque

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

M = []

white = 0
for _ in range(H):
    M.append(input())
    white += M[-1].count('.')

q = deque()
q.append((0, 0))
visit = [0] * (H * W)
visit[0] = 1

def bfs():
    while q:
        x, y = q.popleft()
        for (dx, dy) in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
            x2 = x + dx
            y2 = y + dy

            if x2 < 0 or x2 > W - 1: continue
            if y2 < 0 or y2 > H - 1: continue

            if visit[y2 * W + x2]: continue
            if M[y2][x2] == '#': continue

            visit[y2 * W + x2] = visit[y * W + x] + 1

            if y2 == H - 1 and x2 == W - 1:
                return visit[y2 * W + x2]

            q.append((x2, y2))

steps = bfs()
ans = -1
if steps:
    ans = white - steps

print(ans)

H,W=list(map(int,input().split()))
sq=[list(input()) for i in range(H)]
ans=False
c=H*W
pos=[[0,0,0]]

while pos!=[]:
    y,x,depth=pos.pop(0)

    if x==W-1 and y==H-1:
        ans=True
        break

    if 0<=x+1<=W-1:
        if sq[y][x+1]==".":
            pos.append([y,x+1,depth+1])
            sq[y][x+1]="!"
            
    if 0<=x-1<=W-1:
        if sq[y][x-1]==".":
            pos.append([y,x-1,depth+1])
            sq[y][x-1]="!"
            
    if 0<=y+1<=H-1:
        if sq[y+1][x]==".":
            pos.append([y+1,x,depth+1])
            sq[y+1][x]="!"
            
    if 0<=y-1<=H-1:
        if sq[y-1][x]==".":
            pos.append([y-1,x,depth+1])
            sq[y-1][x]="!"
    
    
for j in range(H):
    for k in range(W):
        if sq[j][k]=="#":
            c-=1

if ans==True:
    print((c-depth-1))
else:
    print((-1))


# config
from collections import deque
import sys
sys.setrecursionlimit(10**6)

# input
H, W = map(int, input().split())
maze = []
for _ in range(H):
    maze.append(input())


# スタートとゴール
si, sj = 0, 0
gi, gj = H-1, W-1

# 4近傍ベクトル↓→↑←
didj = [(1,0), (0,1), (-1, 0), (0, -1)]

def bfs(H, W, blocker="X"):
    # queが空になったら探索終了
    while que != deque():
        i, j = que.popleft()
        for di, dj in didj:
            ni = i + di
            nj = j + dj
            # 遷移先ninjが不正でないか・壁でないか・まだ訪れたことがないかをチェック
            if 0 <= ni and ni < H and 0 <= nj and nj < W and maze[ni][nj] != blocker and d[ni][nj] == INF:
                d[ni][nj] = d[i][j] + 1
                que.append((ni, nj))
    return

INF = H*W*10
d = [[INF for x in range(W)] for x in range(H)]
d[si][sj] = 0

# 最短経路探索開始
que = deque()
que.append((si, sj))
bfs(H,W, blocker="#")

# たどり着くとこができなかった場合
if d[gi][gj] == INF:
    print(-1)

# スコア出力
else:
    blc = 0
    for h in maze:
        for l in h:
            if l == "#":
                blc += 1
    score = H*W - blc - d[gi][gj] - 1 # 全マス数 - 壁の数 - 最短経路分 - スタートマスの分
    print(score)

t,*g=open(0);h,w=list(map(int,t.split()));v=[[0]*w for _ in range(h)];v[0][0]=1;q=[(0,0)]
while q:
	a,b=q.pop(0)
	for c,d in((-1,0),(0,-1),(1,0),(0,1)):
		x=a+c;y=b+d
		if w>x>=0<=y<h and v[y][x]<1 and g[y][x]==".":q+=[(x,y)];v[y][x]=v[b][a]+1
t=v[-1][-1];print(((-1,sum(c.count(".")for c in g)-t)[t>0]))


import collections
import math


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

c=[list(str(input())) for i in range(H)]
#1<=sy<=R
d=[[0 for j in range(W)]for i in range(H)]
inf=10**6
ans=0
for i in range(H):
    for j in range(W):
        if c[i][j]=='#':
            d[i][j]=-1
        else:
            d[i][j]=inf
            ans+=1


d[0][0]=0
queue=collections.deque([[0,0]])
gy,gx=H-1,W-1

moves=[[1,0],[-1,0],[0,1],[0,-1]]

flag=False
while len(queue)>0:
    now=queue.popleft()
    for i in range(4):
        ny=now[0]+moves[i][0]
        nx=now[1]+moves[i][1]
        
        if 0<=ny and ny<H and 0<=nx and nx<W and c[ny][nx]=='.' and d[ny][nx]==inf:
            d[ny][nx]=d[now[0]][now[1]]+1
            queue.append([ny,nx])
            if ny==gy and nx==gx:
                print(ans-d[ny][nx]-1)
                return
print(-1)     

# 白だけ動いて(0,0)から(H-1, W-1)に行く
# その際にできるだけ黒を増やす
# 全体の白から最短距離を除いたものが答え

from collections import deque


H, W = list(map(int, input().split()))
grid = [list(input()) for _ in range(H)] # .は白、#は黒
visited = [[-1] * W for _ in range(H)]
moves = [(1, 0), (0, 1), (-1, 0), (0, -1)]

q = deque()
q.append((0, 0))
visited[0][0] = 0

while q:
    y, x = q.popleft()

    for dy, dx in moves:
        moved_y = y + dy
        moved_x = x + dx

        if moved_y < 0 or H-1 < moved_y or moved_x < 0 or W-1 < moved_x:
            continue
        if grid[moved_y][moved_x] == '#':
            continue
        if visited[moved_y][moved_x] != -1:
            continue

        visited[moved_y][moved_x] = visited[y][x] + 1
        q.append((moved_y, moved_x))

min_route = visited[H-1][W-1]

if min_route == -1:
    answer = -1
else:
    total_white = 0
    for row in grid:
        total_white += row.count('.')

    answer = total_white - min_route - 1

print(answer)




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

sq=[list(input()) for i in range(H)]

pos=[[0,0,0]]
g=True

while pos!=[]:
    y,x,depth=pos.pop(0)

    if y==H-1 and x==W-1:
        g=False
        break
    
    if x-1>=0:
        if sq[y][x-1]==".":
            pos.append([y,x-1,depth+1])
            sq[y][x-1]="!"
    if x+1<=W-1:
        if sq[y][x+1]==".":
            pos.append([y,x+1,depth+1])
            sq[y][x+1]="!"
    if y-1>=0:
        if sq[y-1][x]==".":
            pos.append([y-1,x,depth+1])
            sq[y-1][x]="!"
    if y+1<=H-1:
        if sq[y+1][x]==".":
            pos.append([y+1,x,depth+1])

if g==True:
    print((-1))
else:
    temp=0
    for k in range(H):
        for m in range(W):
            if sq[k][m]=="#":
                temp+=1


    print((H*W-temp-depth-1))


a, b = map(int, input().split())
G = []
white_num = 0
for i in range(a):
    s = list(input())
    white_num += s.count('.')
    G.append(s)
from collections import deque
def mazesearch(G, initial_h, initial_w, target_h, target_w):
    '''
    G is for example:
        G = [[1,0,1,1,1,1],
            [1,0,1,0,1,0],
            [1,0,1,0,1,1],
            [1,1,1,0,1,1]]
    '''
    steps = 0
    BLOCKED, ALLOWED   = '#', '.'
    UNVISITED, VISITED = 0, 1
    directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
    if G[initial_h][initial_w] == BLOCKED:
        return -1
    height, width = len(G), len(G[0])
    is_visited = [[UNVISITED for w in range(width)] for h in range(height)]
    is_visited[initial_h][initial_w] = VISITED
    queue = deque([(initial_h, initial_w, steps)])
    while queue:
        h, w, steps = queue.popleft()
        if h == target_h and w == target_w:
            return steps
        for dh, dw in directions:
            new_h = h + dh
            new_w = w + dw
            if not (0 <= new_h < height and 0 <= new_w < width):
                continue
            if G[new_h][new_w] == ALLOWED and is_visited[new_h][new_w] == UNVISITED:
                queue.append((new_h, new_w, steps + 1))
                is_visited[new_h][new_w] = VISITED
    return -1
steps = mazesearch(G, 0, 0, a-1, b-1)
if steps == -1:
    print(-1, flush=True)
else:
    print(white_num - steps - 1, flush=True)


from collections import deque
import copy
H,W = map(int, input().split())
s=[list(input()) for i in range(H)]
#H,W=3,3
#s=[['.', '.', '#'], ['#', '.', '.'], ['.', '.', '.']]

ss=copy.deepcopy(s)
q=deque([[0,0]])#(H,W)
ss[0][0]=0
move=[[1,0],[0,1],[0,-1],[-1,0]]
num=0
t=False
while q:
    num+=1
    for i in range(len(q)):
        b=q.popleft()
        #print(b)
        if b==[H-1,W-1]:
            t=True
            num-=1
            break
        for m in move:
         #  print(m)
            if 0<=b[0]+m[0]<=H-1 and 0<=b[1]+m[1]<=W-1 and ss[b[0]+m[0]][b[1]+m[1]]=='.':
                ss[b[0]+m[0]][b[1]+m[1]]=num
                q.append([b[0]+m[0],b[1]+m[1]])
    else:
        continue
    break
if not t :
    print('-1')
else:
    x=num
    b=H-1,W-1
    ss[b[0]][b[1]]='#'
    while x!=0:
        for m in move:
            if 0<=b[0]+m[0]<=H-1 and 0<=b[1]+m[1]<=W-1 and ss[b[0]+m[0]][b[1]+m[1]]==x-1:
                x=x-1
                ss[b[0]+m[0]][b[1]+m[1]]='#'
                b=b[0]+m[0],b[1]+m[1]
                break
    ans=0
    for h in range(H):
        for w in range(W):
            if ss[h][w]!='#':
                ans+=1
    print(ans)

from collections import deque

H, W = map(int, input().split())
M = []
M = ['#' * (W+2)]

num_blk = 0

for h in range(H):
    inp = input() 
    M.append('#' + inp + '#')
    num_blk += inp.count('#')
M.append('#' * (W+2))

sy, sx = 1, 1
gy, gx = H, W

T = [[float('inf')] * (W + 2) for _ in range(H + 2)]
T[sy][sx] = 0

que = deque([(sy, sx)])
while len(que) > 0:
    y, x = que.popleft()
    for a, b in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        if M[y+b][x+a] != '#' and T[y+b][x+a] == float('inf'):
            T[y+b][x+a] = T[y][x]+1
            que.append((y+b, x+a))
    if y == gy and x == gx:
        break
if T[gy][gx] == float('inf'):
    print(-1)
else:
    print(H * W - num_blk - T[gy][gx] - 1)

from collections import deque
from collections import Counter
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
t = [[-1]*W for _ in range(H)]
q = deque([[0,0]])
t[0][0] = 0
while len(q) > 0:
  qq = q.popleft()
  dh = [-1,0,1,0]
  dw = [0,1,0,-1]
  for i in range(4):
    h = qq[0] + dh[i]
    w = qq[1] + dw[i]
    if 0 <= h < H and 0 <= w < W:
      if s[h][w] == "#" or t[h][w] != -1: continue
      t[h][w] = t[qq[0]][qq[1]] + 1
      q.append([h,w])

X = 0
for i in range(H):
  c = Counter(s[i])
  X += c["."]
if t[H-1][W-1] == -1:
  print(-1)
else:
  print(X-1-t[H-1][W-1])

import sys
from collections import Counter
from collections import deque

input = sys.stdin.readline

def main():
    H, W = list(map(int, input().split()))
    grid = []
    wh = 0
    for _ in range(H):
        tmp = list(input()[:-1])
        wh += Counter(tmp)['.']
        grid.append(tmp)
    check = [[0]*W for _ in range(H)]
        
    # digtmp
    digtmp = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    #digtmp = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)]
    
    # BFS
    # please prefer objects:
    #  H: height.
    #  W: width
    #  field: maze field made of '.', '#'.
    #  check: check field
    que = deque([(0, 0)])
    check[0][0] = 1
    while True:
        a, b = que.popleft()
        for dx, dy in digtmp:
            x = a + dx
            y = b + dy
            if not (0 <= x < H and 0 <= y < W):
                continue
            if check[x][y] != 0 or grid[x][y] == '#':
                continue
            check[x][y] = check[a][b] + 1
            que.append((x, y))
        if len(que) == 0:
            break
    
    if check[H-1][W-1] == 0:
        print((-1))
    else:
        print((wh - check[H-1][W-1]))

def __starting_point():
    main()

__starting_point()

import numpy as np

h, w, *s = open(0).read().split()
h = int(h)
w = int(w)
all = sum(t.count('#') for t in s)

inf = 1 << 30
d = np.full((h + 1, w + 1), inf, dtype=np.int)

d[0][0] = 0
q = [(0, 0)]
for v in q:
    for nv in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
        ny = v[0] + nv[0]
        nx = v[1] + nv[1]
        if 0 <= nx < w and 0 <= ny < h and d[ny][nx] == inf and s[ny][nx] == '.':
            d[ny][nx] = d[v[0]][v[1]] + 1
            q.append((ny, nx))

if d[h - 1][w - 1] == inf:
    print((-1))
else:
    print((h * w - (d[h - 1][w - 1] + 1) - all))


import sys
import operator
from collections import deque,Counter

input=sys.stdin.readline
h,w=map(int,input().split())
sx,sy=0,0
#print(sx,sy)
gx,gy=h-1,w-1
#print(gx,gy)
s=[list(input()) for _ in range(h)]
#白のブロックを数える
c=[]
for a in s:
  c+=a
c=Counter(c)
#print(c["."])
white=c["."]
#移動先4方向
dx = [1, 0, -1,  0]
dy = [0, 1,  0, -1]
#訪問リストを作る
visited=[[-1]*w for _ in range(h)]

def bfs(x,y):
  queue=deque([[x,y]])
  visited[x][y]=0
  while queue:
    
    x,y=queue.popleft()
    if [x,y]==[gx,gy]:
      return visited[x][y]
    for i in range(4):
      nx,ny=x+dx[i],y+dy[i]
      if nx>=0 and nx<h and ny>=0 and ny<w and s[nx][ny]=="." and visited[nx][ny]==-1:
        visited[nx][ny]=visited[x][y]+1
        queue.append([nx,ny])
        #print(queue)
    
bfs(sx,sy)
#print(*visited,sep="\n")
print(white-visited[gx][gy]-1 if visited[gx][gy]!=-1 else -1)

from collections import deque

def bfs(sy,sx):
  q = deque([[sy,sx]])
  d[sy][sx] = 0
  while q:
    y,x = q.popleft()
    for i,j in [(-1,0),(1,0),(0,-1),(0,1)]:
      dy,dx = y+i,x+j
      if dy < 0 or h <= dy: continue
      elif dx < 0 or w <= dx: continue
      elif s[dy][dx] == "#": continue
      elif d[dy][dx] != -1: continue
      d[dy][dx] = d[y][x]+1
      q.append([dy,dx])

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

if s[0][0] == "#" or s[h-1][w-1] == "#":
  print(-1)
  return

d = [[-1]*w for _ in range(h)]
bfs(0,0)
if d[h-1][w-1] == -1: print(-1)
else:
  t = 0
  for i in range(h): t += s[i].count("#")
  print(h*w-t-(d[h-1][w-1]+1))

#!/usr/bin/env python
# coding: utf-8

# In[47]:


from collections import deque


# In[50]:


H,W = list(map(int, input().split()))
grid = [list("#"*(W+2))]
b_cnt = 0
for _ in range(H):
    tmp = list(input())
    grid.append(["#"]+tmp+["#"])
grid.append(list("#"*(W+2)))


# In[52]:


grid[1][1] = 1
q = deque([[1,1]])
move = [
    [1,0],[-1,0],[0,1],[0,-1]
]
while q:
    x,y = q.popleft()
    for dx,dy in move:
        if grid[x+dx][y+dy] == ".":
            grid[x+dx][y+dy] = grid[x][y]+1
            q.append([x+dx,y+dy])
if grid[H][W] == ".":
    print((-1))
else:
    print(((H+2)*(W+2) - sum(g.count("#") for g in grid) - grid[H][W]))


# In[ ]:






from collections import deque

H, W = map(int, input().split())
w = "#"*(W+2)
white = 0
S = [w]
for _ in range(H):
    wwww = input()
    white += wwww.count(".")
    S.append("#"+wwww+"#")
S.append(w)

m = [[10**10]*(W+2) for _ in range(H+2)]

q = deque([[1, 1]])
d = ((-1, 0), (0, -1), (0, 1), (1, 0))

m[1][1] = 0

while q:
    y, x = q.popleft()
    p = m[y][x]
    for dx, dy in d:
        xx = x + dx
        yy = y + dy
        if S[yy][xx] == "#":
            continue
        if m[yy][xx] > p+1:
            m[yy][xx] = p+1
            q.append([yy, xx])

if m[H][W] == 10**10:
    print(-1)
else:
    print(white-m[H][W]-1)

from collections import deque

inf = 10**10

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

length = [[inf for j in range(w)]for i in range(h)]
visited = [[0 for j in range(w)]for i in range(h)]

move = [[-1,0],[1,0],[0,-1],[0,1]]

que = deque([])
que.append([0,0])
length[0][0] = 0
visited[0][0] = 1

white = 0

for i in range(h):
    white += field[i].count(".")

while que:
    y,x = que.popleft()

    for i,j in move:
        ny,nx = y+i,x+j

        if ny < 0 or ny >= h or nx < 0 or nx >= w:
            continue
        elif field[ny][nx] == "#":
            continue
        elif visited[ny][nx] == 1:
            continue
        
        visited[ny][nx] = 1
        que.append([ny,nx])
        length[ny][nx] = length[y][x] + 1

if length[h-1][w-1] == inf:
    print(-1)
else:
    print(white-(length[h-1][w-1]+1))

from collections import deque

H, W = [int(x) for x in input().split()]
board = []
for _ in range(H):
    board.append(input())

white = sum([board[h].count('.') for h in range(H)])

dist = {(x, y):white + 1 for x in range(W) for y in range(H)}
q = deque([(0, 0)])
dist[(0, 0)] = 1
while q:
    x, y = q.popleft()
    for d in range(4):
        nx, ny = x + int(((1j)**d).real), y + int(((1j)**d).imag)
        if nx < 0 or W <= nx or ny < 0 or H <= ny:
            continue
        if board[ny][nx] == '#':
            continue
        if dist[(nx, ny)] <= white:
            continue
        dist[(nx, ny)] = dist[(x, y)] + 1
        q.append((nx, ny))

lenofpath = dist[(W - 1, H - 1)]
ans = white - lenofpath
print(ans)

#!/usr/bin/env python3
def main():
    from collections import deque

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

    move = ((0, 1), (0, -1), (1, 0), (-1, 0))
    distance = [[1] * W for _ in range(H)]
    queue = deque([(0, 0)])
    while queue:
        y, x = queue.popleft()
        if y == H - 1 and x == W - 1:
            break
        for dy, dx in move:
            ny = y + dy
            nx = x + dx
            if (1
                    and 0 <= ny < H
                    and 0 <= nx < W
                    and distance[ny][nx] == 1
                    and S[ny][nx] == '.'):
                queue.append((ny, nx))
                distance[ny][nx] = distance[y][x] + 1
    if distance[H - 1][W - 1] == 1:
        print((-1))
    else:
        print((num_path - distance[H - 1][W - 1]))


def __starting_point():
    main()

__starting_point()

import sys

from collections import deque


def main():
    def input(): return sys.stdin.readline()[:-1]
    H, W = map(int, input().split())

    graph = [input() for _ in range(H)]

    dist = [[-1] * W for _ in range(H)]
    queue = deque()

    H -= 1
    W -= 1
    
    # initialize
    queue.append((0, 0))
    dist[0][0] = 0
    cnt = 0
    for g in graph:
        cnt += g.count(".")

    while queue:
        vx, vy = queue.popleft()

        if (vx, vy) == (W, H):
            break

        dxdy = [(1,0), (0, 1), (-1, 0), (0, -1)]
        for dx, dy in dxdy:
            if (vx + dx > W) or (vy + dy > H): continue
            elif (vx + dx < 0) or (vy + dy < 0): continue

            elif graph[vy + dy][vx + dx] == ".":
                if dist[vy + dy][vx + dx] == -1:
                    queue.append((vx + dx, vy + dy))
                    dist[vy + dy][vx + dx] = dist[vy][vx] + 1
                    

            elif graph[vy + dy][vx + dx] == "#": continue
            else: continue

    # can't goal
    if dist[H][W] == -1:
        print(-1)
    else:
        # the number of "." - min(dist) - "." of start
        print(cnt - dist[H][W] - 1)

def __starting_point():
    main()
__starting_point()

H,W = map(int,input().split())
s = [input() for i in range(H)]
from collections import deque
m = [[-1]*W for i in range(H)]
m[0][0] = 0
d = deque()
d.append([0,0])
dx = [1,-1,0,0]
dy = [0,0,1,-1]
while len(d) > 0:
    y,x = d.popleft()
    for i in range(4):
        ny = y+dy[i]
        nx = x+dx[i]
        if 0 <= ny <= H-1 and 0 <= nx <= W-1 and s[ny][nx] == "." and m[ny][nx] == -1:
            m[ny][nx] = m[y][x] + 1
            d.append([ny,nx])
ans = m[H-1][W-1]
whites = -1
for i in s:
    whites += i.count(".")
if ans != -1:
    ans = whites - ans
print(ans)

H, W = map(int, input().split())
inf = 101
s = [''] * H
cnt = 0
for i in range(H):
	s[i] = input()
	cnt += s[i].count('.')
d = [[inf] * W for i in range(H)]
from collections import deque
queue = deque([[0, 0]])
d[0][0] = 0

while queue:
	x, y = queue.popleft()
	if x+1 == H and y+1 == W:
		break
	dx, dy = [-1, 0, 1, 0], [0, -1, 0, 1]
	for i in range(4):
		nx, ny = x + dx[i], y + dy[i]
		if 0 <= nx and nx < H and 0 <= ny and ny < W and s[nx][ny] != '#' and d[nx][ny] == inf:
			queue.append([nx, ny])
			d[nx][ny] = d[x][y] + 1

if d[H-1][W-1] == inf:
	print(-1)
else:
	print(cnt-d[H-1][W-1]-1)

import sys
h,w=list(map(int,input().split()))
ss=[list(input()) for i in range(h)]
num=0
for i in range(h):
    num+=ss[i].count('.')

visited=[[0 for i in range(w)] for j in range(h)]
queue=[]
queue.append([0,0])
ss[0][0]='fin'
dy=[1,0,-1,0]
dx=[0,1,0,-1]


while len(queue)>0:
    now=queue.pop(0)
    for i in range(4):
        x= now[1]+dx[i]
        y= now[0]+dy[i]
        if 0<=x<w and 0<=y<h :
            if ss[y][x]=='.' and visited[y][x]==0:
                visited[y][x]=visited[now[0]][now[1]]+1
                queue.append([y,x])
            if x==w-1 and y==h-1:
                print((num-visited[y][x]-1))
                return
print((-1))


import sys
sys.setrecursionlimit(10**7)
from collections import deque

H,W=list(map(int,input().split()))
dots=H*W
field=[]
for _ in range(H):
    tmp=input()
    dots-=tmp.count("#")
    field.append(tmp)

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

while que:
    y,x=que.popleft()
    for dx,dy in zip(DX,DY):
        nx=x+dx
        ny=y+dy
        if nx<0 or nx>=W or ny<0 or ny>=H: continue
        if field[ny][nx]=="#": continue
        if dist[ny][nx]==-1:
            dist[ny][nx]=dist[y][x]+1
            que.append([ny,nx])

score=-1
goal=dist[H-1][W-1]
if goal!=-1:
    score=dots-goal-1
print(score)


from collections import deque

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

q = deque()
q.append((0, 0, 0))
check = [[0]*w for _ in range(h)]

flag = False
while q:
    y, x, d = q.popleft()
    if y == h-1 and x == w-1:
        g = d
        flag = True
        break
    if check[y][x] == 0:
        check[y][x] = 1
        for xdx, ydy in zip((x, x, x+1, x-1), (y+1, y-1, y, y)):
            if (0 <= xdx < w) and (0 <= ydy < h):
                if check[ydy][xdx] == 0 and s[ydy][xdx] == '.':
                    q.append((ydy, xdx, d+1))
ss = 0
for i in s:
    ss += i.count('#')
print(h*w-ss-d-1 if flag else -1)

from collections import deque


def bfs(start):
    q = deque([[start]])
    visited = set()
    while q:
        path = q.popleft()
        i, j = path[-1]
        if (i, j) == (H - 1, W - 1):
            return path
        for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ni, nj = i + di, j + dj
            if (
                0 <= ni < H
                and 0 <= nj < W
                and field[ni][nj] != "#"
                and (ni, nj) not in visited
            ):
                q.append(path + [(ni, nj)])
                visited.add((ni, nj))


H, W = list(map(int, input().split()))
field = [input() for _ in range(H)]
shortest_path = bfs((0, 0))
if shortest_path is None:
    print((-1))
    return
ans = 0
for i in range(H):
    for j in range(W):
        if field[i][j] == "." and (i, j) not in shortest_path:
            ans += 1
print(ans)


#
# abc088 d
#
import sys
from io import StringIO
import unittest
from collections import deque


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """3 3
..#
# ..
..."""
        output = """2"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
....................................."""
        output = """209"""
        self.assertIO(input, output)


def resolve():
    H, W = list(map(int, input().split()))
    S = [list(input()) for _ in range(H)]

    F = [[-1]*W for _ in range(H)]

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

    Q = deque()
    Q.append([0, 0])
    F[0][0] = 1

    while Q:
        p = Q.popleft()
        x, y = p

        if x == W-1 and y == H-1:
            break

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= W or ny < 0 or ny >= H or S[ny][nx] == "#" or F[ny][nx] != -1:
                continue

            Q.append([nx, ny])
            F[ny][nx] = F[y][x] + 1

    if F[H-1][W-1] == -1:
        print((-1))
    else:
        NS = 0
        for s in S:
            NS += s.count("#")
        print((W*H-F[H-1][W-1]-NS))


def __starting_point():
    # unittest.main()
    resolve()

__starting_point()

from collections import deque
def main():
    # bfs
    def _bfs():
        while q:
            now = q.popleft()
            height, width = now[0], now[1]
            # board[ny][nx] = 
            if height == h-1 and width == w-1:
                return board[height][width]
            for i in range(4):
                ny = height + dy[i]
                nx = width + dx[i]
                if 0<= ny < h and 0 <= nx < w and board[ny][nx] == ".":
                    q.append((ny, nx))
                    board[ny][nx] = 1 + board[height][width]
        return -1

    # input
    h, w = list(map(int, input().split()))
    # board creation
    board = []
    totalPoints = 0
    for _ in range(h):
        row = list(input())
        # count the number of "."s
        totalPoints += row.count(".")
        board.append(row)

    board[0][0] = 1
    q = deque([(0, 0)])
    dy = [0, -1, 0, 1]
    dx = [1, 0, -1, 0]
    
    # print(totalPoints)
    step = _bfs()
    # subtrack # of "." - the result of bfs as the answer.
    if step == -1:
        return -1
    ans = totalPoints - step
    return ans

    
def __starting_point():
    print((main()))

__starting_point()

from collections import deque
from typing import List


def main():
    h, w = list(map(int, input().split()))
    g = []
    for _ in range(h):
        gg = list(input())
        g.append(gg)
    print((gr(h, w, g)))


def gr(h: int, w: int, g: List[List[str]]) -> int:
    m = [[-1] * w for _ in range(h)]
    q = deque([(0, 0)])
    m[0][0] = 0
    while q:
        x, y = q.popleft()
        for nx, ny in [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)]:
            if (0 <= nx <= w - 1 and 0 <= ny <= h - 1) and g[ny][nx] == "." and m[ny][nx] < 0:
                m[ny][nx] = m[y][x] + 1
                if nx == w - 1 and ny == h - 1:
                    break
                q.append((nx, ny))

    if m[h - 1][w - 1] < 0:
        return -1
    return sum(gg.count(".") for gg in g) - m[h - 1][w - 1] - 1


def __starting_point():
    main()

__starting_point()

from collections import deque

def bfs(sy,sx):
  q = deque([[sy,sx]])
  d[sy][sx] = 0
  while q:
    y,x = q.popleft()
    for i,j in [(-1,0),(1,0),(0,-1),(0,1)]:
      dy,dx = y+i,x+j
      if 0<=dy<h and 0<=dx<w:
        if s[dy][dx] == "#": continue
        if d[dy][dx] != -1: continue
        d[dy][dx] = d[y][x] + 1
        q.append([dy,dx])

h,w = map(int, input().split())
s = [input() for _ in range(h)]
d = [[-1]*w for _ in range(h)]
if s[0][0] == "#" or s[h-1][w-1] == "#":
  print(-1)
  return
bfs(0,0)
if d[h-1][w-1] == -1: print(-1)
else:
  t = 0
  for i in range(h): t += s[i].count("#")
  print(h*w - (t+d[h-1][w-1]+1))

import sys

H, W = list(map(int, input().split()))
sx = 0
sy = 0
gx = W-1
gy = H-1
ans = 0
A = [list(i for i in input()) for _ in range(H)]
for j in A:
    ans += j.count(".")
inf = -1
distance = [[inf] * W for _ in range(H)]
queue = []
queue.insert(0, (sy, sx))
distance[sy][sx] = 0
X = 0
while True:
    try:
        y, x = queue.pop()
        # print(y,x)
    except:
        # print("Fail")
        break
    for i in range(4):
        nx = x + (-1, 0, 1, 0)[i]
        ny = y + (0, -1, 0, 1)[i]
        # print("nynx",ny,nx)
        if (0 <= nx and nx <= W-1 and 0 <= ny and ny <= H-1 and A[ny][nx] != '#' and distance[ny][nx] == inf):
            queue.insert(0, (ny, nx))
            distance[ny][nx] = distance[y][x] + 1
            A[ny][nx] = "!"
    # print(queue,"Q")

if distance[H-1][W-1] != inf:
    #print(distance[gy][gx])
    ans -= distance[gy][gx] + 1
    print(ans)
else:
    print((-1))


H, W = list(map(int, input().split()))
# maze = [list(map(int, input().split())) for i in range(H)]
maze = []
s_init_cnt = 0
for i in range(H):
    gyo = list(input())
    s_init_cnt += gyo.count('.')
    maze.append(gyo)

#print(maze)
#print(s_init_cnt)

direction = [(-1, 0), (0, -1), (1, 0), (0, 1)]
reached = [[-1] * W for i in range(H)]
reached[0][0] = 1
from collections import deque


def bfs():
    d = deque([[0, 0]])
    while len(d) > 0:
        px, py = d.popleft()
        for dx, dy in direction:
            tx = px + dx
            ty = py + dy
            if tx >= H or ty >= W or tx < 0 or ty < 0:
                continue
            if reached[tx][ty] != -1 or maze[tx][ty] == '#':
                continue
            else:
                reached[tx][ty] = reached[px][py] + 1
                d.append([tx, ty])
bfs()
ans = reached[H-1][W-1]
if ans == -1:
    print(ans)
else:
    ans = s_init_cnt - ans
    print(ans)


from collections import deque

H, W = list(map(int, input().split()))
C=list(list(input()) for _ in range(H))

def bfs():
	sx, sy= 0, 0
	gx, gy= H-1, W-1
	dx = [1, 0, -1, 0]
	dy = [0, 1, 0, -1]

	work_queue=deque([])
	work_queue.append((sx, sy))
	visited=[[float("inf")]*W for _ in range(H)]
	visited[sx][sy]=1

	while work_queue:
		x, y = work_queue.popleft()

		for i in range(4):
			nx, ny = x+dx[i], y+dy[i]

			if 0<=nx<H and 0<=ny<W and visited[nx][ny]==float("inf") and C[nx][ny]!="#":
				work_queue.append((nx, ny))
				visited[nx][ny]= visited[x][y]+1
	return visited[gx][gy]


temp=bfs()

black=0
white=0
for i in range(H):
	for j in range(W):
		if C[i][j]==".":
			white+=1
		else:
			black+=1

if temp==float("inf"):
	print((-1))
else:
	print((white-temp))






import re
import copy
import numpy as np
import queue

def accept_input():
    H,W = list(map(int,input().split()))
    S = []
    for _ in range(H):
        S.append(input())
    return H,W,S


def widthsearch(q):
    movelist = [(0,1),(0,-1),(1,0),(-1,0)] 
    while not q.empty():
        pack = q.get()
        y = pack[0][0]
        x = pack[0][1]
        num = pack[1]
        if S[y][x] == "g":
            return num
        for move in movelist:
            if y+move[0] == -1 or y + move[0] == H or x+move[1] == -1 or x + move[1] == W:
                continue
            elif visitedlist[y+move[0]][x+move[1]] == 1:
                continue
            elif S[y+move[0]][x+move[1]] == "#":
                continue
            else:
                visitedlist[y+move[0]][x+move[1]] = 1
                q.put(((y+move[0],x+move[1]),num+1))
    return -1

H,W,S = accept_input()
for i in range(len(S)):
    if i == 0:
        S[i] = "s"+S[i][1:]
    if i == H-1:
        S[i] = S[i][:W-1]+"g"
siro = H*W
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            siro -= 1
q = queue.Queue()
q.put(((0,0),0))
#幅優先探索
visitedlist = np.zeros((H,W))
visitedlist[0][0] = 1
result = widthsearch(q)
if result == -1:
    print((-1))
else:
    print((siro-result-1))


from collections import deque
h, w = map(int, input().split())
field = [input() for _ in range(h)]
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
white = 0
for i in range(h):
    white += field[i].count(".")
cnt = [[-1]*w for _ in range(h)]
cnt[0][0] = 0
q = deque([[0, 0]])

while q:
    y, x = q.pop()
    for dy, dx in d:
        ny = y + dy
        nx = x + dx
        if 0 <= ny < h and 0 <= nx < w and field[ny][nx] == "." and cnt[ny][nx] < 0:
            cnt[ny][nx] = cnt[y][x] + 1
            q.appendleft([ny, nx])
        if ny == h-1 and nx == w-1:
            print(white - cnt[h-1][w-1] - 1)
            return

print(-1)

from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
dots = sum([v.count('.') for v in s])

visited = [[-1] * w for _ in range(h)]
q = deque([[0, 0]])
visited[0][0] = 1

while q:
    y, x = q.popleft()
    if y == h - 1 and x == w - 1:
        break
    for i, j in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        ny, nx = y + i, x + j
        if (not 0 <= ny < h) or (not 0 <= nx < w) or s[ny][nx] == '#':
            continue
        elif visited[ny][nx] == -1:
            visited[ny][nx] = visited[y][x] + 1
            q.append([ny, nx])
if visited[h - 1][w - 1] != -1:
    print(dots - visited[h - 1][w - 1])
else:
    print(-1)

#!/usr/bin/env python3
import sys
sys.setrecursionlimit(1000000)
from collections import deque

# スペース区切りの整数の入力
H, W = list(map(int, input().split()))

#配列の入力
s = [list(input()) for _ in range(H)]

dist = [[-1 for _ in range(W)]for _ in range(H)]


def bfs():
    que = deque()
    que.append((0, 0))
    dist[0][0] = 0
    offset = ((1,0),(-1,0),(0,1),(0,-1))
    while que:
        now_h, now_w = que.popleft()
        if now_h < 0 or H-1 < now_h or now_w < 0 or W-1 < now_w:
            continue
        if s[now_h][now_w] == '#':
            continue
        for oh, ow in offset:
            if now_h+oh < 0 or H-1 < now_h+oh or now_w+ow < 0 or W-1 < now_w+ow:
                continue
            if dist[now_h+oh][now_w+ow] != -1:
                continue
            else:
                dist[now_h+oh][now_w+ow] = dist[now_h][now_w]+1
                que.append((now_h+oh, now_w+ow))





bfs()
m = dist[H-1][W-1]

if m == -1:
    print((-1))
else:
    count = 0
    for t in s:
        count += t.count('.')
    
    print((count - m- 1))



#キューのクラス
class Queue:
    def __init__(self,data = []):
        self.data = data
    def enqueue(self,x):
        self.data.append(x)
        return self.data
    def dequeue(self):
        if len(self.data) == 0:
            return "Queue is Empty!"
        else:
            cell = self.data[0]
            del self.data[0]
            return self.data

H, W = list(map(int, input().split()))
s = [list(input()) for i in range(H)]
#4近傍探索のために用意
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
#最小距離のリスト(Falseで初期化)
min_dis = [[False for i in range(W)] for j in range(H)]
min_dis[0][0] = 1#スタート位置を1にする(注意!!)
#キューのインスタンスQ作成
Q = Queue()
Q.enqueue([0, 0])
#キューの中身がなくなるまでループ
while Q.data:
    y = Q.data[0][0]
    x = Q.data[0][1]
    #4近傍探索
    for i, j in zip(dy, dx):
        if  (0 <= y + i < H) and  (0 <= x + j <W) and s[y + i][x + j] == ".":#（範囲内にあった場合）かつ（道だった場合）
            if min_dis[y+i][x+j] == False:#最小距離がFalseだった場合
                min_dis[y+i][x+j] = min_dis[y][x] + 1
                Q.enqueue([y+i, x+j])#値を更新したマスをQにプッシュ
    Q.dequeue()#探索し終わったマスをQからプル

if not min_dis[H-1][W-1]:
    print((-1))
    return

##マスをカウント
num_shap = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == "#":
            num_shap += 1
#スコア＝（全マス)-(#マス)-(gへの最短経路)
score = (H*W) - num_shap - (min_dis[H-1][W-1])
print(score)


def cal():
    import queue
    h, w = list(map(int, input().split()))
    s = [list(input()) for _ in range(h)]
    cost = [[-1]*w for _ in range(h)]
    INF = float('inf')
    count, ans = 0, INF
    for i in range(h):
        for j in range(w):
            if s[i][j] != '#':
                cost[i][j] = INF
            else:
                count += 1        
    q = queue.Queue()
    q.put((0, 0, 1))
    while not q.empty():
        c0, c1, c2 = q.get()
        s[c0][c1] = '#'
        if c0 == h-1 and c1 == w-1:
            return h*w-count-c2
        for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            x, y = c0+i, c1+j
            if 0 <= x < h and 0 <= y < w:
                if s[x][y] != '#' and cost[x][y] == INF:
                    cost[x][y] = c2+1
                    q.put((x, y, c2+1))

    return ans

ans = cal()
if ans == float('inf'):
    print((-1))
else:
    print(ans)


from collections import deque
move=((-1,0),(1,0),(0,-1),(0,1))
H,W=map(int,input().split())
M=[]
visited=[ [0]*W for _ in range(H)]
D=[[0]*W for _ in range(H)]
black=0
for _ in range(H):
  s=input()
  M.append(s)
  for c in s:
    if c=='#':
      black += 1
q=deque()
q.append((0,0))
cost=-1
while q:
  y,x=q.popleft()
  d=D[y][x]
  if x==W-1 and y==H-1:
    cost=d
    break
  if visited[y][x]==1:
    continue
  else:
    visited[y][x] = 1
    for dx,dy in move:
      nx,ny=x+dx,y+dy
      if (0<=nx<W) and (0<=ny<H):                
        if visited[ny][nx]==0 and M[ny][nx]=='.':
          D[ny][nx]=d+1
          q.append((ny,nx))
if cost==-1:
  print (-1)
else:
  print (H*W-cost-1-black)

from collections import*
H,W=map(int,input().split());M=[input()for _ in"_"*H];C=[[1]*W for _ in"_"*H];q=deque([[0,0]])
while q:
  x,y=q.popleft()
  for i,j in [[1,0],[-1,0],[0,1],[0,-1]]:
    h,w=x+i,y+j
    if H>h>-1and W>w>-1and M[h][w]>'#'and C[h][w]<2:C[h][w]=C[x][y]+1;q.append([h,w])
c=C[H-1][W-1];print(-1*(c<2)or sum(m.count(".") for m in M)-c)

from collections import deque


def main():
    H, W = list(map(int, input().split()))
    field = [list(input().rstrip()) for _ in range(H)]

    black = 0

    for f in field:
        for s in f:
            if s == "#":
                black += 1

    dir_h = [0, 0, 1, -1]
    dir_w = [1, -1, 0, 0]

    print((H * W - black - bfs(H, W, field, dir_h, dir_w)))


def bfs(H, W, field, dir_h, dir_w):
    q = deque([])
    seen = [[-1 for _ in range(W)] for _ in range(H)]

    q.append([0, 0])
    seen[0][0] = 1

    while q:
        h, w = q.popleft()

        for dh, dw in zip(dir_h, dir_w):
            nh, nw = h + dh, w + dw

            if nh < 0 or nh >= H or nw < 0 or nw >= W:
                continue
            elif field[nh][nw] == "#":
                continue
            elif seen[nh][nw] != -1:
                continue

            seen[nh][nw] = seen[h][w] + 1
            q.append([nh, nw])

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

    return seen[H - 1][W - 1]


def __starting_point():
    main()

__starting_point()

import sys
H,W = map(int,input().split())
C = [list(input()) for i in range(H)]
cost = [[-1 for i in range(W)] for i in range(H)]
queue = []

black = 0
for i in range(H):
    black += C[i].count('#')

queue.append([0,0])
cost[0][0] = 0
            
dy_dx = [[1,0],[0,1],[-1,0],[0,-1]]

while len(queue) > 0:
    now = queue.pop(0)
    if now[0] == H-1 and now[1] == W-1:
        ans = H*W - cost[H-1][W-1] - black - 1
        print(ans)
        return
    for i in range(4):
        y = now[0]+dy_dx[i][0]
        x = now[1]+dy_dx[i][1]
        if 0 <= y < H and 0 <= x < W:
            if C[y][x] != '#' and cost[y][x] == -1:
                cost[y][x] = cost[now[0]][now[1]] + 1
                queue.append([y,x])     
print(-1)

from collections import deque

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

s = [input() for _ in range(h)]

c = 0

for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            c += 1

#DFS
q = deque([[0, 0]])
dist = [[10000] * w for _ in range(h)]
dist[0][0] = 0

flag = False

while len(q) > 0:
    i, j = q.popleft()
    if i == h-1 and j == w-1:
        break
    else:
        if i < h-1 and s[i+1][j] == "." and not dist[i+1][j] < 10000:
            q.append([i+1, j])
            dist[i+1][j] = dist[i][j] + 1
        if j < w-1 and s[i][j+1] == "." and not dist[i][j+1] < 10000:
            q.append([i, j+1])
            dist[i][j+1] = dist[i][j] + 1
        if i > 0 and s[i-1][j] == "." and not dist[i-1][j] < 10000:
            q.append([i-1, j])
            dist[i-1][j] = dist[i][j] + 1
        if j > 0 and s[i][j-1] == "." and not dist[i][j-1] < 10000:
            q.append([i, j-1])
            dist[i][j-1] = dist[i][j] + 1

if dist[h-1][w-1] < 10000:
    print(h * w - dist[h-1][w-1] - 1 - c)
else:
    print(-1)

from collections import deque

LOAD = "."

H, W = map(int, input().split())
field = [["" for _ in range(W)] for _ in range(H)]
dist = [[-1 for _ in range(W)] for _ in range(H)]
for h in range(H):
    field[h] = list(input())

total_laod = 0
for f in field:
    total_laod += f.count(LOAD)

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
sh, sw = (0, 0)
gh, gw = (H-1, W-1)
dist[sh][sw] = 0
q = deque()
q.append((sh, sw))

while q:
    h, w = q.popleft()
    for i in range(4):
        nh = h + dy[i]
        nw = w + dx[i]

        if nh < 0 or H <= nh or nw < 0 or W <= nw:
            continue
        if field[nh][nw] != LOAD:
            continue
        if dist[nh][nw] != -1:
            continue

        dist[nh][nw] = dist[h][w] + 1
        q.append((nh, nw))

if dist[gh][gw] == -1:
    print(-1)
else:
    print(total_laod - (dist[gh][gw] + 1))

import sys
from collections import deque


def IN_I(): return int(sys.stdin.readline().rstrip())
def IN_LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def IN_S(): return sys.stdin.readline().rstrip()
def IN_LS(): return list(sys.stdin.readline().rstrip().split())


H, W = IN_LI()
s = [IN_S() for _ in range(H)]

dh = [-1, 0, 1, 0]
dw = [0, -1, 0, 1]

dist = [[-1] * W for j in range(H)]
dist[0][0] = 0

q = deque()
q.append([0, 0])

while q:
    now = q.popleft()
    now_h = now[0]
    now_w = now[1]

    for i in range(4):
        next_h = now_h + dh[i]
        next_w = now_w + dw[i]

        if not (0 <= next_h < H and 0 <= next_w < W):
            continue
        if s[next_h][next_w] == '#':
            continue

        if dist[next_h][next_w] == -1:
            q.append([next_h, next_w])
            dist[next_h][next_w] = dist[now_h][now_w] + 1

if dist[-1][-1] == -1:
    print((-1))
    return

white = sum([i.count('.') for i in s])
ans = white - (dist[-1][-1] + 1)
print(ans)


H,W=map(int,input().split())
S=[list(input())for _ in range(H)]

from collections import deque
def bfs(h,w,sy,sx,gy,gx,S):
    maze=[[10**9]*(W)for _ in range(H)]
    maze[sy-1][sx-1]=0
    que=deque([[sy-1,sx-1]])
    while que:
        y,x=que.popleft()
        for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if 0<=nexty<h and 0<=nextx<w:
                dist1=S[nexty][nextx]
                dist2=maze[nexty][nextx]
            else:
                continue
            if dist1!='#':
                if dist2>maze[y][x]+1:
                    maze[nexty][nextx]=maze[y][x]+1
                    que.append([nexty,nextx])
    return maze[gy-1][gx-1]+1

A=0
for s in S:
    A+=s.count('.')

B=bfs(H,W,1,1,H,W,S)
if B>10**9:
    ans=-1
else:
    ans=A-B
print(ans)

from collections import deque

R, C = map(int, input().split())
masu = [list(input()) for _ in range(R)]
sr, sc = 0, 0
gr, gc = R - 1, C - 1

def bfs():
    d = [[float("inf")] * C for _ in range(R)]
    dr = [0, -1, 0, 1]
    dc = [1, 0, -1, 0]
    que = deque([])

    que.append((sr, sc))
    d[sr][sc] = 0
    while que:
        p = que.popleft()
        if p[0] == gr and p[1] == gc:
            break
        for i in range(4):
            nr = p[0] + dr[i]
            nc = p[1] + dc[i]
            if (0 <= nr < R) and (0 <= nc < C) and masu[nr][nc] != "#" and d[nr][nc] == float("inf"):
                que.append((nr, nc))
                d[nr][nc] = d[p[0]][p[1]] + 1
    
    return d[gr][gc]

white = 0
for i in range(R):
    for j in range(C):
        if masu[i][j] == ".":
            white += 1

res = bfs()
if 0 < res < float("inf"):
    print(white - res - 1)
else:
    print(-1)

import sys
from collections import deque


def LI():
    return list(map(int, input().split()))


def LSH(h):
    return [list(input()) for _ in range(h)]


H, W = LI()
MAP = LSH(H)
d = deque()
d.append([0, 0])
looked = [[0 for i in range(W)]for j in range(H)]
looked[0][0] = 1
move = [[1, 0], [0, 1], [-1, 0], [0, -1]]
while d:
    x = d.popleft()
    h = x[0]
    w = x[1]
    for i in move:
        a = h+i[0]
        b = w+i[1]
        if not(0 <= a < H) or not(0 <= b < W) or looked[a][b] != 0 or MAP[a][b] == "#":
            continue
        d.append([a, b])
        looked[a][b] = looked[h][w]+1
if looked[H-1][W-1] == 0:
    print((-1))
    return

white = 0
for i in range(H):
    for j in range(W):
        if MAP[i][j] == ".":
            white += 1

print((white-looked[H-1][W-1]))


from collections import deque, Counter

def main():
    with open(0) as f:
        H, W = map(int, f.readline().split())
        maze = [list(line) for line in f.readlines()]

    rank = [[None]*W for _ in range(H)]
    rank[0][0] = 0
    #bfs
    reserved = deque([(0,0)])
    while len(reserved) > 0:
        x, y = reserved.popleft()
        for u,v in [(s,t) for s,t in [(x-1,y), (x+1,y), (x,y-1), (x,y+1)] if 0<=s<H and 0<=t<W]:
            if rank[u][v] is not None:
                continue
            if maze[u][v] == '.':
                rank[u][v] = rank[x][y] + 1
                reserved.append((u,v))

    if rank[H-1][W-1] is None:
        print(-1)
    else:
        counter = Counter()
        for line in maze:
            counter.update(line)
        print(counter['.'] - rank[H-1][W-1]-1)

main()

from collections import deque
h,w=list(map(int,input().split()))
queue=deque()
s=[list(input()) for _ in range(h)]
seen=[[False]*w for _ in range(h)]
queue.append([0,0])
ans=[[1000000000]*w for _ in range(h)]
seen[0][0]=True
ans[0][0]=1
for i in range(h*w*10):
    if len(queue)==0:
        break
    cnt=queue.popleft()
    if cnt[0]!=0:
        if seen[cnt[0]-1][cnt[1]]==False and s[cnt[0]-1][cnt[1]]==".":
            queue.append([cnt[0]-1,cnt[1]])
            ans[cnt[0]-1][cnt[1]]=ans[cnt[0]][cnt[1]]+1
            seen[cnt[0]-1][cnt[1]]=True
    if cnt[1]!=0:
        if seen[cnt[0]][cnt[1]-1]==False and s[cnt[0]][cnt[1]-1]==".":
            queue.append([cnt[0],cnt[1]-1])
            ans[cnt[0]][cnt[1]-1]=ans[cnt[0]][cnt[1]]+1
            seen[cnt[0]][cnt[1]-1]=True
    if cnt[0]!=h-1:
        if seen[cnt[0]+1][cnt[1]]==False and s[cnt[0]+1][cnt[1]]==".":
            queue.append([cnt[0]+1,cnt[1]])
            ans[cnt[0]+1][cnt[1]]=ans[cnt[0]][cnt[1]]+1
            seen[cnt[0]+1][cnt[1]]=True
    if cnt[1]!=w-1:
        if seen[cnt[0]][cnt[1]+1]==False and s[cnt[0]][cnt[1]+1]==".":
            queue.append([cnt[0],cnt[1]+1])
            ans[cnt[0]][cnt[1]+1]=ans[cnt[0]][cnt[1]]+1
            seen[cnt[0]][cnt[1]+1]=True
cnt2=0
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            cnt2+=1
if seen[-1][-1]==False:
    print((-1))
else:
    print((cnt2-ans[-1][-1]))


H,W = map(int,input().split())
s = ['' for i in range(H)]
white = H*W
black = 0
for i in range(H):
    s[i] = input()
    black += s[i].count('#')
white -= black
direction = [[1,0],[0,1],[-1,0],[0,-1]]
q = [[0,0,0]]

mass = [[-1 for i in range(W)] for j in range(H)]
while len(q) > 0:
    tmp = [y,x,d] = q.pop(0)
    if mass[y][x] >= 0: 
        continue
    mass[y][x] = d
    for [dy,dx] in direction:
        ny = y + dy
        nx = x + dx
        if 0 <= ny and ny < H and 0 <= nx and nx < W:
            if s[ny][nx] == '#' or mass[ny][nx] >= 0:
                continue
            q.append([ny,nx,d+1])
# for i in mass:
#     print(i)
if mass[H-1][W-1] < 0:
    print(-1)
else:
    print(white - mass[H-1][W-1] - 1)

from collections import *
H,W = map(int,input().split())
S = [(W+2)*["#"]]+list(["#"]+list(input())+["#"] for h in range(H))+[(W+2)*["#"]]
S[1][1] = 1
Q = deque([[1,1]])
D = [[1,0],[-1,0],[0,1],[0,-1]]

while Q:
  x,y = Q.popleft()
  for dx,dy in D:
    if S[x+dx][y+dy]==".":
      S[x+dx][y+dy] = S[x][y]+1
      Q.append([x+dx,y+dy])

if S[H][W]==".":
  print(-1)
else:
  print((H+2)*(W+2)-sum(s.count("#") for s in S)-S[H][W])

from collections import deque
move=((-1,0),(1,0),(0,-1),(0,1))
H,W=map(int,input().split())
M=['#'*(W+2)]
black=0
for _ in range(H):
  row=input()
  M.append('#'+row+'#')
  black+=row.count('#')
M.append('#'*(W+2))
sy,sx=1,1
gy,gx=H,W
D=[[-1]*(W+2) for _ in range(H+2)]
D[sy][sx]=0
visited=set()
q=deque()
q.append((sy,sx))
visited.add((sy,sx))
while q:
  y,x=q.popleft()
  for dy,dx in move:
    ny,nx=y+dy,x+dx
    if M[ny][nx]=='#' or D[ny][nx]!=-1:
      continue
    D[ny][nx]=D[y][x]+1
    q.append((ny,nx))
print(W*H-(D[gy][gx]+1)-black if D[gy][gx]!=-1 else -1)