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
black = 0
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

r,c = [int(x) for x in input().split()]
sy,sx = [0,0]
gy,gx = [r-1,c-1]
m = []
for _ in range(r):
    m.append(list(input()))



q = deque()
d = [[-1]*c for i in range(r)]

q.append([sy,sx])
d[sy][sx] = 0
while q:
    v = q.popleft()
    if v == [gy,gx]:
        break
    for i in [[1,0],[-1,0],[0,1],[0,-1]]:
        ny = v[0]+i[0]
        nx = v[1]+i[1]
        if 0<=ny<r and 0<=nx<c and m[ny][nx] == "." and d[ny][nx] == -1:
            q.append([ny,nx])
            d[ny][nx] = d[v[0]][v[1]] + 1


count = 0
for i in m:
    for j in i:
        if j==".":
            count += 1
if d[gy][gx] == -1:
    print(-1)
else:
    ans = count - d[gy][gx] - 1
    print(ans)

Solution (Python):
INF = 1000000000

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

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

dist = [[INF for i in range(w)] for j in range(h)]

dist[0][0] = 1

que = [[0, 0]]

while len(que) > 0:
    p = que.pop(0)

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

    for x, y in zip(dx, dy):
        nx = p[0] + x
        ny = p[1] + y

        if 0 <= nx < h and 0 <= ny < w and S[nx][ny] == '.' and dist[nx][ny] == INF:
            que.append([nx, ny])
            dist[nx][ny] = dist[p[0]][p[1]] + 1

if dist[h-1][w-1] == INF:
    print(-1)
else:
    ans = 0
    for s in S:
        ans += s.count('.')
    ans -= dist[h-1][w-1]
    print(ans)

Solution (Python):
import numpy as np

H, W = map(int, input().split())
G = [list(input()) for _ in range(H)]
visited = [[-1]*W for _ in range(H)]
que = [[0,0]]
direction = [[1,0],[0,1],[-1,0],[0,-1]]
visited[0][0] = 1
while que:
  h, w = que.pop(0)
  for dh, dw in direction:
    if h+dh<0 or H<=h+dh or w+dw<0 or W<=w+dw:
      continue
    if G[h+dh][w+dw] == '
      continue
    if visited[h+dh][w+dw] != -1:
      continue
    que.append([h+dh, w+dw])
    visited[h+dh][w+dw] = visited[h][w]+1
cnt = 0
for i in range(H):
  for j in range(W):
    if G[i][j] == '
      cnt += 1
if visited[H-1][W-1] != -1:
  ans = H*W-visited[H-1][W-1]-cnt
else:
  ans = -1
print(ans)

Solution (Python):
from collections import deque

def bfs():
    q = deque()
    st = [1, 1]
    go = [h, w]
    q.append(st)
    d[1][1] = 1
    v = [1, -1]
    while q:
        u = q.popleft()
        x, y = u[0], u[1]
        for i in range(2):
            if s[x + v[i]][y] == "." and d[x + v[i]][y] == 0:
                q.append([x + v[i], y])
                d[x + v[i]][y] = d[x][y] + 1
        for i in range(2):
            if s[x][y + v[i]] == "." and d[x][y + v[i]] == 0:
                q.append([x, y + v[i]])
                d[x][y + v[i]] = d[x][y] + 1
    c = 0
    for i in s:
        for j in i:
            if j == ".":
                c += 1
    if d[h][w] == 0:
        return -1
    return c - d[h][w]

