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

Solution (Python):
H,W = map(int,input().split())
field = [input() for x in range(H)]
vx = [0,0,1,-1]
vy = [1,-1,0,0]
reached = [[-1 for x in range(W)]for x in range(H)]
from collections import deque
def bfs(y,x):
    q = deque([[y,x]])
    reached[y][x] = 1

    while q:
        y,x = q.popleft()
        if [y,x] == [H-1,W-1]:
            return reached[y][x]
        for dy,dx in zip(vy,vx):
            ny,nx = y+dy,x+dx
            if not (0<=ny<H and 0<=nx<W):
                continue
            if field[ny][nx] == '.' and reached[ny][nx] == -1:
                q.append([ny,nx])
                reached[ny][nx] = reached[y][x] + 1
    return -1
bk = 0
for x in field:
    for y in x:
        if y == '
            bk += 1
ans = bfs(0,0)
if ans==-1:
    print(-1)
else:
    print(H*W-ans-bk)

Solution (Python):
import sys
from collections import deque

import numpy as np

sys.setrecursionlimit(10000)
INF = float('inf')

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


distances = np.empty((H, W), dtype=int)
distances.fill(-1)
que = deque()


def valid(h, w):
    return 0 <= h < H and 0 <= w < W and S[h][w] == '.' and distances[h][w] == -1



distances[0][0] = 1
que.append((0, 0, H - 1, W - 1))
while len(que) > 0 and distances[-1, -1] == -1:
    sh, sw, eh, ew = que.popleft()
    if valid(sh + 1, sw):
        distances[sh + 1, sw] = distances[sh, sw] + 1
        que.append((sh + 1, sw, eh, ew))
    if valid(sh - 1, sw):
        distances[sh - 1, sw] = distances[sh, sw] + 1
        que.append((sh - 1, sw, eh, ew))
    if valid(sh, sw + 1):
        distances[sh, sw + 1] = distances[sh, sw] + 1
        que.append((sh, sw + 1, eh, ew))
    if valid(sh, sw - 1):
        distances[sh, sw - 1] = distances[sh, sw] + 1
        que.append((sh, sw - 1, eh, ew))

d = distances[-1, -1]
if d == -1:
    print(-1)
