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: MEDIUM

Solutions:
import sys
input = sys.stdin.readline
from collections import deque
(H, W) = map(int, input().split())
X = [1, 0, -1, 0]
Y = [0, -1, 0, 1]
num = 0
D = []
for i in range(H):
	s = list(input())
	num += s.count('.')
	D.append(s)
Q = deque()
Q.append((0, 0))
dist = [[-1] * W for i in range(H)]
dist[0][0] = 0
while Q:
	(y, x) = Q.popleft()
	for i in range(4):
		nx = x + X[i]
		ny = y + Y[i]
		if 0 <= nx < W and 0 <= ny < H and (dist[ny][nx] == -1) and (D[ny][nx] == '.'):
			dist[ny][nx] = dist[y][x] + 1
			Q.append((ny, nx))
if dist[H - 1][W - 1] == -1:
	print(-1)
else:
	print(num - dist[H - 1][W - 1] - 1)


import queue
(H, W) = list(map(int, input().split()))
s = [list(input()) + ['#'] for i in range(H)] + [['#' for i in range(W + 1)]]
white = sum([s[i].count('.') for i in range(H)])
q = queue.Queue()
s[0][0] = 1
q.put((0, 0))
while not q.empty():
	(i, j) = q.get()
	for (x, y) in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
		if s[x][y] == '.':
			s[x][y] = s[i][j] + 1
			q.put((x, y))
if s[H - 1][W - 1] in ['.', '#']:
	print(-1)
else:
	print(white - s[H - 1][W - 1])


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


from collections import deque, defaultdict
(H, W) = map(int, input().split())
s = [['#'] * (W + 2)] + [list('#' + input() + '#') for _ in range(H)] + [['#'] * (W + 2)]
Q = deque([(1, 1, 1)])
cnt = 0
for S in s[1:-1]:
	cnt += S.count('.')
while Q:
	(x, y, d) = Q.popleft()
	s[x][y] = '#'
	if x == H and y == W:
		route = d
		break
	for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
		if s[x + dx][y + dy] == '.':
			Q.append((x + dx, y + dy, d + 1))
			s[x + dx][y + dy] = '#'
else:
	print(-1)
	exit()
print(cnt - route)


from collections import deque
(h, w) = map(int, input().split())
s = [list('#' + input() + '#') for i in range(h)]
s = [['#'] * (w + 2)] + s + [['#'] * (w + 2)]
z = 0
for i in s:
	z += i.count('.')
ans = [[-1] * (w + 2) for i in range(h + 2)]
m = [[0, 1], [0, -1], [1, 0], [-1, 0]]
ans[1][1] = 1
d = deque([[1, 1]])
while len(d):
	(x, y) = d.popleft()
	for (i, j) in m:
		(a, b) = (x + i, y + j)
		if s[a][b] == '.' and ans[a][b] == -1:
			d.append([a, b])
			ans[a][b] = ans[x][y] + 1
if ans[h][w] == -1:
	print(-1)
else:
	print(z - ans[h][w])


(h, w) = map(int, input().split())
grid = [['#'] * (w + 2)] + [list('#' + input() + '#') for x in range(h)] + [['#'] * (w + 2)]
(sx, sy) = (1, 1)
(gx, gy) = (w, h)
loc = [[sy, sx]]
ans = sum((i.count('.') for i in grid))
for c in range(h * w):
	next_loc = []
	for (y, x) in loc:
		for (i, j) in ([0, 1], [1, 0], [0, -1], [-1, 0]):
			if grid[y + i][x + j] == '.':
				grid[y][x] = c + 1
				grid[y + i][x + j] = c + 2
				next_loc.append([y + i, x + j])
	loc = next_loc
	if [gy, gx] in loc:
		ans -= grid[gy][gx]
		print(ans)
		exit()
print(-1)


from collections import deque
(H, W) = map(int, input().split())
Map = [list(input()) for i in range(H)]
for h in range(H):
	Map[h].insert(0, '#')
	Map[h].append('#')
Map.insert(0, ['#'] * (W + 2))
Map.append(['#'] * (W + 2))
white = sum((Map[i].count('.') for i in range(H + 2)))
Que = deque([(1, 1, 1)])
visited = [[10 ** 10] * (W + 2) for i in range(H + 2)]
while Que:
	(x, y, stage) = Que.popleft()
	if x == W and y == H:
		print(white - stage)
		exit()
	stage += 1
	for (i, j) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
		if Map[j][i] == '.' and stage < visited[j][i]:
			visited[j][i] = stage
			Que.append((i, j, stage))
print(-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)


(H, W) = list(map(int, input().split()))
M = [[-1] * (W + 2)]
ans = 0
for _ in range(H):
	s = input()
	ans += s.count('.')
	M.append([-1] + [0 if c == '.' else -1 for c in s] + [-1])
