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

Solution (Python):
from collections import deque


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] != "
                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)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
m = [list(input()) for _ in range(H)]
numdot = sum([line.count('.') for line in m])

q = deque([[0, 0, 1]])
m[0][0] = '
goal = False
while q:
    i, j, score = q.popleft()
    if i == H-1 and j == W-1:
        goal = True
        break

    for movei, movej in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        ni = i + movei; nj = j + movej
        if ni < 0 or H <= ni or nj < 0 or W <= nj or m[ni][nj] == '
            continue
        m[ni][nj] = '
        q.append([ni, nj, score+1])

if goal:
    print(numdot - score)
else:
    print(-1)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
S = [input() for _ in range(H)]
white = sum(s.count(".") for s in S)
visited = [[-1] * W for _ in range(H)]
deq = deque([(0,0)])
visited[0][0] = 1
dia = [1, 0, -1, 0, 1]
while deq:
    i, j = deq.popleft()
    if i == H - 1 and j == W - 1:
        break
    d = visited[i][j]
    for x, y in zip(dia, dia[1:]):
        ii, jj = i + x, j + y
        if 0 <= ii < H and 0 <= jj < W and S[ii][jj] == "." and visited[ii][jj] < 0:
            visited[ii][jj] = d + 1
            deq.append((ii, jj))
print(white - visited[H-1][W-1] if visited[H-1][W-1] > 0 else -1)

Solution (Python):
import sys
 
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()
nas = lambda: stdin.readline().split()

from collections import deque

h, w = na()
s = [ns() for _ in range(h)]
m = [[s[i][j] for j in range(w)] for i in range(h)]
inf = 1 << 60
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs():
    q = deque()
    q.append((0, 0))
    d = [[inf] * w for _ in range(h)]
    d[0][0] = 0
    while len(q):
        p = q.popleft()
        if p[0] == w-1 and p[1] == h-1:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx and nx < w and 0 <= ny and ny < h and m[ny][nx] != '
                q.append((nx, ny))
                d[ny][nx] = d[p[1]][p[0]] + 1
    return d[h-1][w-1]

b = 0
for y in range(h):
    for x in range(w):
        if m[y][x] == '
            b += 1

k = bfs()
if k == inf:
    res = -1
else:
    res = (h * w) - b - (k + 1)
print(res)

Solution (Python):
H,W=[int(x) for x in input().split()]
import heapq
A=[]
temp=0
for i in range(H):
	s=input()
	A.append(s)
	for j in range(W):
		if s[j]==".":
			temp+=1


B=[[1000000000000000 for i in range(W)] for j in range(H)]



queue=[]
heapq.heapify(queue)
heapq.heappush(queue,[1,0,0])

ans=100000000000000000000
B[0][0]=1
while queue:
	
	count,x,y=heapq.heappop(queue)
	
	if x==H-1 and y==W-1:
		ans=min(ans,count)
	else:
		if (x+1<=H-1 and A[x+1][y]==".") and B[x+1][y]>count+1:
			heapq.heappush(queue,[count+1,x+1,y])
			B[x+1][y]=count+1
		if (0<=x-1 and A[x-1][y]==".") and B[x-1][y]>count+1:
			heapq.heappush(queue,[count+1,x-1,y])
			B[x-1][y]=count+1
		if (y+1<=W-1 and A[x][y+1]==".") and B[x][y+1]>count+1:
			heapq.heappush(queue,[count+1,x,y+1])
			B[x][y+1]=count+1
		if (0<=y-1 and A[x][y-1]==".") and B[x][y-1]>count+1:
			heapq.heappush(queue,[count+1,x,y-1])
			B[x][y-1]=count+1
if ans==100000000000000000000:
	print(-1)
else:
	print(temp-ans)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
maze = []
b = 0
for h in range(H):
    tmp = list(input())
    maze.append(tmp)
    for x in tmp:
        if x == ".":
            b += 1