else:
    print(H * W - list(S.flat).count('

Solution (Python):
h,w=map(int,input().split())
grid=[["
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)

Solution (Python):
h,w=map(int,input().split())
grid=[["
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)

Solution (Python):
R,C = map(int,input().split())
sy,sx = 2,2
gy,gx = R+1,C+1

maze = [["
white_count = 0
for i in range(R):
    temp = list(input())
    temp.insert(0,'
    temp.append('
    maze.append(temp)
    white_count += temp.count('.')
    
maze.append(["

vx = [0,1,0,-1]
vy = [1,0,-1,0]
Q = [[sy-1,sx-1,0]]

checked = [[sy-1,sx-1]]
while True:
   if len(Q) == 0:
       length = white_count+1
       break
   now = Q.pop(0)
   if now[0] == gy-1 and now[1] == gx-1:
       length = now[2]+1
       break
   for i in range(4):
       next_y = now[0]+vy[i]
       next_x = now[1]+vx[i]
       if not [next_y,next_x] in checked and maze[next_y][next_x] == '.':
           checked.append([next_y,next_x])
           Q.append([next_y,next_x,now[2]+1])      
print(white_count-length)

Solution (Python):
import heapq
class edge:
    def __init__(self,to,cost):
        self.to=to
        self.cost=cost

H,W=map(int,input().split())
G=[list() for i in range(H*W)]
s=[]
for j in range(H):
    s.extend(input())

for i in range(H):
    for j in range(W):
        if(j<W-1 and  s[W*i+j+1]=="."):
            G[W*i+j].append(edge(W*i+j+1,1))
        if(i<H-1 and  s[W*i+j+W]=="."):
            G[W*i+j].append(edge(W*i+j+W,1))
        if(j>0 and  s[W*i+j-1]=="."):
            G[W*i+j].append(edge(W*i+j-1,1))
        if(i>0 and  s[W*i+j-W]=="."):
            G[W*i+j].append(edge(W*i+j-W,1))
            
        
        
    

def dijkstra(o):
    d=[float('inf') for i in range(H*W)]
    d[o]=0
    hq=[]
    prev=[[] for i in range(H*W)]
    heapq.heappush(hq,(0,o))
    while hq:
        p=heapq.heappop(hq)
        v=p[1]
        if(d[v]<p[0]):
            continue
        for i in G[v]:
            if(d[i.to]>d[v]+i.cost):
                d[i.to]=d[v]+i.cost
                prev[i.to]=prev[v]+[str(sorted([v,i.to]))]
                heapq.heappush(hq,(d[i.to],i.to))
    return d,prev


ans=set()
for i in range(1):
    tmp=dijkstra(i)[0]
    if(tmp[H*W-1]==float('inf')):
        print(-1)
    else:
        
        print(H*W-s.count('

Solution (Python):
from queue import Queue


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


count = 0 
lst = []
row = []
for i in range(H):
    row = list(input())
    count += row.count('.')
    lst += [row]
 








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

def bfs():
    q = Queue()
    INF = 10 ** 9
    d = [[INF]* W for _ in range(H)]
    q.put(0)
    q.put(0)
    d[0][0] = 0

    while True:
        if q.empty():
            break
        else:
            px = q.get()
            py = q.get()
            if px == H-1 and py == W-1:
                break
            else:
                for dx, dy in move:
                    nx = px + dx
                    ny = py + dy

                    if 0 <= nx and nx < H and 0 <= ny and ny < W and lst[nx][ny] == '.' and d[nx][ny] == INF:
                        q.put(nx)
                        q.put(ny)
                        d[nx][ny] = d[px][py] + 1
    return d[H-1][W-1]

a = bfs()

if a == 10 **9:
    print (-1)
else:
    print (count - a - 1)

Solution (Python):
from queue import Queue


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


count = 0 
lst = []
row = []
for i in range(H):
    row = list(input())
    count += row.count('.')
    lst += [row]
 








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

def bfs():
    q = Queue()
    INF = 10 ** 9
    d = [[INF]* W for _ in range(H)]
    q.put(0)
    q.put(0)
    d[0][0] = 0

    while True:
        if q.empty():
            break
        else:
            px = q.get()
            py = q.get()
            if px == H-1 and py == W-1:
                break
            else:
                for dx, dy in move:
                    nx = px + dx
                    ny = py + dy

                    if 0 <= nx and nx < H and 0 <= ny and ny < W and lst[nx][ny] == '.' and d[nx][ny] == INF:
                        q.put(nx)
                        q.put(ny)
                        d[nx][ny] = d[px][py] + 1
    return d[H-1][W-1]

a = bfs()

if a == 10 **9:
    print (-1)
else:
    print (count - a - 1)

Solution (Python):
h,w=map(int,input().split())
s=[]
ans=0
white=0
for i in range(h):
    s.append(input())
    for j in s[-1]:
        if j==".":
            white+=1
    
from collections import deque
  
def dfs(field):
    q = deque([(0, 0, 1)])
    visited = [[False] * w for _ in range(h)]
    while q:
        i, j, d = q.popleft()
        if i == h - 1 and j == w - 1:
            return d
        if visited[i][j]:
            continue
        visited[i][j] = True
        if i > 0 and field[i - 1][j] == '.':
            q.append((i - 1, j, d + 1))
        if i < h - 1 and field[i + 1][j] == '.':
            q.append((i + 1, j, d + 1))
        if j > 0 and field[i][j - 1] == '.':
            q.append((i, j - 1, d + 1))
        if j < w - 1 and field[i][j + 1] == '.':
            q.append((i, j + 1, d + 1))
    else:
        return -1

ans=dfs(s)

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

Solution (Python):


import sys
import heapq
import copy
import itertools

inf = float('inf')
a = '.'
b = '

def solve(H, W, s):
    white_count = sum([line.count(a) for line in s])
    
    field = [[b for w in range(W+2)] for h in range(H+2)]
    for h in range(H):
        field[1+h][1:W+1] = s[h]

    D = {(h, w): inf for h, w in itertools.product(range(H+2), range(W+2))}
    start = (1, 1)
    D[start] = 1
    Q = [(D[start], start)]
    direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    
    while len(Q) > 0:
        Du, u = heapq.heappop(Q)
        for d in direction:
            v = (u[0]+d[0], u[1]+d[1])
            if field[u[0]+d[0]][u[1]+d[1]] == b:
                continue
            if Du + 1 < D[v]:
                D[v] = Du + 1
                heapq.heappush(Q, (D[v], v))

    path_length = D[(H, W)]
    if path_length == inf:
        print(-1)
        return
    print(white_count - path_length)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  
    W = int(next(tokens))  
    s = [[c for c in next(tokens)] for _ in range(H)]  
    solve(H, W, s)
    pass

if __name__ == '__main__':
    main()

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


def bfs(startx: int, starty: int) -> set:
    dxdy = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    queue = deque()
    queue.appendleft((startx, starty, 0))
    reached = set()
    while queue:
        d = queue.pop()
        if d[0] == W - 1 and d[1] == H - 1:
            return d[2]
        for a in dxdy:
            x = d[0] + a[0]
            y = d[1] + a[1]
            if (x, y) not in reached and 0 <= x < W and 0 <= y < H and maze[y][x] != '
                reached.add((x, y))
                queue.appendleft((x, y, d[2] + 1))
    return -1


d = bfs(0, 0)
if d == -1:
    print(-1)
    exit()
cnt = 0
for c in maze:
    cnt += c.count('
print(H * W - cnt - d - 1)

Solution (Python):
from collections import deque

H, W = map(int, input().split())
s = ['
Q = deque()
Q.append((1, 1))
M = [[-1 for _ in range(W + 2)] for _ in range(H + 2)]
L = [[1, 0], [-1, 0], [0, -1], [0, 1]]
c = 0
for i in range(H + 1):
    for j in range(W + 1):
        if s[i][j] == '.':
            c += 1
M[1][1] = 1
while Q:
    y, x = Q.popleft()
    if y == H and x == W:
        print(c - M[H][W])
        exit()
    else:
        for i, j in L:
            if M[y + i][x + j] == -1 and s[y + i][x + j] == '.':
                Q.append((y + i, x + j))
                M[y + i][x + j] = M[y][x] + 1

print(-1)

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

total_white = 0
for i in s:
  total_white += i.count(".")

sh = 0
sw = 0
gh = H-1
gw = W-1

s[sh][sw] = 0
q = [[sh, sw]]
min_path = 0

while len(q) > 0:
  h, w = q.pop(0)
  if h == gh and w == gw:
    min_path = s[h][w]
    print(total_white - min_path -1)
    exit()
  for dh, dw in ([0, 1], [0, -1], [1, 0], [-1, 0]):
    if 0 <= h + dh < H and 0 <= w + dw < W:
      if s[h+dh][w+dw] == ".":
        s[h+dh][w+dw] = s[h][w] + 1
        q.append([h+dh, w+dw])

print(-1)

Solution (Python):
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(100000)

s = [['


cost = [[-1 if s[y][x] == '
cost[1][1] = 0


move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1 and cost[y+1][x] == float('inf'):
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1 and cost[y-1][x] == float('inf'):
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1 and cost[y][x+1] == float('inf'):
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1 and cost[y][x-1] == float('inf'):
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]



if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Solution (Python):
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(100000)

s = [['


cost = [[-1 if s[y][x] == '
cost[1][1] = 0


move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]



if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Solution (Python):
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(100000)

s = [['


cost = [[-1 if s[y][x] == '
cost[1][1] = 0


move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]



if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Solution (Python):
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(100000)

s = [['


cost = [[-1 if s[y][x] == '
cost[1][1] = 0


def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(y,x):
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move(y+1,x)
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move(y-1,x)
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move(y,x+1)
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move(y,x-1)
  

move(1,1)



if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Solution (Python):
from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)

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

white = 0
black = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            white += 1
        else:
            black += 1
cnt = [[-1]*W for _ in range(H)]

def bfs():
    queue = deque([[0, 0]])
    cnt[0][0] = 0
    while queue:
        y, x = queue.popleft()
        for dy, dx in [[1,0], [-1,0], [0,1], [0,-1]]:
            if y+dy >= 0 and y+dy < H and x+dx >= 0 and x+dx < W:
                if cnt[y+dy][x+dx] == -1 and S[y+dy][x+dx] == ".":
                    cnt[y+dy][x+dx] = cnt[y][x] + 1
                    queue.append([y+dy,x+dx])

bfs()
if cnt[H-1][W-1] == -1:
    print("-1")
else:
    print(white-cnt[H-1][W-1]-1)

Solution (Python):
H,W = map(int,input().split())
s = [["
ans = sum([sum([int(c == ".") for c in row]) for row in s])
s[1][1] = 1
ij = [[1,1]]
d = [[0,1],[0,-1],[1,0],[-1,0]]
cnt = 0
while ij[cnt:]:
    i,j = ij[cnt]
    for di,dj in d:
        if s[i+di][j+dj] == ".":
            s[i+di][j+dj] = s[i][j] + 1
            ij.append([i+di,j+dj])
            if i+di == H and j+dj == W:
                break
    cnt += 1
if s[H][W] == ".":
    ans = -1
else:
    ans -= s[H][W]
print(ans)

Solution (Python):
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import deque

def bfs(grid):
    h = len(grid)
    w = len(grid[0])
    
    dist = [[float('inf')]*w for _ in range(h)]
    
    que = deque([])
    que.append(((0,0), 1))
    dist[0][0] = 0
    
    drs = [-1,0,1,0]
    dcs = [0,-1,0,1]
    
    while que:
        (rcur, ccur), cost = que.popleft()
        if rcur == h-1 and ccur == w-1:
            return dist[h-1][w-1]
    
        for dr, dc in zip(drs, dcs):
            if not (0 <= rcur+dr < h and 0 <= ccur+dc < w):
                continue
            
            elif grid[rcur+dr][ccur+dc] == '
                continue
            
            elif dist[rcur+dr][ccur+dc] != float('inf'):
                continue
            
            dist[rcur+dr][ccur+dc] = cost + 1
            que.append(((rcur+dr, ccur+dc), cost+1))
            
    return -1
            

h,w = li()
grid = [lc() for _ in range(h)]

white = 0
for row in grid:
    for col in row:
        if col == '.':
            white += 1

route = bfs(grid)
print(-1 if route == -1 else white - route)

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

white = 0
for d in map:
    white += d.count('.')

memory = [(0,0)]
data = [[0] * W for _ in range(H)]
data[0][0] = 1
direction = [(0,1), (0,-1), (1,0), (-1,0)]
while True:
    if len(memory) == 0:
        print(-1)
        exit()
    x, y = memory.pop(0)
    for dx, dy in direction:

        if x + dx == H - 1 and y + dy == W-1:
            print(white - (data[x][y] + 1))
            exit()
        if 0 <= x + dx < H and 0 <= y + dy < W:
            if map[x+dx][y+dy] == '.' and data[x+dx][y+dy] == 0:
                data[x+dx][y+dy] = data[x][y] + 1
                memory.append((x+dx, y+dy))

Solution (Python):
H, W = map(int, input().split())
MA = [list(input().strip()) for _ in range(H)]
VI = [[-1] * W for _ in range(H)]

kabe = 0
for i in range(H):
    kabe += MA[i].count("

from collections import deque


def bfs(ma, vi):
    Q = deque([(0,0)])
    sy, sx = (0,0)
    vi[sy][sx] = 0
    while True:
        if Q == deque([]):
            return -1
        q = Q.popleft()
        y, x = q
        if q == (H-1,W-1):
            return vi[y][x]
        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            nq = y + dy, x + dx
            ny, nx = nq
            if 0 <= ny < H and 0 <= nx < W and vi[ny][nx] == -1:
                if ma[ny][nx] == '.':
                    Q.append(nq)
                    vi[ny][nx] = vi[y][x] + 1


score = bfs(MA,VI)

if score != -1:
    print(H * W - kabe - score - 1)
else:
    print(-1)

Solution (Python):
INF=10*10
H,W=map(int, input().split())
s=[list(input()) for _ in range(H)]
wall=sum(map(lambda x: x.count("
d=[[INF for _ in range(W)] for _ in range(H)]
def bfs(h, w, c):
	if d[h][w] <= c:
		return
	d[h][w] = c
	for dh,dw in [(0, -1), (-1, 0), (0, 1), (1, 0)]:
		if h+dh >= 0 and w+dw >= 0 and h+dh < H and w+dw < W and s[h+dh][w+dw] == ".":
			bfs(h+dh, w+dw, c+1)
bfs(0, 0, 1)
print(-1 if d[H-1][W-1] == INF else H*W - d[H-1][W-1] - wall)

Solution (Python):
import sys
from queue import Queue  


def parse(file):
    height, width = map(int, file.readline().split())
    maze = []
    for y in range(height):
        row = file.readline().strip()
        maze.append(row)

    return height, width, maze


def main(height, width, maze):
    traversed = [(0, 0)]
    queue = Queue()  

    queue.put((0, 0, 0))

    nwhite = 0
    for r in maze:
        nwhite += r.count('.')

    while not queue.empty():
        (y, x, count) = queue.get()

        if (y, x) == (height - 1, width - 1):
            return nwhite - count - 1
        for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):
            if ny >= height or nx >= width or ny < 0 or nx < 0:
                continue
            if (ny, nx) in traversed:
                continue
            if maze[ny][nx] == '.':
                queue.put((ny, nx, count + 1))
                traversed.append((ny, nx))
    return -1


if __name__ == '__main__':
    print(main(*parse(sys.stdin)))

Solution (Python):
from collections import deque
h, w = map(int, input().split())
grid = [[c == "." for c in input()] for i in range(h)]
q = deque()
q.append((0,0,1))
visited = set()
min_dist = 0
while q:
    y, x, d = q.popleft()
    
    if (y,x) in visited or not grid[y][x]:
        continue
    visited.add((y,x))
    
    if y == h-1 and x == w-1:
        min_dist = d
        break

    for dy, dx in [[-1,0],[1,0],[0,1],[0,-1]]:
        yn = y + dy
        xn = x + dx
        if 0<=yn<h and 0<=xn<w:
            q.append((yn, xn, d+1))
if min_dist:
    white = sum(sum(i) for i in grid)
    
    print(white - min_dist)
else:
    print(-1)

Solution (Python):
from collections import deque

H, W = map(int, input().split())
Map = [list(-1 if s=='.' else -2 for s in input()) for _ in range(H)]
ttl=H*W*2
for i in range(H):
  ttl += sum(Map[i])

Map[0][0]=0
sy, sx = 0, 0
  
dq = deque()
dq.append([sy, sx])
d = [[1,0],[0,1],[-1,0],[0,-1]]

ans=-1
while(len(dq)>0):
  y, x = dq.popleft()
  cnt = Map[y][x]+1
  for i in range(4):
    ytmp, xtmp = y+d[i][0], x+d[i][1]
    if ytmp<0 or ytmp>=H or xtmp<0 or xtmp>=W:
      continue
    elif Map[ytmp][xtmp]==-1:
      Map[ytmp][xtmp]=cnt
      dq.append([ytmp, xtmp])
      if ytmp==H-1 and xtmp==W-1:
        ans=cnt
        dq.clear()
        break
if ans==-1:
  print(ans)
else:
  print(ttl-ans-1)

Solution (Python):
from collections import deque

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

def bfs():
    queue = deque([[0, 0]])
    cnt[0][0] = 0
    while queue:
        i, j = queue.popleft()
        if [i, j] == [h - 1, w - 1]:
            return cnt[i][j]
        for di, dj in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            if (0 <= i + di < h and 0 <= j + dj < w and s[i + di][j + dj] == "." and cnt[i + di][j + dj] == -1):
                cnt[i + di][j + dj] = cnt[i][j] + 1
                queue.append([i + di, j + dj])

bfs()
ans = -1
if cnt[h - 1][w - 1] != -1:
    ans = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                ans += 1
    ans = ans - (cnt[h - 1][w - 1] + 1)
print(ans)

Solution (Python):
import collections

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

p = [[None] * w for _ in range(h)]
q = collections.deque()
reachable = False

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

while len(q) > 0:
    x, y = q.popleft()
    for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
        if x + dx == w - 1 and y + dy == h - 1:
            reachable = True
            break
        if 0 <= x + dx < w and 0 <= y + dy < h:
            if M[y + dy][x + dx] == '.':
                if p[y + dy][x + dx] is None:
                    p[y + dy][x + dx] = p[y][x] + 1
                    q.append((x + dx, y + dy))

    if reachable:
        print(sum(row.count('.') for row in M) - p[y][x] - 2)
        break
else:
    print(-1)

Solution (Python):

from collections import deque
import sys
import math
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, input().split()))
ns = lambda: input()

H,W=na()
f = [input() for i in range(H)]


def bfs():
    Q=deque([(0,0,1)])
    visited = [[False] * W for _ in range(H)]
    while Q:
        h,w,d = Q.popleft()
        if(h==H-1 and w==W-1):
            return d
        
        if visited[h][w]:
            continue
        visited[h][w] = True
        if h > 0 and f[h - 1][w] == '.':
            Q.append((h - 1, w, d + 1))
        if h < H - 1 and f[h + 1][w] == '.':
            Q.append((h + 1, w, d + 1))
        if w > 0 and f[h][w - 1] == '.':
            Q.append((h, w - 1, d + 1))
        if w < W - 1 and f[h][w + 1] == '.':
            Q.append((h, w + 1, d + 1))
    else:
        return -1



black_sum=0
for i in range(H):
    black_sum+=f[i].count("


res=bfs()
if(res==-1):
    print(res)
else:
    print(H*W-res-black_sum)

Solution (Python):
H, W = map(int, raw_input().split())
dungeon = []
memo = []
whitecount = 0
for i in range(0, H):
	dlst = []
	nlst = []
	s = raw_input()
	for j in range(0, W):
		if s[j] == '.': whitecount += 1
		dlst.append(s[j]=='.')
		nlst.append(H*W+1)
	dungeon.append(dlst)
	memo.append(nlst)
max = -1
queue = [[0, 0, 1]]
while queue != []:
	now = queue.pop(0)
	if now[2] < memo[now[0]][now[1]] and dungeon[now[0]][now[1]]:
		memo[now[0]][now[1]] = now[2]
		for i in range(0, 2):
			nexth = now[0] - 1 + 2*i
			nextw = now[1] - 1 + 2*i
			if 0 <= nexth and nexth < H:
				queue.append([nexth, now[1], now[2]+1])
			if 0 <= nextw and nextw < W:
				queue.append([now[0], nextw, now[2]+1])
if max < whitecount - memo[H-1][W-1]:
	max = whitecount-memo[H-1][W-1]
print max

Solution (Python):
import queue

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

white = 0

for i in range(h):
    for j in range(w):
        if s[i][j]=='.':
            white += 1

q = queue.Queue()

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

q.put([0,0])

inf = float('inf')
d = [[inf for i in range(w)] for j in range(h)]
d[0][0] = 0

while not q.empty():
    p = q.get()
    for m in move:
        if 0<=p[0]+m[0]<h and 0<=p[1]+m[1]<w and d[p[0]+m[0]][p[1]+m[1]] == inf and s[p[0]+m[0]][p[1]+m[1]] != '
            d[p[0]+m[0]][p[1]+m[1]] = d[p[0]][p[1]]+1
            q.put([p[0]+m[0], p[1]+m[1]])

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

Solution (Python):
h,w = map(int,input().split())
s = [list(input()) for _ in range(h)]
num = 1
dis = [[10**9]*w for _ in range(h)]
cnt = 0
for i in range(len(s)):
    cnt += s[i].count('.')
def bfs():
    queue = []
    done = []
    queue.insert(0,(0,0))
    dis[0][0] = 1

    while len(queue):
        y,x = queue.pop()
        if (y,x) in done:
            continue
        else:
            done.insert(0,(y,x))
        if x==w-1 and y==h-1:
            break

        for i in range(0,4):
            nx,ny = x+[1,0,-1,0][i], y+[0,1,0,-1][i]
            if 0<=nx<w and 0<=ny<h and s[ny][nx]!='
                queue.insert(0,(ny,nx))
                dis[ny][nx] = min(dis[ny][nx],dis[y][x]+1)
    return dis[h-1][w-1]
ret = bfs()
if ret==10**9:
    print(-1)
else:
    print(cnt-ret)

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

q = queue.Queue(2500)
q.put((0,0,1))
cood = [(1,0),(-1,0),(0,1),(0,-1)]
res = 0

visited = set((0,0))

while not q.empty():
    x,y,cnt=q.get(False)
    if x+1 == W and y+1 == H:
        res = cnt
        break
    for dx, dy in cood:
        if x+dx >= 0 and x+dx < W and y+dy >= 0 and y+dy < H:
            if inmap[y+dy][x+dx] != '
                q.put((x+dx, y+dy, cnt+1))
                visited.add((x+dx, y+dy))

black = 0
for i in range(H):
    for j in range(W):
        if inmap[i][j] == '
            black += 1


if res == 0:
    print(-1)
else:
    print(H*W - black - res)

Solution (Python):
from collections import deque
R,C = map(int,input().split())
sy,sx = 1,1  
gy,gx = R,C  
L = []
for i in range(R):
  L.append(list(input()))   
dy_dx = [[1,0],[-1,0],[0,1],[0,-1]]   
black = 0
for i in range(R):
  for j in range(C):
    if L[i][j] == '
      black += 1
que = deque([[sy-1,sx-1]])   
L[sy-1][sx-1] = 0  
while len(que) > 0:  
  cur = que.popleft()   
  for i in range(4):  
    if 0 <= cur[0]+dy_dx[i][0] <= R-1 and 0 <= cur[1]+dy_dx[i][1] <= C-1:  
      if L[cur[0]+dy_dx[i][0]][cur[1]+dy_dx[i][1]] == '.':  
        L[cur[0]+dy_dx[i][0]][cur[1]+dy_dx[i][1]] = L[cur[0]][cur[1]]+1  
        que.append([cur[0]+dy_dx[i][0],cur[1]+dy_dx[i][1]])   
if L[gy-1][gx-1] == '
  print(-1)
elif L[gy-1][gx-1] == '.':
  print(-1)
else:
  print(R*C-L[gy-1][gx-1]-1-black)