M += [[-1] * (W + 2)]
queue = [(1, 1)]
M[1][1] = 1
dr = [(+1, 0), (-1, 0), (0, +1), (0, -1)]
turn = 1
while len(queue) > 0:
	turn += 1
	queue_new = []
	for (qx, qy) in queue:
		for (dx, dy) in dr:
			(x, y) = (qx + dx, qy + dy)
			if M[y][x] == 0:
				M[y][x] = turn
				queue_new.append((x, y))
	queue = queue_new
print(ans - M[H][W] if M[H][W] > 0 else -1)


(H, W) = map(int, input().split())
m = []
m.append('#' * (W + 2))
white = 0
for i in range(H):
	s = input()
	m.append(list('#' + s + '#'))
	white += s.count('.')
m.append('#' * (W + 2))
op = set([(1, 1)])
dist = 0
while len(op) > 0:
	dist += 1
	next_op = set()
	for (y, x) in op:
		m[y][x] = dist
		if (y, x) == (H, W):
			print(white - dist)
			exit()
		for (dx, dy) in ([0, 1], [0, -1], [1, 0], [-1, 0]):
			if m[y - dy][x - dx] == '.':
				next_op.add((y - dy, x - dx))
	op = next_op
print('-1')


import sys
import operator
from collections import deque, Counter
input = sys.stdin.readline
(h, w) = map(int, input().split())
(sx, sy) = (0, 0)
(gx, gy) = (h - 1, w - 1)
s = [list(input()) for _ in range(h)]
c = []
for a in s:
	c += a
c = Counter(c)
white = c['.']
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])
bfs(sx, sy)
print(white - visited[gx][gy] - 1 if visited[gx][gy] != -1 else -1)


(H, W) = map(int, input().split())
MAP = [['#'] * (W + 2)] + [['#'] + list(input()) + ['#'] for i in range(H)] + [['#'] * (W + 2)]
white = 0
for line in MAP:
	white += line.count('.')
from collections import deque
check = deque([(1, 1, 1)])
dist = float('inf')
while len(check) > 0:
	(d, x, y) = check.popleft()
	for (i, j) in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
		if MAP[x + i][y + j] == '.':
			if x + i == H and y + j == W:
				dist = d + 1
				check = []
				break
			check.append((d + 1, x + i, y + j))
			MAP[x + i][y + j] = '#'
if dist > 10 ** 10:
	print(-1)
else:
	print(white - dist)


DIR = [(1, 0), (-1, 0), (0, 1), (0, -1)]
(H, W) = [int(x) for x in input().split()]
G = []
B = 0
G.append('#' * (W + 2))
for i in range(H):
	s = input()
	B += s.count('.')
	G.append(['#'] + list(s) + ['#'])
G.append('#' * (W + 2))
que = [(1, 1, 1)]
ans = -1
while que:
	(y, x, c) = que.pop(0)
	if (y, x) == (H, W):
		ans = c
		break
	for dir in DIR:
		ny = y + dir[0]
		nx = x + dir[1]
		if G[ny][nx] == '.':
			G[ny][nx] = '#'
			que.append((ny, nx, c + 1))
print(B - ans if ans != -1 else -1)


from collections import deque
(h, w) = map(int, input().split())
m = ['#' * (w + 2)] + ['#' + input() + '#' for _ in range(h)] + ['#' * (w + 2)]
cnt = 0
for hi in range(1, h + 1):
	for wi in range(1, w + 1):
		if m[hi][wi] == '.':
			cnt += 1
inf = 10 ** 9
d = [[inf] * (w + 2) for _ in range(h + 2)]
q = deque([(1, 1, 1)])
d[1][1] = 1
while len(q):
	(ch, cw, r) = q.popleft()
	for (hi, wi) in [[ch + 1, cw], [ch, cw + 1], [ch - 1, cw], [ch, cw - 1]]:
		if m[hi][wi] == '.' and d[hi][wi] > r + 1:
			d[hi][wi] = r + 1
			q.append((hi, wi, r + 1))
if d[h][w] == inf:
	print(-1)
else:
	print(cnt - d[h][w])


from collections import deque
(H, W) = map(int, input().split())
con = [[1, 0], [0, 1], [-1, 0], [0, -1]]
m = []
c = 0
d = [[0] * (W + 2) for _ in range(H + 2)]
d[1][1] = 1
m.append('#' * (W + 2))
for i in range(H):
	b = input()
	c += b.count('.')
	a = '#' + b + '#'
	m.append(a)
q = deque()
m.append('#' * (W + 2))
q.append((1, 1))
while len(q) > 0:
	(y, x) = q.popleft()
	if y == H and x == W:
		print(c - d[H][W])
		exit()
	for (dx, dy) in con:
		if d[y + dy][x + dx] == 0 and m[y + dy][x + dx] == '.':
			q.append((y + dy, x + dx))
			d[y + dy][x + dx] += d[y][x] + 1
print(-1)


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

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


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)