sx, sy = 0, 0
gx, gy = W-1, H-1
dist = [[-1 for y in range(W)] for x in range(H)]
dist[sy][sx] = 0
que = deque([[sy, sx]])
while len(que) > 0:
    y, x = que.popleft()
    if y == gy and x == gx:
        break
    for n in range(4):
        ny, nx = y+[0,0,-1,1][n], x+[1,-1,0,0][n]
        if nx >= 0 and nx < W and ny >= 0 and ny < H and dist[ny][nx] == -1:
            if maze[ny][nx] == ".":
                dist[ny][nx] = dist[y][x] + 1
                que.append([ny, nx])
if dist[gy][gx] == -1:
    print(-1)
else:
    print(b-1-dist[gy][gx])

Solution (Python):
from collections import deque

def bfs():
    dist = [[f_inf] * w for _ in range(h)]
    
    D = ((1,0), (0,1), (-1,0), (0, -1))

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

    while que:
        p = que.popleft()
        for d in D:
            nx = p[0] + d[0]
            ny = p[1] + d[1]

            if h > nx >= 0 and w > ny >= 0 and \
               C[nx][ny] != '
               dist[nx][ny] == f_inf:
                que.append((nx, ny))
                dist[nx][ny] = dist[p[0]][p[1]]+1
    return dist[h-1][w-1]

h, w = map(int, input().split())
C =[input() for _ in range(h)]
f_inf = float('inf')

cnt = 0
for c in C:
    cnt += c.count('.')

if bfs() == f_inf:
    print(-1)
else:
    print(cnt - 1 - bfs())

Solution (Python):
from collections import deque

def bfs():
    dist = [[f_inf] * w for _ in range(h)]

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

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

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

            if h > nx >= 0 and w > ny >= 0 and \
               C[nx][ny] != '
               dist[nx][ny] == f_inf:
                que.append((nx, ny))
                dist[nx][ny] = dist[p[0]][p[1]]+1
    return dist[h-1][w-1]

h, w = map(int, input().split())
C =[input() for _ in range(h)]
f_inf = float('inf')

cnt = 0
for c in C:
    cnt += c.count('.')

if bfs() == f_inf:
    print(-1)
else:
    print(cnt - 1 - bfs())

Solution (Python):
import sys
from collections import deque
 
 
def bfs(H, W, maze, visited, sharp):
    queue = deque([[0, 0]])
    visited[0][0] = 0
    while queue:
        y, x = queue.popleft()
        if[y, x] == [H-1, W-1]:
            return ((H*W-sharp)-(visited[y][x]+1))
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y+j, x+k
            if  new_y != -1 and new_y != H and  \
                new_x != -1 and new_x != W and  \
                maze[new_y][new_x] == "." and   \
                visited[new_y][new_x] == -1:
                visited[new_y][new_x] = visited[y][x] + 1
                queue.append([new_y, new_x])
 
    return -1
 
 
def main():
    sharp = 0
 
    H, W = map(int,input().split())
    maze = [input() for i in range(H)]
    visited = [[-1]*W for j in range(H)]
 
    for k in range(H):
        sharp += maze[k].count('
 
    print(bfs(H, W, maze, visited, sharp))
 
main()

Solution (Python):

from collections import deque
h,w = map(int, input().split())
m = ["

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])