h, w = map(int, input().split())
s = [["
t = ["
s.append(t)
s.insert(0, t)
d = [[0 for _ in range(w + 2)] for _ in range(h + 2)]
print(bfs())

Solution (Python):
import queue

def bfs(s1,s2):
    global ans
    queueX = queue.Queue()
    queueY = queue.Queue()
    queueX.put(s1)
    queueY.put(s2)
    s[s1][s2] = 0
    while queueX.empty() == False:
        x = queueX.get()
        y = queueY.get()

        for i in range(4):
            nextX = x + moveR[i]
            nextY = y + moveC[i]
            if 0 <= nextX and nextX < H\
                and 0 <= nextY and nextY < W\
                and s[nextX][nextY] != '
                and s[nextX][nextY] == '.':
                s[nextX][nextY] = s[x][y] + 1
                queueX.put(nextX)
                queueY.put(nextY)

H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
cnt = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == '
            cnt += 1
moveR = [0, 1, -1, 0]
moveC = [1, 0, 0, -1]
bfs(0,0)
if s[H - 1][W - 1] == '.':
    print(-1)
else:
    print(H * W - cnt - s[H - 1][W - 1] - 1)

Solution (Python):
H, W = map(int, input().split())
s = []
nb = 0
for _ in range(H):
    s.append(list(input()))
    nb += s[-1].count("

nw = H * W - nb

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

q = [[sy, sx]]
visited = [[int(1e10)]*W for _ in range(H)]
visited[sy][sx] = 0
while q:
    ty, tx = q.pop(0)
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        ny, nx = ty + dy, tx + dx
        if 0 <= ny < H and 0 <= nx < W and s[ny][nx] != "
            if visited[ny][nx] > visited[ty][tx] + 1:
                visited[ny][nx] = visited[ty][tx] + 1
                q.append([ny, nx])
    if [gy, gx] in q:
        temp = visited[gy][gx]
        break
if visited[gy][gx] == int(1e10):
    print(-1)
else: print(nw - temp - 1)

Solution (Python):
from collections import deque


def bfs():
    d = [[float("inf")]*w for i in range(h)]
    que = deque([])
    que.append((0, 0))
    d[0][0] = 1

    while que:
        p = que.popleft()
        if p[0] == h - 1 and p[1] == w - 1:
            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 f[nx][ny] != "
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[h-1][w-1]


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

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

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

ans = bfs()
if ans != float("inf"):
    print(white - ans)
else:
    print(-1)

Solution (Python):
from collections import deque

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

que = deque([(0, 0, 1)])
minDist = [[10**10] * W for _ in range(H)]

while que:
    h, w, d = que.popleft()

    if minDist[h][w] <= d:
        continue
    minDist[h][w] = d

    if (h, w) == (H - 1, W - 1):
        break

    for dh, dw in zip([0, 0, 1, -1], [1, -1, 0, 0]):
        toH, toW = h + dh, w + dw
        if 0 <= toH < H and 0 <= toW < W and A[toH][toW] == '.':
            que.append((toH, toW, d + 1))

if minDist[H - 1][W - 1] == 10**10:
    print(-1)
    exit()

white = sum([a.count('.') for a in A])
print(max(0, white - minDist[H - 1][W - 1]))

Solution (Python):
from collections import deque

def dfs(sx, sy ,gx, gy):             
    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

    white = 0

    for m in maze:
        white += m.count(".")

    while que:
        
        now = que.popleft()
        
        if now[0] == gx and now[1] == gy:
            break
        for i in range(4):
            nx = now[0] + dx[i]
            ny = now[1] + dy[i]
            
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "
                
                que.append((nx, ny))
                
                d[nx][ny] = d[now[0]][now[1]] + 1

    if d[gx][gy] == float("inf"):
       return -1
    else:
        return white - d[gx][gy] - 1

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

print(dfs(0, 0, h - 1, w - 1))

Solution (Python):
from collections import deque

H,W = map(int,input().split())
c =[]
c.append(['
ans = [[0 for _ in range(W+2)]for _ in range(H+2)]
score = 0
for i in range(H):
    tmp = list('
    c.append(tmp)
    for j in range(W+2):
        if tmp[j] == '.':
            score += 1

c.append(['
q = deque()

def bfs(x,y):
    q.append([x,y])
    while q:
        x,y = q.popleft()
        if [x,y] == [W,H]:
            return ans[H][W]
        if c[y][x-1] == '.':
            q.append([x-1,y])
            ans[y][x-1] = ans[y][x] + 1
            c[y][x-1] = '
        if c[y][x+1] == '.':
            q.append([x+1,y])
            ans[y][x+1] = ans[y][x] + 1
            c[y][x+1] = '
        if c[y-1][x] == '.':
            q.append([x,y-1])
            ans[y-1][x] = ans[y][x] + 1
            c[y-1][x] = '
        if c[y+1][x] == '.':
            q.append([x,y+1])
            ans[y+1][x] = ans[y][x] + 1
            c[y+1][x] = '
    return -1

tmp = bfs(1,1)
if tmp == -1:
    print(-1)
else:
    print(score - tmp - 1)

Solution (Python):
from collections import deque
def bfs(sy,sx):
    dis=[[0]*W for i in range(H)]
    q=deque()
    q.append([sy,sx])
    while(len(q)!=0):
        y=q[0][0]
        x=q[0][1]
        q.popleft()
        for dy,dx in ([0, 1], [1, 0], [0, -1], [-1, 0]):
            ny=y+dy
            nx=x+dx
            if ny<0 or ny>=H or nx<0 or nx>=W:
                continue
            if field[ny][nx]=="
                continue
            if dis[ny][nx]!=0:
                continue
            dis[ny][nx]=dis[y][x]+1
            q.append([ny,nx])
    if dis[H-1][W-1]==0:
        print(-1)
        exit()
    return dis[H-1][W-1]


H,W=map(int,input().split())
field=[input() for i in  range(H)]
O=0
for i in range(H):
    O+=field[i].count(".")
ans=O-1-bfs(0,0)
print(ans)

Solution (Python):
from collections import deque


dir_x = [1, 0, -1, 0]
dir_y = [0, 1, 0, -1]
def bfs(y, x):
    for i in range(4):
        next_y = y + dir_y[i]
        next_x = x + dir_x[i]
        if 0 <= next_y < H and 0 <= next_x < W and maze[next_y][next_x] == "." and dist[next_y][next_x] == -1:
            que.append((next_y, next_x))
            dist[next_y][next_x] = dist[y][x] + 1


H, W = map(int, input().split())
sy, sx = 0, 0
maze = []
empty_count = 0
for i in range(H):
    maze.append(input())
    empty_count += maze[i].count(".")

dist = [[-1]*(W+1) for _ in range(H+1)]
dist[sy][sx] = 0
que = deque([(sy, sx)])

while len(que) > 0:
    y, x = que.popleft()
    bfs(y, x)

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

Solution (Python):
from collections import deque
h,w = map(int,input().split())
maze = [['']*w]*h
wcnt = 0
for i in range(h):
  temp = list(input())
  wcnt += temp.count('.')
  maze[i] = temp
que = deque()
que.append([0,0])
d = [[float('inf')]*w for i in range(h)]
d[0][0] = 0
dx = [0,-1,0,1]
dy = [-1,0,1,0]
while que:
    [px,py] = que.popleft()
    for i in range(4):
        nx = px + dx[i]
        ny = py + dy[i]
        if 0<=nx<h and 0<=ny<w and maze[nx][ny] == '.' and d[nx][ny] == float('inf'):
            d[nx][ny] = d[px][py] + 1
            que.append([nx,ny])
if d[h-1][w-1] == float('inf'):
    ans = -1
else:
    ans = wcnt - d[h-1][w-1] - 1
print(ans)

Solution (Python):
H, W = list(map(int, input().split()))
grid = []
for _ in range(H):
    grid.append(list(input()))
dist_grid = [[-1 for _ in range(W)] for __ in range(H)]

queue = [(0, 0)]
dist_grid[0][0] = 1
while queue:
    h, w = queue.pop(0)
    nexts = [(h+1, w), (h-1, w), (h, w+1), (h, w-1)]
    for y, x in nexts:
        if y < 0 or H <= y or x < 0 or W <= x:
            continue
        if dist_grid[y][x] == -1 and grid[y][x] == '.':
            dist_grid[y][x] = dist_grid[h][w] + 1
            queue.append((y, x))
            
sharp_num = 0
for h in range(H):
    for w in range(W):
        if grid[h][w] == '
            sharp_num += 1

if dist_grid[-1][-1] == -1:
    print(-1)
else:
    print(H * W - dist_grid[-1][-1] - sharp_num)

Solution (Python):
import sys
from collections import deque
 
h,w = map(int, sys.stdin.readline().split())
maze = [list(sys.stdin.readline()) for _ in range(h)]
dis = [[-1 for _ in range(w)] for _ in range(h)]
 
que = deque()
que.append((0,0))
dis[0][0] = 1
 
while que:
    y,x = que.popleft()
    for dx, dy in ((1,0), (0,1), (-1, 0), (0, -1)):
        nx = x + dx
        ny = y + dy
        if (nx < 0) or (nx > w-1) or (ny < 0) or (ny > h-1): continue
        if (maze[ny][nx] == '.') and (dis[ny][nx] == -1):
            dis[ny][nx] = dis[y][x] + 1
            que.append((ny, nx))
 
ans = 0
black_num = 0
for m in maze:
    black_num += m.count('
 
if dis[h-1][w-1] == -1:
    ans = -1
else:
    ans = w*h - black_num - dis[h-1][w-1]
 
print(ans)

Solution (Python):
H,W=map(int,input().split())
s=["
m=0
for i in range(H):
    s.append(input())
    m+=s[-1].count(".")
s.append("
for i in range(H+2):
    s[i]="
l=[[-1]*(W+2) for i in range(H+2)]
l[1][1]=1
b=[(1,1)]
c=2
while b:
    a=[]
    for i in b:
        if s[i[0]][i[1]+1]=="." and l[i[0]][i[1]+1]==-1:
            l[i[0]][i[1]+1]=c
            a.append((i[0],i[1]+1))
        if s[i[0]-1][i[1]]=="." and l[i[0]-1][i[1]]==-1:
            l[i[0]-1][i[1]]=c
            a.append((i[0]-1,i[1]))
        if s[i[0]+1][i[1]]=="." and l[i[0]+1][i[1]]==-1:
            l[i[0]+1][i[1]]=c
            a.append((i[0]+1,i[1]))
        if s[i[0]][i[1]-1]=="." and l[i[0]][i[1]-1]==-1:
            l[i[0]][i[1]-1]=c
            a.append((i[0],i[1]-1))
    c+=1
    b=a
if l[-2][-2]==-1:
    print(-1)
else:
    print(m-l[-2][-2])

Solution (Python):
import sys
from collections import deque

h,w = map(int, sys.stdin.readline().split())
maze = [list(sys.stdin.readline()) for _ in range(h)]
dis = [[-1 for _ in range(w)] for _ in range(h)]

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

while que:
    y,x = que.popleft()
    for dx, dy in ((1,0), (0,1), (-1, 0), (0, -1)):
        nx = x + dx
        ny = y + dy
        if (nx < 0) or (nx > w-1) or (ny < 0) or (ny > h-1): continue
        if (maze[ny][nx] == '.') and (dis[ny][nx] == -1):
            dis[ny][nx] = dis[y][x] + 1
            que.append((ny, nx))

ans = 0
black_num = 0
for m in maze:
    black_num += m.count('

if dis[h-1][w-1] == -1:
    ans = -1
else:
    ans = w*h - black_num - dis[h-1][w-1]

print(ans)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
s=[]
for i in range(H):
    S=input()
    s.append(S)
w_count=0
for i in range(H):
    for j in range(W):
        if s[i][j]==".":
            w_count+=1
count=[[10**9 for i in range(W)]for j in range(H)]
chk=[[0 for i in range(W)]for j in range(H)]
rl=[1,-1]
up=[1,-1]
q=deque([(0,0)])
count[0][0]=1
chk[0][0]=1

while(q):
    
    a,b=q.popleft()
    
    for i in rl:
        r=b+i
        if r>=0 and r<W:
            if s[a][r]==".":
                count[a][r]=min(count[a][r],count[a][b]+1)
                
                if chk[a][r]==0:
                    q.append((a,r))
                chk[a][r]=1
    for i in up:
        u=a+i
        if u>=0 and u<H:
            if s[u][b]==".":
                count[u][b]=min(count[u][b],count[a][b]+1)
                
                if chk[u][b]==0:
                    q.append((u,b))
                chk[u][b]=1

ans=w_count-count[H-1][W-1]

if count[-1][-1]==10**9:
    print(-1)
    exit()



print(ans)

Solution (Python):
from collections import deque
def bfs(S,H,W):
    que = deque([(0,0)])
    dist = [[2**60]*W for _ in range(H)]
    dist[0][0] = 0
    while que:
        u = que.popleft()
        d = [-1,1]
        y,x = u
        for i in range(2):
            s = x+d[i]
            t = y+d[i]
            if 0 <= s < W:
                if S[y][s] == '.':
                    if dist[y][s] == 2**60:
                        que.append((y,s))
                    dist[y][s] = min(dist[y][s],dist[y][x]+1)
            if 0 <= t < H:
                if S[t][x] == '.':
                    if dist[t][x] == 2**60:
                        que.append((t,x))
                    dist[t][x] = min(dist[t][x],dist[y][x]+1)
    return dist[-1][-1]

def main():
    H,W = map(int,input().split(" "))
    S = []
    total = -1
    for _ in range(H):
        s = input()
        total += s.count('.')
        S.append(s)
    num = bfs(S,H,W)
    if num == 2**60:
        ans = -1
    else:
        ans = total-num
    
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):


from collections import deque
from sys import setrecursionlimit

setrecursionlimit(10 ** 9)

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

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

queue = deque([])
seen = [[0] * W for i in range(H)]
prev_x = [[0] * W for i in range(H)]
prev_y = [[0] * W for i in range(H)]
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]


def bfs(y, x):
    queue.append([y, x])
    seen[y][x] = 1
    prev_x[y][x] = -1
    prev_y[y][x] = -1

    while len(queue) != 0:
        y, x = queue.popleft()

        for dy, dx in direction:
            next_x = x + dx
            next_y = y + dy

            if next_x < 0 or next_x >= W or next_y < 0 or next_y >= H:
                continue
            elif field[next_y][next_x] == "
                continue
            elif seen[next_y][next_x] != 0:
                continue
            else:
                seen[next_y][next_x] = 1
                prev_x[next_y][next_x] = x
                prev_y[next_y][next_x] = y
                queue.append([next_y, next_x])


shortest_path = [[0] * W for i in range(H)]


def path_restoration(y, x):
    shortest_path[y][x] = 1

    if prev_x[y][x] == -1 and prev_y[y][x] == -1:
        return
    else:
        next_y = prev_y[y][x]
        next_x = prev_x[y][x]
        path_restoration(next_y, next_x)


bfs(0, 0)
path_restoration(H - 1, W - 1)

ans = 0

for i in range(H):
    for j in range(W):
        if field[i][j] == "." and shortest_path[i][j] == 0:
            field[i][j] = "
            ans += 1

if seen[H - 1][W - 1] == 0:
    
    print(-1)
else:
    print(ans)

Solution (Python):
from collections import deque

A, B = [-1, 0, 0, 1], [0, -1, 1, 0]


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

GRID = []
black = 0
for _ in range(h):
    s = input()
    black += s.count("
    GRID.append("
GRID = ["


DISTANCE = [[0] * (w + 2) for _ in range(h + 2)]

DISTANCE[1][1] = 1
QUEUE = deque([(1, 1)])
while QUEUE:
    i, j = QUEUE.popleft()
    for a, b in zip(A, B):
        if GRID[i + a][j + b] == "
            continue
        if DISTANCE[i + a][j + b] != 0:
            continue
        DISTANCE[i + a][j + b] = DISTANCE[i][j] + 1
        QUEUE.append((i + a, j + b))


if DISTANCE[h][w] == 0:
    print(-1)
else:
    print(h * w - DISTANCE[h][w] - black)

Solution (Python):
def bfs(queue, visited):
  while len(queue) > 0:
    y, x = queue.pop(0)
    for delta_y, delta_x in [[1,0],[-1,0],[0,1],[0,-1]]:
      new_y , new_x = y + delta_y, x + delta_x 
      if new_y < 0 or new_x < 0 or new_y >= h or new_x >= w:
        continue 
      if c[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 visited


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

cnt = 0
for tate in c:
    for yoko in tate:
        if yoko == ".":
            cnt +=1

visited = [[-1]*w for _ in range(h)]
queue = []
sy, sx = 0, 0
visited[sy][sx] = 0 
queue.append([sy,sx])
visited = bfs(queue, visited)

if visited[h-1][w-1] == -1:
    print(-1)
else:
    print(cnt-visited[h-1][w-1]-1)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
maze = [list(input()) for _ in range(h)]
visited = [[-1] * w for _ in range(h)]
move = [(1,0), (0,1), (-1,0), (0,-1)]

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

queue = deque([(sy, sx, 0)])

while queue:
    y, x, dist = queue.popleft()
    for dy, dx in move:
        if maze[y+dy:y+dy+1] and maze[y+dy][x+dx:x+dx+1]:
            if maze[y+dy][x+dx] == "." and visited[y+dy][x+dx] == -1:
                visited[y+dy][x+dx] = dist + 1
                queue.append((y+dy, x+dx, dist+1))
shortest_distance = visited[gy][gx]

if shortest_distance == -1:
    print("-1")
else:
    white_count = 0
    for row in maze:
        for cell in row:
            if cell == ".":
                white_count += 1

    score = white_count - 1 - shortest_distance
    print(score)

Solution (Python):
def main():
    height, width = map(int, input().split())
    grid = []
    initial_white = 0
    for _ in range(height):
        g = input()
        initial_white += g.count(".")
        grid.append(list(g))
    count = [[0 for _ in range(width)] for _ in range(height)]
    next_search = [(0, 0)]
    grid[0][0] = "
    while not next_search == []:
        now = next_search.pop(0)
        for d in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            next_index = (now[0] + d[0], now[1] + d[1])
            if next_index[0] < 0 or height <= next_index[0] or next_index[1] < 0 or width <= next_index[1]:
                continue
            elif grid[next_index[0]][next_index[1]] == ".":
                grid[next_index[0]][next_index[1]] = "
                count[next_index[0]][next_index[1]] = count[now[0]][now[1]] + 1
                next_search.append(next_index)
    print(initial_white - count[-1][-1] - 1 if count[-1][-1] > 0 else -1)


if __name__ == '__main__':
    main()

Solution (Python):
h, w = map(int, input().split())
field = []
ans = 0
white = 0
for i in range(h):
    t = list(input())
    white += t.count(".")
    field.append(t)

next_point = []
next_point_cand = []

start = (0, 0)
d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
count = 1 
next_point.append(start)
field[0][0] = 0

while True:
    for (y, x) in next_point:
        for (dy, dx) in d:
            if 0 <= (x + dx) <= (w - 1) and 0 <= (y + dy) <= (h - 1):
                if field[y + dy][x + dx] == ".":
                    field[y + dy][x + dx] = count
                    next_point_cand.append((y + dy, x + dx))
    next_point.clear()
    next_point.extend(next_point_cand)
    next_point_cand.clear()
    count += 1

    if len(next_point) == 0:
        ans = -1
        break

    if (h - 1, w - 1) in next_point:
       ans = count 
       break


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

else:
    print(white - count)

Solution (Python):
H,W=map(int, input().split())
S=[]
S.append(list(['X']*(W+2)))
for h in range(H):
    S.append(['X']+list(input())+['X'])
S.append(list(['X']*(W+2)))

from collections import deque
q=deque([[1,1]])
d=[(1,0),(-1,0),(0,1),(0,-1)]
S[1][1]=0

cnt_nm=0
for h in range(H+2):
    for w in range(W+2):
        if S[h][w]=='
            cnt_nm+=1

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

    for dy,dx in d:
        if S[y+dy][x+dx]=='.':
            q.append([y+dy,x+dx])
            S[y+dy][x+dx]=S[y][x]+1

if S[H][W]=='.':
    print('-1')
else:
    print(H*W-cnt_nm-S[H][W]-1)

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

que = deque([[0,0]])
seen = [[-1]*W for _ in range(H)]
seen[0][0] = 0
count = 0
for i in range(H):
    for j in range(W):
        if map[i][j]=="
            seen[i][j] = -2
        else:
            count +=1

while que:
    y, x = que.popleft()
    for dy, dx in ([0,1],[1,0],[0,-1],[-1,0]):
        ny, nx = y+dy, x+dx
        if 0<=ny<H and 0<=nx<W and seen[ny][nx]==-1 and map[ny][nx] != "
            seen[ny][nx] = seen[y][x] + 1
            que.append([ny, nx])



max = seen[H-1][W-1]
if max >=0:
    cnt = count-max-1
elif max ==-1:
    cnt = -1
print(cnt)

Solution (Python):
h, w = map(int, input().split())
maze = [list(input()) for _ in range(h)]
from collections import deque
def bfs(maze, sy, sx, gy, gx):
    d = [[-1] * w for _ in range(h)]
    que = deque([[sy, sx]])
    
    d[sy][sx] = 0
    while que:
        y, x = que.popleft()
        if y == gy and x == gx:
            break
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            ny, nx = y + j, x + k
            if 0 <= nx < w  and 0 <= ny < h  and d[ny][nx] == -1 and maze[ny][nx] != "
                d[ny][nx] = d[y][x] + 1
                que.append([ny, nx])
                
    return d
gx, gy = w - 1, h - 1
def counting(maze, h, w, aim):
    cnt = 0
    for i in range(h):
        for j in range(w):
            if maze[i][j] == aim:
                cnt += 1
    return cnt
a = bfs(maze, 0, 0, gy, gx)
if a[gy][gx] == -1:
    print(-1)
else:
    print(h * w - (counting(maze, h, w, '

Solution (Python):
from collections import deque

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

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

while q:
    x, y = q.popleft()
    for dx, dy in d:
        nx = x + dx
        ny = y + dy
        if nx < 0 or nx >= W or ny < 0 or ny >= H:
            continue
        if S[ny][nx] == "." and c[ny][nx] is -1:
            c[ny][nx] = c[y][x] + 1
            q.append((nx, ny))

c_min = c[H - 1][W - 1]

if c_min == -1:
    ans = -1
else:
    ans = sum([s.count(".") for s in S]) - c_min

print(ans)

Solution (Python):
h,w=map(int,input().split())
g=[list(input()) for _ in range(h)]
dyx=[(1,0),(-1,0),(0,1),(0,-1)]
from collections import deque
q=deque()
q.append((0,0))
g[0][0]=0
while q:
    ny,nx=q.popleft()
    for dy,dx in dyx:
        y=ny+dy
        x=nx+dx
        if 0<=y<h and 0<=x<w and g[y][x]==".":
            g[y][x]=1+g[ny][nx]
            q.append((y,x))
if g[h-1][w-1]=="." or g[h-1][w-1]=="
    print(-1)
    exit()

d={}
ans=0
x=g[h-1][w-1]
for i in range(h):
    for j in range(w):
        if g[i][j]==".":
            ans+=1
            g[i][j]="@"
            continue
        if g[i][j]=="
            continue
        if g[i][j] in d:
            ans+=1
            g[i][j]="@"
        else:
            if g[i][j]>x:
                ans+=1
                g[i][j]="@"
            d[g[i][j]]=1

print(ans)

Solution (Python):
from collections import deque

H, W = map(int, input().split())
edges = ['
field = [edges]
dyx = [(0, 1), (0, -1), (1, 0), (-1, 0)]
bk = 0
for _ in range(H):
    line = list(input())
    bk += line.count('
    field.append(['
field.append(edges)

steps = 1
q = deque()
field[1][1] = 1
q.append((1, 1, 1))

while q:
    cy, cx, lv = q.popleft()

    for dy, dx in dyx:
        ny, nx = dy+cy, dx+cx

        if field[ny][nx] == '.':
            field[ny][nx] = lv+1
            q.append((ny, nx, lv+1))
steps = str(field[H][W])
if steps.isnumeric():
    print(W*H-bk-int(steps))
else:
    print(-1)

Solution (Python):
from collections import deque
h, w = map(int, input().split())
bord = [list(input()) for _ in range(h)]
visit = [[-1 for _ in range(w)] for _ in range(h)]
visit[0][0] = 1


q = deque([[0,0]])
visit[0][0] = 1
while q:
    px, py = q.popleft()
    for i, j in ([1,0],[-1,0],[0,1],[0,-1]):
        if px+i >= 0 and px+i < h and py+j >= 0 and py+j < w:
            if bord[px+i][py+j] == "." and visit[px+i][py+j] < 0:
                visit[px+i][py+j] = visit[px][py]+1
                q.append([px+i, py+j])
if visit[h-1][w-1] < 0:
    print(-1)
else:
    c = [i.count(".") for i in bord]
    print(sum(c)-visit[h-1][w-1])

Solution (Python):
import sys
input = sys.stdin.readline
 
H, W = [int(x) for x in input().split()]
s = []
W_count = 0
for _ in range(H):
    tmp = list(input().rstrip())
    s.append(tmp)
    W_count += tmp.count('.')

from collections import deque
D = [[-1] * W for _ in range(H)]

def bfs():
    queue = deque([(0, 0, 0, 0)])
    D[0][0] = 0
    while queue:
        u = queue.popleft()
        x = u[0]
        y = u[1]
        D[x][y] = D[u[2]][u[3]] + 1
        for i in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if 0 <= i[0] < H and 0 <= i[1] < W and D[i[0]][i[1]] < 0 and s[i[0]][i[1]] == ".":
                queue.append((i[0], i[1], x, y))
                s[i[0]][i[1]] = "
    return D

D = bfs()
if D[-1][-1] == -1:
    print(-1)
    sys.exit()
print(W_count - D[-1][-1])

Solution (Python):
import sys
input = sys.stdin.readline
 
H, W = [int(x) for x in input().split()]
s = []
W_count = 0
for _ in range(H):
    tmp = list(input().rstrip())
    s.append(tmp)
    W_count += tmp.count('.')

from collections import deque
D = [[-1] * W for _ in range(H)]

def bfs():
    queue = deque([(0, 0, 0, 0)])
    D[0][0] = 0
    while queue and D[-1][-1] < 0:
        u = queue.popleft()
        x = u[0]
        y = u[1]
        D[x][y] = D[u[2]][u[3]] + 1
        for i in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if 0 <= i[0] < H and 0 <= i[1] < W and D[i[0]][i[1]] < 0 and s[i[0]][i[1]] == ".":
                queue.append((i[0], i[1], x, y))
                s[i[0]][i[1]] = "
    return D

D = bfs()
if D[-1][-1] == -1:
    print(-1)
    sys.exit()
print(W_count - D[-1][-1])