(H, W) = (int(i) for i in input().split())
grid = ['#' * (W + 2)] + ['#' + input() + '#' for i in range(H)] + ['#' * (W + 2)]
smap = [[-1 for i in range(W + 2)] for i in range(H + 2)]
q = []
dot = 0
angle = [[1, 0], [-1, 0], [0, 1], [0, -1]]
for i in grid:
	dot += i.count('.')
smap[1][1] = 1
q.append([1, 1])
while len(q) > 0:
	pos = q.pop(0)
	cnt = smap[pos[0]][pos[1]] + 1
	for a in angle:
		if grid[pos[0] + a[0]][pos[1] + a[1]] == '.' and smap[pos[0] + a[0]][pos[1] + a[1]] == -1:
			q.append([pos[0] + a[0], pos[1] + a[1]])
			smap[pos[0] + a[0]][pos[1] + a[1]] = cnt
print(-1) if smap[H][W] == -1 else print(dot - smap[H][W])


(H, W) = map(int, input().strip().split(' '))
maze = ['#' * (W + 2)]
maze += ['#' + input().strip() + '#' for _ in range(H)]
maze.append('#' * (W + 2))
maze_map = [[float('inf')] * (W + 2) for _ in range(H + 2)]
maze_map[1][1] = 1
mem = [(1, 1)]
while True:
	if len(mem) == 0:
		break
	(x, y) = mem.pop()
	for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
		if maze[y + dy][x + dx] == '.':
			if maze_map[y + dy][x + dx] > maze_map[y][x] + 1:
				maze_map[y + dy][x + dx] = maze_map[y][x] + 1
				mem.append((x + dx, y + dy))
if maze_map[H][W] == float('inf'):
	print(-1)
else:
	w = sum((m.count('.') for m in maze))
	print(w - maze_map[H][W])


(h, w) = map(int, input().split())
l = []
l.append(['#' for i in range(w + 2)])
for i in range(h):
	l.append(list('#' + input() + '#'))
l.append(['#' for i in range(w + 2)])
ctw = 0
for i in range(1, h + 1):
	for j in range(1, w + 1):
		if l[i][j] == '.':
			ctw += 1
L = [[1, 1]]
ct = 0
x = 0
for i in range(h * w):
	L2 = []
	for j in range(len(L)):
		L3 = [[L[j][0] - 1, L[j][1]], [L[j][0] + 1, L[j][1]], [L[j][0], L[j][1] - 1], [L[j][0], L[j][1] + 1]]
		for k in range(4):
			if l[L3[k][0]][L3[k][1]] == '.':
				L2.append(L3[k])
				l[L3[k][0]][L3[k][1]] = '#'
	ct += 1
	L = L2
	if [h, w] in L:
		x = ct
		break
if x == 0:
	print(-1)
else:
	print(ctw - ct - 1)


(H, W) = map(int, input().split())
maze = ['#' * (W + 2)]
for _ in range(H):
	maze.append('#' + input() + '#')
maze.append('#' * (W + 2))
cost = [[-1] * (W + 2) for _ in range(H + 2)]
cost[1][1] = 0
que = [(1, 1)]
while que:
	(i, j) = que.pop(0)
	if (i, j) == (H, W):
		break
	for (k, l) in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
		if maze[k][l] == '.' and cost[k][l] == -1:
			cost[k][l] = cost[i][j] + 1
			que.append((k, l))
if cost[H][W] == -1:
	print(-1)
else:
	n = -2
	for i in range(1, H + 1):
		for j in range(1, W + 1):
			if maze[i][j] == '.':
				n += 1
	print(n - cost[H][W] + 1)


from collections import deque
(H, W) = map(int, input().split())
edges = [0] * (W + 2)
field = [edges]
WH = 0
for _ in range(H):
	row = [c == '.' for c in input()]
	field.append([0] + row + [0])
	WH += sum(row)
field.append(edges)
que = deque([(1, 1, 1)])
(enq, deq) = (que.append, que.popleft)
while que:
	(x, y, cnt) = deq()
	if (x, y) == (W, H):
		print(WH - cnt)
		exit()
	for (dx, dy) in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
		(nx, ny) = (x + dx, y + dy)
		if field[ny][nx]:
			enq((nx, ny, cnt + 1))
			field[ny][nx] = 0
print(-1)


(H, W) = map(int, input().split())
L = ['#' * (W + 2)]
n = 0
for i in range(H):
	S = input()
	n += S.count('.')
	L.append('#' + S + '#')
L.append('#' * (W + 2))
r = [(1, 1)]
dic = {(1, 1): 1}
m = [(1, 1)]
i = 1
mm = []
nyan = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while m:
	i += 1
	for (a, b) in m:
		for (c, d) in nyan:
			(x, y) = (a + c, b + d)
			if L[x][y] == '.' and (x, y) not in r:
				r.append((x, y))
				mm.append((x, y))
				dic[x, y] = i
	m = mm[:]
	mm = []
if (H, W) in r:
	print(n - dic[H, W])
else:
	print(-1)