Solution (Python):
from collections import deque
h,w=map(int,input().split())
meiro=[list('
h+=2
w+=2
top=list('
bot=list('
meiro.insert(0,top)
meiro.append(bot)

def bfs(a,b):
    dist=[[-1]*w for i in range(h)]
    dist[b][a]=0
    q=deque([(a,b)])
    ans=-1
    flag=0
    while q:
        x,y=q.popleft()
        kyori=dist[y][x]
        dx=[0,1,0,-1]
        dy=[1,0,-1,0]
        for i in range(4):
            nx=x+dx[i]
            ny=y+dy[i]
            if nx==w-2 and ny==h-2 and meiro[ny][nx]=='.':
                return kyori +1
            if dist[ny][nx]==-1 and meiro[ny][nx]=='.':
                dist[ny][nx]=kyori+1
                ans=max(ans,kyori+1)
                q.append((nx,ny))
    return -1
saitan = bfs(1,1)
if saitan==-1:
    print(-1)
else:
    cnt=0
    for i in range(h):
        cnt+=str(meiro[i]).count('.')
    ans=cnt-saitan-1
    print(ans)

Solution (Python):
H,W = map(int,input().split())
Gd = [list(input()) for _ in range(H)]
ans = 0
for i in range(H):
  ans += Gd[i].count('.')
INF = -1
direc = [[1,0,-1,0],[0,1,0,-1]]
Dis = [[INF]*W for _ in range(H)]
from collections import deque
def dfs(start,goal):
  q = deque([])
  Dis[start[0]][start[1]]=1
  q.append(start)
  while len(q)!=0:
    h,w = q.popleft()
    for i in range(4):
      hs = h+direc[0][i]
      ws = w+direc[1][i]
      if 0<=hs<H and 0<=ws<W and Dis[hs][ws]==INF:
        if Gd[hs][ws]=='.':
          q.append([hs,ws])
          Dis[hs][ws]=Dis[h][w]+1
  return Dis[goal[0]][goal[1]]
minpath = dfs([0,0],[H-1,W-1])
if minpath == INF:
  ans = INF
else:
  ans = ans - minpath
print(ans)

Solution (Python):
h,w = map(int,input().split())
s = [str(input()) for i in range(h)]
num = [[-1] * w for i in range(h)]
num[0][0] = 0
now = {(0,0)}
for i in range(1,2501):
    tmp = set()
    for x,y in now:
        if x > 0:
            if s[x-1][y] == "." and num[x-1][y] == -1:
                num[x-1][y] = i
                tmp.add((x-1,y))
        if x < h-1:
            if s[x+1][y] == "." and num[x+1][y] == -1:
                num[x+1][y] = i
                tmp.add((x+1,y))
        if y > 0:
            if s[x][y-1] == "." and num[x][y-1] == -1:
                num[x][y-1] = i
                tmp.add((x,y-1))
        if y < w-1:
            if s[x][y+1] == "." and num[x][y+1] == -1:
                num[x][y+1] = i
                tmp.add((x,y+1))
    now = tmp
if num[-1][-1] == -1:
    print(-1)
else:
    print(h * w-num[-1][-1]-sum([s[i].count("

Solution (Python):
h,w = map(int,input().split())
s = [str(input()) for i in range(h)]
num = [[-1] * w for i in range(h)]
num[0][0] = 0
now = {(0,0)}
for i in range(1,2501):
    tmp = set()
    for x,y in now:
        if x > 0:
            if s[x-1][y] == "." and num[x-1][y] == -1:
                num[x-1][y] = i
                tmp.add((x-1,y))
        if x < h-1:
            if s[x+1][y] == "." and num[x+1][y] == -1:
                num[x+1][y] = i
                tmp.add((x+1,y))
        if y > 0:
            if s[x][y-1] == "." and num[x][y-1] == -1:
                num[x][y-1] = i
                tmp.add((x,y-1))
        if y < w-1:
            if s[x][y+1] == "." and num[x][y+1] == -1:
                num[x][y+1] = i
                tmp.add((x,y+1))
    now = tmp
if num[-1][-1] == -1:
    print(-1)
else:
    print(h * w-num[-1][-1]-sum([s[i].count("

Solution (Python):
from collections import deque
h,w=map(int,input().split())
p=[list("
s0,s1=1,1
g0,g1=h,w
p[s0][s1]=0
d=[(1,0),(-1,0),(0,1),(0,-1)]
q=deque([[s0,s1]])
while q:
    x,y=q.popleft()
    for dx,dy in d:
        if p[x+dx][y+dy]==".":
            p[x+dx][y+dy]=p[x][y]+1
            q.append([x+dx,y+dy])
if p[g0][g1]=='.':
    print(-1)
else:
    yy=0
    for i in range(1,h+1):
        for j in range(1,w+1):
            if p[i][j]=='
                yy+=1
    print(h*w-p[g0][g1]-yy-1)

Solution (Python):
h,w=map(int,input().split())
s=['
s+=['
s.append('
h+=2
w+=2
p=[[1,0],[0,1],[-1,0],[0,-1]]
st=[]
cnt=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='.':
            cnt+=1
ans=0
n=[(1,1)]
route={n[0]:0}
count=0
while n:
    count+=1
    n2=[]
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if s[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                route[np]=count
    n=n2
if route.get((h-2,w-2),-1)>=0:
    print(cnt-route.get((h-2,w-2),-1)-1)
else:
    print(-1)

Solution (Python):
h,w=map(int,input().split())

field=[list(input())for i in range(h)]
cnt=0
for i in field:
    for j in i:
        if j=='
            cnt+=1
dp=[[0 for i in range(w)]for i in range(h)]

dydx=[[-1,0],[1,0],[0,-1],[0,1]]

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

while queue:
    ny,nx=queue.pop(0)
    for dy,dx in dydx:
        nny,nnx=ny+dy,nx+dx
        if 0<=nny<=h-1 and 0<=nnx<=w-1 and field[nny][nnx]!="
            dp[nny][nnx]=dp[ny][nx]+1
            queue.append([nny,nnx])
            if nny==h-1 and nnx==w-1:
                print(h*w-cnt-dp[h-1][w-1]-1)
                exit()
print(-1)

Solution (Python):
import collections
H,W=map(int,input().split())
s=[list(input()) for i in range(H)]
kuro=0
siro=0
for h in range(H):
    for w in range(W):
        if s[h][w]=="
            kuro+=1
        else:
            siro+=1



visited=[[0 for i in range(W)] for h in range(H)]
visited[0][0]=1
stack=collections.deque([[0,0,1]])
flag=0
while stack and not flag:

    y,x,m=stack.popleft()
    lst=[]
    if y>0:lst.append([-1,0])
    if y<H-1:lst.append([1,0])
    if x>0:lst.append([0,-1])
    if x<W-1:lst.append([0,1])
    for y1,x1 in lst:
        Y=y+y1
        X=x+x1
        if Y==H-1 and X==W-1:
            flag=1
            m+=1
            break
        if not visited[Y][X] and s[Y][X]==".":
            stack.append([Y,X,m+1])
            visited[Y][X]=1

print((siro-(m)) if flag else -1)

Solution (Python):
from collections import deque
import itertools

def bfs(graph, sh, sw):
    td = deque([[sh, sw]])
    graph[sh][sw] = "0"
    while td:
        h, w = td.popleft()
        num = int(graph[h][w])
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_h, new_w = h + j, w + k
            if new_h == gy and new_w == gx:
                return num + 1
                break
            
            if new_h < 0 or new_h >= H or new_w < 0 or new_w >= W:
                continue
            elif graph[new_h][new_w] == ".":
                graph[new_h][new_w] = str(num + 1)
                td.append([new_h, new_w])

    return -1

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

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

bcnt = 0

for s, t in itertools.product(range(H), range(W)):
    if ls[s][t] == "
        bcnt += 1

nurazu = bfs(ls, sy, sx)
nurazu = nurazu + 1

if nurazu == 0:
    print(-1)
else:
    print(H * W - (bcnt + nurazu))

Solution (Python):

from collections import deque
def bfs(sy,sx,gy,gx):
    q = deque([[sy,sx]])
    visited[sy][sx]=0
    while q:
        y,x = q.popleft()
        if [y,x]==[gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if ny<0 or ny>h-1 or nx<0 or nx>w-1 or path[ny][nx]=="
                continue
            if path[ny][nx]=="." and visited[ny][nx]==-1:
                visited[ny][nx]=visited[y][x]+1
                q.append([ny,nx])

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

ans=0
black=0
for p in path:
    black+=p.count('
if visited[gy][gx]==-1:
    print(-1)
else:
    ans=h*w-(visited[gy][gx]+1)-black
    print(ans)

Solution (Python):
from collections import deque

h,w = map(int,input().split())
s = [None]*h

for i in range(h):
    s[i] = input()

d = [[10000000 for i in range(w)] for j in range(h)]
sharp = 0

sx,sy = 0,0
gx,gy = w-1 , h-1
            
dx = [1,0,-1,0]
dy = [0,1,0,-1]

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

def bfs():
    d[sy][sx] = 0
    que = deque([[sy,sx]])
    
    while que:
        y,x = que.popleft()
        
        for k in range(4):
            nx = x + dx[k]
            ny = y + dy[k]
            
            if 0<=nx and nx<w and 0<=ny and ny<h and s[y][x] != '
                if d[ny][nx] > d[y][x]+1:
                    d[ny][nx]=d[y][x]+1
                    que.append([ny,nx])
                    
    if d[gy][gx] == 10000000:
        print("-1")
    else:
        print(w*h - sharp - (d[gy][gx]+1))
        
bfs()

Solution (Python):
from collections import deque 
import sys
H, W = map(int, input().split())
city = []
dot_count = 0
for i in range(H):
    city.append(input())
    dot_count += city[i].count('.')
search_point = deque([[0, 0, 0]])
direction_list = [[1,0],[-1,0],[0,1],[0,-1]]
searched_point = [[False for _ in range(W)] for _ in range(H)]
while search_point:
    now_point = search_point.popleft()
    for direction in direction_list:
        next_point = [now_point[0] + direction[0], now_point[1] + direction[1], now_point[2] + 1]
        if next_point[0] < 0 or next_point[0] >= H or next_point[1] < 0 or next_point[1] >= W \
        or city[next_point[0]][next_point[1]] == '
            continue
        if next_point[0] == H-1 and next_point[1] == W-1:
            print(dot_count - next_point[2] - 1)
            sys.exit()
        searched_point[next_point[0]][next_point[1]] = True
        search_point.append(next_point)
print("-1")

Solution (Python):
from collections import deque

def bfs(y,x):
    f=[[float("inf")]*(w+1) for i in range(h+1)]
    f[y][x]=0
    que=deque([])
    que.append((y,x))
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    while que:
        p=que.popleft()
        if p[0]==h and p[1]==w:
            break
        for i in range(4):
            nx=p[1]+dx[i]
            ny=p[0]+dy[i]
            if 0<=nx<w+1 and 0<=ny<h+1 and f[ny][nx]==float("inf") and maze[ny][nx]!="
                que.append((ny,nx))
                f[ny][nx]=f[p[0]][p[1]]+1
    return f[h][w]

h,w=map(int,input().split())
h-=1
w-=1
maze=[list(input()) for i in range(h+1)]

cnt=0
for i in range(h+1):
    for j in range(w+1):
        if maze[i][j]==".":
            cnt+=1
route=bfs(0,0)
score=cnt-route-1
if 0<route<float("inf"):
    print(score)
else:
    print(-1)

Solution (Python):
h,w=map(int,input().split())
li=[input() for i in range(h)]
black=0
for i in li:
  temp=i.count("
  black+=temp

zenbu="
li.insert(0,zenbu)
li.append(zenbu)

for i in range(h+2):
  li[i]="
  li[i]+="

ys,xs=2,2
yg,xg=h+1,w+1
a=li

n=[(ys-1,xs-1)]
route={n[0]:0}
p=[[1,0],[0,1],[-1,0],[0,-1]]
count=1
while route.get((yg-1,xg-1),0)==0 and count != 10000:
    n2=[]
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                route[np]=count
    n=n2
    count+=1
if count==10000:
  print(-1)
else:
  print(h*w-black-count)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if s[y][x]!='.':
        continue
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H:
            q_append((nx,ny,l+1))
else:
    print(-1)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if s[y][x]!='.':
        continue
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H:
            q_append((nx,ny,l+1))
else:
    print(-1)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if s[y][x]!='.':
        continue
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H:
            q_append((nx,ny,l+1))
else:
    print(-1)

Solution (Python):
from collections import deque

H, W = map(int, input().split())
S = [0]*H
for i in range(H):
    S[i] = input()


T = [[0]* W for h in range(H)]
blocks = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == '
            T[h][w] = -1
            blocks += 1

def is_inside(w, h, W, H):
    if w >= 0 and w < W and h >= 0 and h < H:
        return True
    return False


V = deque([(0, 0)])
while len(V) != 0:
    v = V.popleft()
    
    h = v[0]
    w = v[1]
    t = T[h][w]
    if is_inside(h - 1, w, H, W):
        if T[h - 1][w] != -1 and T[h - 1][w] == 0:
            T[h - 1][w] = t + 1
            V.append((h - 1, w))
    if is_inside(h + 1, w, H, W):
        if T[h + 1][w] != -1 and T[h + 1][w] == 0:
            T[h + 1][w] = t + 1
            V.append((h + 1, w))
    if is_inside(h, w - 1, H, W):
        if T[h][w - 1] != -1 and T[h][w - 1] == 0:
            T[h][w - 1] = t + 1
            V.append((h , w - 1))
    if is_inside(h, w + 1, H, W):
        if T[h][w + 1] != -1 and T[h][w + 1] == 0:
            T[h][w + 1] = t + 1
            V.append((h , w + 1))

t = T[H - 1][W - 1]
if t == 0:
    print(-1)
else:
    print(W * H - blocks - t - 1)

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

H,W = map(int, input().split())
table = []
b_count = 0

for i in range(H):
    s = list(input())
    b_count += s.count("
    table.append(s)

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

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

if dist[-1][-1] == -1:
    print(-1)
else:
    ans = H*W-b_count-(dist[-1][-1]+1)
    print(ans)

Solution (Python):
H, W = map(int, input().split())

s = ['


m = [[-1 for x in range(W+2)] for y in range(H+2)]
m[1][1] = 1


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

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


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

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

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

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

Solution (Python):
from collections import deque
INF = float('inf')
ROAD = '.'
WALL = '
STEPS = [(1, 0), (-1, 0), (0, 1), (0, -1)]


def main():
    H,W = map(int, input().split())
    maze = [None]*H
    white = 0
    
    for i in range(H):
        maze[i] = list(input())
        for j in range(W):
            if maze[i][j] == ROAD:
                white += 1
                maze[i][j] = INF
    
    
    maze[0][0] = 1
    que = deque([[0, 0]])

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

        for (i, j) in STEPS:
            ny, nx = y+i, x+j
            if ny < 0 or ny >= H or nx < 0 or nx >= W:
                continue
            
            target = maze[ny][nx]
            if target != WALL:
                if target > maze[y][x]+1:
                    maze[ny][nx] = maze[y][x] + 1
                    que.append([ny,nx])
    
    if maze[H-1][W-1] == INF:
        print(-1)
    else:
        print(white - maze[H-1][W-1])
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys
input = sys.stdin.readline
H,W=map(int,input().split())
s=[]
s.append("".join("
cnt=0
for i in range(H):
    ss=input().strip()
    s.append("
    for w in range(W):
        if ss[w]==".":
            cnt+=1

s.append("".join("

import sys
sys.setrecursionlimit(300000)
def solv(h,w,cnt):
    
    
    
    if a[h][w]>cnt+1 and s[h][w]==".":
        a[h][w]=cnt+1
        solv(h-1,w,cnt+1)
        solv(h,w-1,cnt+1)
        solv(h+1,w,cnt+1)
        solv(h,w+1,cnt+1)
    return

a=[[1000000]*(W+2) for _ in range(H+2)]
solv(1,1,0)
print(cnt-a[-2][-2] if a[-2][-2]!= 1000000 else -1)

Solution (Python):

from collections import deque


def solve(*args: str) -> str:
    h, w = map(int, args[0].split())
    S = [[c for c in s] for s in args[1:]]

    total = sum(s.count('.') for s in S)

    Q = deque()
    Q.append((0, 0, 1))

    depth = 0
    while Q:
        x, y, n = Q.popleft()
        if S[y][x] == '.':
            S[y][x] = str(n)
            if (x, y) == (w-1, h-1):
                depth = n
                break

            if 0 < x:
                Q.append((x-1, y, n+1))
            if x+1 < w:
                Q.append((x+1, y, n+1))
            if 0 < y:
                Q.append((x, y-1, n+1))
            if y+1 < h:
                Q.append((x, y+1, n+1))

    return str(total-depth if depth else -1)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Solution (Python):
H, W  = map(int, input().split())
f = []
INF = 10**10
dist = [[INF] * W for _ in range(H)]
cnt = 0
for i in range(H):
    S = list(input())
    for j,s in enumerate(S):
        if s == "
    cnt += S.count("
    f.append(s)



mvs = [(0,1),(0,-1),(1,0),(-1,0)]
from collections import deque
s = (0,0)
g = (H-1,W-1)
dist[0][0] = 0
q = deque()
q.append(s)
while q:
    h,w = q.popleft()
    
    for dh, dw in mvs:
        if 0 <= h+dh < H and 0 <= w+dw < W: 
            
            if dist[h+dh][w+dw] == -1:
                continue
            elif dist[h+dh][w+dw] > dist[h][w] + 1:
                q.append((h+dh,w+dw))
                dist[h+dh][w+dw] = dist[h][w] + 1



if dist[H-1][W-1] == INF or dist[H-1][W-1]==-1:
    print(-1)
    exit()
ans = H*W - dist[H-1][W-1] - 1 - cnt
print(ans)

Solution (Python):
h,w = map(int,input().split())

ys,xs=2,2
yg,xg =h+1,w+1

a= []

a.append("".join(["
cnt=0
for i in range(h):
    arrc = input()
    
    m = int(list(arrc).count("
    cnt +=m
    
    arrc = "
    a.append(arrc)

a.append("".join(["

n=[(ys-1,xs-1)]
route={n[0]:0}
p=[[1,0],[0,1],[-1,0],[0,-1]]
count=1
while route.get((yg-1,xg-1),0)==0 and count != 10000:
    n2=[]
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                route[np]=count
                
    n=n2
    count+=1
if list(route.keys()).count((h,w)) == 1:
    vv = h*w - max(list(route.values())) - cnt -1
    print(vv)
else:
    print(-1)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
sy, sx = 1, 1
gy, gx = h, w
map = [input() for _ in range(h)]

cnt = 0
for s in map:
    cnt += s.count(".")

f_inf = float('inf')
maze = [[f_inf] * 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), (-1, 0), (0, 1), (0, -1)):
        next_y, next_x = y + i, x + j
        if next_y > -1 and next_x > -1 and next_y < h and next_x < w and map[next_y][next_x] == ".":
            if maze[next_y][next_x] > maze[y][x] + 1:
                maze[next_y][next_x] = maze[y][x] + 1
                que.append([next_y, next_x])

if maze[gy - 1][gx - 1] != f_inf:
    print(cnt - (maze[gy - 1][gx - 1] + 1))
else:
    print(-1)

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

n_black = 0
for m in M:
  for n in m:
    if n == '
      n_black += 1

si, sj = 0, 0
gi, gj = H - 1, W - 1

queue = []
distance = [[-1 for _ in range(W)] for _ in range(H)]
queue.append((si, sj))
distance[si][sj] = 0

while queue:
  i, j = queue.pop(0)
  if i == gi and j == gj:
    print(H * W - 1 - n_black - distance[i][j])
    exit()
  for i_, j_ in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
    if i_ >= 0 and i_ < H and j_ >= 0 and j_ < W:
      if distance[i_][j_] == -1 and M[i_][j_] == '.':
        distance[i_][j_] = distance[i][j] + 1
        queue.append((i_, j_))
        
print(-1)

Solution (Python):
h, w = map(int, input().split())
maiz = []
edge = ['
point = 0
for _ in range(h):
    line = list(input())
    line = ['
    point += len([i for i in line if i == '.'])
    maiz.append(line)
maiz = [edge] + maiz + [edge]

def bfs(maiz, h, w):
    queue = [[1, 1]]
    visited = [[False]*(w+2) for _ in range(h+2)]
    maiz[1][1] = 0
    while queue:
        x, y = queue.pop(0)
        visited[y][x] = True
        hjkl = [[x-1, y], [x, y-1], [x+1, y], [x, y+1]]
        for dx, dy in hjkl:
            if (maiz[dy][dx] == '.') and (visited[dy][dx] is False):
                queue.append([dx, dy])
                maiz[dy][dx] = maiz[y][x]+1
    tf = False if maiz[h][w] == '.' else True
    return maiz[h][w], tf

n, tf = bfs(maiz, h, w)
if tf is False:
    print(-1)
    exit()

print(point-n-1)