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())
s = [list('
queue = [[1, 1, 1]]
dot = 0
for i in range(h):
    s.append(['
    dot += s[-1].count('.')
s.append(list('

def move(yxc):
    y, x, cost = yxc[0], yxc[1], yxc[2]
    global queue
    for dy, dx in ([1, 0], [-1, 0], [0, 1], [0, -1]):
        ny, nx = y + dy, x + dx
        if s[ny][nx] == '.':
            s[ny][nx] = cost + 1
            queue.append([ny, nx, cost + 1])

while len(queue) > 0:
    move(queue.pop(0))

s[1][1] = 1
move([1, 1, 1])
if s[h][w] == '.':
    print(-1)
else:
    print(dot - s[h][w])

Solution (Python):


line = input().split(" ")
H = int(line[0])
W = int(line[1])

s = []
cnt_w = 0
for _ in range(H):
    line = list(input())
    for x in line:
        if x==".":
            cnt_w += 1
    s.append(line)

INF = 100000

diff = [
    [0,1]
    ,[0,-1]
    ,[1,0]
    ,[-1,0]
]

def dfs():
    q = []
    m = []
    for i in range(H):
        m.append([INF for _ in range(W)])
    q.append((0,0))
    m[0][0] = 1

    while len(q)>0:
        p = q.pop(0)
        if H-1==p[0] and W-1==p[1]:
            break

        for d in diff:
            ni = p[0]+d[0]
            nj = p[1]+d[1]
            if 0<=ni<H and 0<=nj<W:
                if s[ni][nj]=="." and m[ni][nj]==INF:
                    q.append((ni,nj))
                    m[ni][nj] = m[p[0]][p[1]]+1

    return m[H-1][W-1]

r = dfs()

if r == INF:
    print("-1")
else:
    print(cnt_w - r)

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

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

while que:
    now = que.popleft()
    if now == [H-1, W-1]:
        break

    if now[0]+1 <= H -1:
        if Field[now[0]+1][now[1]] == ".":
            Field[now[0]+1][now[1]] = str(int(Field[now[0]][now[1]])+1)
            que.append([now[0]+1, now[1]])

    if now[0]-1 >= 0:
        if Field[now[0]-1][now[1]] == ".":
            Field[now[0]-1][now[1]] = str(int(Field[now[0]][now[1]])+1)
            que.append([now[0]-1, now[1]])

    if now[1] + 1 <= W -1:
        if Field[now[0]][now[1]+1] == ".":
            Field[now[0]][now[1]+1] = str(int(Field[now[0]][now[1]])+1)
            que.append([now[0], now[1]+1])

    if now[1] -1 >= 0:
        if Field[now[0]][now[1]-1] == ".":
            Field[now[0]][now[1]-1] = str(int(Field[now[0]][now[1]])+1)
            que.append([now[0], now[1]-1])
else:
    print(-1)
    exit()
Z = int(Field[H-1][W-1])

sharp_cnt = 0
for f in Field:
    sharp_cnt += f.count("

print(H*W - sharp_cnt - Z - 1)

Solution (Python):
from collections import deque

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

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

inf = 10 * w * h
dist = [[inf] * w for i in range(h)]

que = deque([(0, 0)])
visited[0][0] = 1
dist[0][0] = 0

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

while len(que) > 0:
    x, y = que.popleft()
    
    if x == w - 1 and y == h - 1:
        break
    
    for k in range(4):
        nx = x + dx[k]
        ny = y + dy[k]
        
        if 0 <= nx < w and 0 <= ny < h and s[ny][nx] == '.' and visited[ny][nx] == 0:
            que.append((nx, ny))
            visited[ny][nx] = 1
            dist[ny][nx] = dist[y][x] + 1

if dist[h - 1][w - 1] == inf:
    print(-1)
else:
    print(sum(s[i].count('.') for i in range(h)) - (dist[h - 1][w - 1] + 1))

Solution (Python):
import sys
from collections import deque
sys.setrecursionlimit(1000000)

h, w = map(int, input().split())
route = [[] for j in range(w * h)]
prev = []
somes = 0
for e in range(h):
    a = list(input())
    for g in a:
        if g == ".":
            somes += 1
    for l in range(w - 1):
        if a[l:l+2] == [".", "."]:
            route[e*w + l].append(e*w + l + 1)
            route[e * w + l + 1].append(e * w + l)
    if not prev:
        prev = a
        continue
    for l in range(len(a)):
        if a[l] == prev[l] == ".":
            route[e*w + l].append(e*w+l-w)
            route[e * w + l - w].append(e * w + l)
    prev = a
start = 0
goal = h*w-1
routes = []
eachmin = [float("inf") for i in range(h*w)]
eachmin[0] = 0
queue = deque([start])
searched = []
def bfs(time = 0):
    global searched, queue

    while queue:
        now = queue.popleft()
        if now in searched:
            continue
        if now == goal:
            break

        for j in route[now]:
            if j not in searched:
                queue.append(j)
                eachmin[j] = eachmin[now] + 1
        searched.append(now)

bfs(start)
if eachmin[-1] > 500000:
    print("-1")
    exit()
print(somes - eachmin[-1] - 1)

Solution (Python):
import queue

def solve():
    h, w = map(int, input().split())

    block = '
    field = [block]
    field.extend(['
    field.append(block)

    dist = [[h*w*100 for i in range(w+1)] for j in range(h+1)]
    dist[1][1] = 1

    q = queue.Queue()
    q.put((1,1))

    while not q.empty() :
        (x,y) = q.get()
        nd = dist[x][y] + 1
        for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)] :
            nx = x + dx
            ny = y + dy
            if field[nx][ny] == '.' and dist[nx][ny] > nd :
                dist[nx][ny] = nd
                q.put((nx,ny))

    if dist[h][w] >= h*w :
        return -1

    ans = h*w - dist[h][w]
    for v in field:
        ans -= v.count('
    ans += w*2
    return ans

print(solve())

Solution (Python):
import queue

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

d = [[0 for i in range(W)] for j in range(H)]

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

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

def bfs():
    que = queue.Queue()
    
    for i in range(H):
        for j in range(W):
            d[i][j] = float("inf")
    
    que.put((sx, sy))
    d[sx][sy] = 0
    
    
    while que.qsize() > 0:
        
        p = que.get()
        
        if p[0] == gx and p[1] == gy:
            break
        
        for i in range(4):
            
            nx, ny = p[0] + dx[i], p[1] + dy[i]
            
            
            if 0 <= nx < H and 0 <= ny < W:
                if board[nx][ny] != "
                    que.put((nx, ny))
                    d[nx][ny] = d[p[0]][p[1]] + 1
    return d[gx][gy]

def solve():
    res = bfs()
    if type(res) != int:
        print(-1)
        return
    sharp_num = 0
    for l in board:
        for c in l:
            if c == "
                sharp_num += 1
    print(H*W - res - sharp_num - 1)
    
    
    
solve()

Solution (Python):

from collections import deque
def inpl(): return tuple(map(int, input().split()))

H, W = inpl()

S = []
for _ in range(H):
    S.append(input())

M = [[50*50*10 if S[h][w]=="." else -1 for w in range(W)] for h in range(H)]

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

ok = False
while Q:
    s, h, w = Q.popleft()
    if h == H-1 and w == W-1:
        ok = True
        break
    
    if h > 0:
        if M[h-1][w] > s+1:
            M[h-1][w] = s+1
            Q.append([s+1, h-1, w])
    
    if h < H-1:
        if M[h+1][w] > s+1:
            M[h+1][w] = s+1
            Q.append([s+1, h+1, w])

    if w > 0:
        if M[h][w-1] > s+1:
            M[h][w-1] = s+1
            Q.append([s+1, h, w-1])
    
    if w < W-1:
        if M[h][w+1] > s+1:
            M[h][w+1] = s+1
            Q.append([s+1, h, w+1])

if ok:
    b = sum([s.count("
    print(H*W - b - s)
else:
    print(-1)

Solution (Python):
import numpy as np
from collections import deque

H, W = map(int, input().split())
board = np.ones((H, W))
for i in range(H):
    for j, c in enumerate(input()):
        if c == '
            board[i, j] = 0

history = np.zeros((H, W))
history[0, 0] = 1

dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
q = deque()
q.append((0, 0))

while len(q):
    p = q.popleft()

    
    if p == (H - 1, W - 1):
        break

    for d in dirs:
        
        nxt = (p[0] + d[0], p[1] + d[1])

        
        if not (0 <= nxt[0] < H and 0 <= nxt[1] < W):
            continue

        
        if board[nxt[0], nxt[1]] == 0:
            continue

        
        if history[nxt[0], nxt[1]] != 0:
            continue

        q.append(nxt)
        history[nxt[0], nxt[1]] = history[p[0], p[1]] + 1

if history[-1, -1] == 0:
    print(-1)
else:
    print(int(board.sum() - history[-1, -1]))

Solution (Python):
H,W = map(int, input().split())
s = [[-1 if w == "
black = sum([ sum([ 1 for w in range(W) if s[h][w] == -1]) for h in range(H)])

neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
s[0][0] = 1
check_list = [(0, 0)]
index = 0
while index < len(check_list):
    check = check_list[index]
    for neighbor in [(check[0] + neighbor[0], check[1] + neighbor[1]) for neighbor in neighbors]:
        if 0 <= neighbor[0] < H and 0 <= neighbor[1] < W and s[neighbor[0]][neighbor[1]] != -1:
            if s[neighbor[0]][neighbor[1]] > s[check[0]][check[1]] + 1:
                s[neighbor[0]][neighbor[1]] = s[check[0]][check[1]] + 1
                check_list.append(neighbor)
    index += 1

if s[H - 1][W - 1] == 9999:
    print(-1)
else:
    print(W*H - black - s[H - 1][W - 1])

Solution (Python):
import sys
import math
import collections
import itertools
import array
import inspect
import pprint


sys.setrecursionlimit(10000)


def chkprint(*args):
    names = {id(v):k for k,v in inspect.currentframe().f_back.f_locals.items()}
    print(', '.join(names.get(id(arg),'???')+' = '+repr(arg) for arg in args))


def to_bin(x):
    return bin(x)[2:]


def dim2input(N):
    li = []
    for _ in range(N):
        li.append(list(map(int, input())))
    return li

""" input template
S = input()
N = int(input())
L = list(map(int, input().split()))
a, b = list(map(int, input().split()))
SL = list(input())
"""



def main():
    delta_x = [-1, 0, 0, 1]
    delta_y = [0, -1, 1, 0]

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

    S = []
    for _ in range(H):
        S.append(list(input()))

    S[0][0] = 0

    reached = [[0, 0]]
    move = 1

    while len(reached) != 0:
        new_reached = []

        for r in reached:
            for dx, dy in zip(delta_x, delta_y):
                new_y = r[0] + dy
                new_x = r[1] + dx

                if not (0 <= new_y < H):
                    continue

                if not(0 <= new_x < W):
                    continue

                if S[new_y][new_x] == ".":
                    S[new_y][new_x] = move
                    new_reached.append([new_y, new_x])

        move += 1
        reached = new_reached

    if S[-1][-1] == "." or S[-1][-1] == "
        print(-1)
        return


    i = H-1
    j = W-1
    while True:
        current = S[i][j]

        if current == 0:
            break
        S[i][j] = "


        for dx, dy in zip(delta_x, delta_y):
            new_y = i + dy
            new_x = j + dx

            if not (0 <= new_y < H):
                continue

            if not(0 <= new_x < W):
                continue

            if S[new_y][new_x] == current - 1:
                i = new_y
                j = new_x
                break

    S[0][0] = "

    point = 0
    for row in S:
        for cell in row:
            if isinstance(cell, int) or cell == ".":
                point += 1

    print(point)





main()

Solution (Python):
H, W = map(int, input().split())
s = [[i for i in input()]for i in range(H)]
maze = [[False for i in range(W)] for i in range(H)]
bknum = 0
for i in range(H):
    for j in range(W):
        if s[i][j]==".":
            maze[i][j]=True
        else:
            maze[i][j]=False
            bknum += 1


def ncell(i, j):
    tmp = [[i-1,j],[i+1,j],[i,j-1],[i,j+1]]
    out = []
    for p in tmp:
        if 0<=p[0]<H and 0<=p[1]<W and maze[i][j]:
            out.append(p)
    return out

d = [[1000 for j in range(W)] for i in range(H)]
prev = [[-1 for j in range(W)] for i in range(H)]
d[0][0]=0
Q = set()
for i in range(H):
    for j in range(W):
        if maze[i][j]:
            Q.add(i*W+j)
while(len(Q)!=0):
    u = list(Q)[0]
    du = d[u//W][u%W]
    for v in Q:
        if d[v//W][v%W]<du:
            du = d[v//W][v%W]
            u=v
    Q -=set([u])
    for v in ncell(u//W, u%W):
        if d[v[0]][v[1]]>d[u//W][u%W]+1:
            d[v[0]][v[1]]=d[u//W][u%W]+1
            prev[v[0]][v[1]]=u
length=d[H-1][W-1]
if length != 1000:
    print(H*W-length-1-bknum)
else:
    print(-1)

Solution (Python):
from collections import deque
H,W = map(int,input().split())
src = [input() for i in range(H)]
walls = 0
for row in src:
    walls += row.count('

visited = [[0 for j in range(W)] for i in range(H)]
q = deque([(0,0,0)])
dxs = [1,0,-1,0]
dys = [0,1,0,-1]
while q:
    d,x,y = q.popleft()
    if (x,y) == (W-1,H-1):
        print(H*W - walls - d - 1)
        exit()
    for dx,dy in zip(dxs,dys):
        nx,ny = x+dx, y+dy
        if not(0 <= nx < W) or not(0 <= ny < H): continue
        if src[ny][nx] == '
        q.append((d+1,nx,ny))
        visited[ny][nx] = 1

print(-1)

Solution (Python):
def solve(H, W, s):
    from collections import deque, defaultdict
    dotcount = sum([sum([c == "." for c in row]) for row in s])
    s = [row + "
    s.append("
    distance = defaultdict(lambda:9999999999999)
    q = deque()
    q.append((0, 0, 0))
    distance[0, 0] = 0
    while q:
        x, y, d = q.popleft()
        for dx, dy in ((-1, 0), (+1, 0), (0, -1), (0, +1)):
            nx, ny, nd = x + dx, y + dy, d + 1
            if s[ny][nx] == "." and nd < distance[nx, ny]:
                distance[nx, ny] = nd
                q.append((nx, ny, nd))
    if distance[W - 1, H - 1] == 9999999999999:
        return -1
    return dotcount - distance[W - 1, H - 1] - 1

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

print(solve(H, W, s))

Solution (Python):
H, W = map(int, input().split())
m = []
m.append('
white = 0
for i in range(H):
  s = input()
  m.append(list('
  white += s.count('.')
m.append('

op = set([(1, 1)])
dist = 0
while len(op) > 0:
  dist += 1
  next_op = set()
  for y, x in op:
    m[y][x] = dist
    if (y, x) == (H, W):
      print(white - dist)
      exit()

    for dx,dy in [0,1],[0,-1],[1,0],[-1,0]:
      if m[y-dy][x-dx] == '.':
        next_op.add((y-dy,x-dx))
  op = next_op

print('-1')

Solution (Python):
def i1():
 return int(input())
def i2():
 return [int(i) for i in input().split()]
[h,w]=i2()
s=[]
c=0
for i in range(h):
 s.append(input())
 c+=s[-1].count("
d=[[float("inf") for i in range(w)]for j in range(h)]
import sys
sys.setrecursionlimit(10000)

def dfs(x,y):
   global d
   d[x][y]=0
   q=[[x,y]]
   while len(q):
    v=q.pop(0)
    for i in [[0,1],[1,0],[0,-1],[-1,0]]:
      if 0<=v[0]+i[0]<h and 0<=v[1]+i[1]<w and d[v[0]+i[0]][v[1]+i[1]]==float("inf") and s[v[0]+i[0]][v[1]+i[1]]!="
         d[v[0]+i[0]][v[1]+i[1]]=min(d[v[0]+i[0]][v[1]+i[1]],d[v[0]][v[1]]+1)
         q.append([v[0]+i[0],v[1]+i[1]])
dfs(0,0)
if d[h-1][w-1]==float("inf"):
 print(-1)
else:
 print(h*w-c-d[h-1][w-1]-1)

Solution (Python):
import queue

def solve():
    h, w = map(int, input().split())

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

    dist = [[h*w*100 for i in range(w)] for j in range(h)]
    dist[0][0] = 1

    q = queue.Queue()
    q.put((0,0))

    while not q.empty() :
        (x,y) = q.get()
        nd = dist[x][y] + 1
        for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)] :
            nx = x + dx
            ny = y + dy
            if nx < 0 or nx >= h or ny < 0 or ny>= w :
                continue
            if field[nx][ny] == '.' and dist[nx][ny] > nd :
                dist[nx][ny] = nd
                q.put((nx,ny))

    if dist[h-1][w-1] >= h*w :
        return -1

    ans = h*w - dist[h-1][w-1]
    for v in field:
        ans -= v.count('

    return ans

if __name__ == '__main__':
    print(solve())

Solution (Python):
h, w = (int(x) for x in input().split())
s = ['
from collections import deque
q = deque()
q.append((1,1))
d = [0,1,0,-1,0]
f = [[False]*(w+2) for _ in range(h+2)]
f[1][1] = True
t = [[0]*(w+2) for _ in range(h+2)]
t[1][1] = 1
while len(q)>0:
    y,x = q.popleft()
    l = t[y][x]
    for i in range(4):
        dx = x+d[i+1]
        dy = y+d[i]
        if not f[dy][dx] and s[dy][dx] == '.':
            q.append((dy,dx))
            f[dy][dx] = True
            t[dy][dx] = l+1
whites = sum(sum(1 if ch == '.' else 0 for ch in ss) for ss in s)
if t[h][w] == 0:
    print(-1)
else:
    print(whites-t[h][w])

Solution (Python):
from collections import deque
h, w = map(int, input().split())
inf = int(1e9)
g = []
whites = 0
for _ in range(h):
  g.append(input())
  for c in g[-1]:
    whites += c == '.'
if (g[0][0] == '
    print(-1)
    exit()
d = [[inf for _ in range(w)] for _ in range(h)]
d[0][0] = 1
offsets = [(-1, 0), (0, 1), (0, -1), (1, 0)]
q = deque()
q.append((0, 0))
while q:
    i, j = q.popleft()
    for di, dj in offsets:
        ii = i + di
        jj = j + dj
        if (min(ii, jj) >= 0 and min(h-ii, w-jj) > 0 and g[ii][jj] == '.' and d[ii][jj] > d[i][j] + 1):
            d[ii][jj] = d[i][j] + 1
            q.append((ii, jj))
if d[-1][-1] == inf:
    print(-1)
else:
    print(whites - d[-1][-1])

Solution (Python):
from collections import deque
white = 0
H,W = map(int,input().split())
c = []
for i in range(H):
  s = input()
  white += s.count(".")
  c.append(s)
st = [0,0]
go = [H - 1,W - 1]

dx = [1,-1,0,0]
dy = [0,0,1,-1]
def BFS(graph,start,goal):
  que = deque()
  que.append(start)
  dist = [["Fail" for i in range(W)] for j in range(H)]
  dist[start[0]][start[1]] = 0
  while que:
    x,y = que.popleft()
    if [x,y] == goal:
      break
    else:
      for i in range(4):
        if 0 <=x+dx[i] <H and 0 <=y+dy[i] <W:
          if c[x+dx[i]][y+dy[i]] != "
            que.append([x+dx[i],y+dy[i]])
            dist[x+dx[i]][y+dy[i]] = dist[x][y]+1
  return dist[goal[0]][goal[1]]
if BFS(c,st,go) == "Fail": print(-1)
else: print(white - BFS(c,st,go) - 1)

Solution (Python):
import sys
import copy
from collections import deque
import time
from math import *

def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline


def bfs(board, H, W):
    is_visit = [[False for j in range(W)] for i in range(H)]
    move_list = [(1,0),(-1,0),(0,1),(0,-1)]
    now_pos_list = deque([((0, 0), 1)])
    while 1:
        if len(now_pos_list) <= 0:
            return -1;

        pos = now_pos_list.popleft()
        if pos[0][0] == H -1 and pos[0][1] == W -1:
            return pos[1]

        for move in move_list:
            new_y = pos[0][0] + move[0]
            new_x = pos[0][1] + move[1]
            if new_x >= 0 and new_y >= 0 and  new_x < W and new_y < H:
                if board[new_y][new_x] == "." and is_visit[new_y][new_x] == False:
                    is_visit[new_y][new_x] = True
                    now_pos_list.append(((new_y, new_x), pos[1] + 1))


def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    [H, W] = [int(input_raw[0]), int(input_raw[1])]
    board =[]
    for i in range(H):
        input_raw = read_func().strip()
        board.append(input_raw)
    black_num = 0
    for i in range(H):
        for j in range(W):
            if board[i][j] == "
                black_num += 1

    score = bfs(board, H, W)
    if score < 0:
        print -1
    else:
        print H * W - black_num - score


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque
H, W = map(int, input().split())
INF = float("inf")
d = [[INF] * W for _ in range(H)]
T = [[""] * W for _ in range(H)]
sx, sy = 0, 0
gx, gy = H - 1, W - 1
num = 0
for i in range(H):
    a = input()
    for j in range(W):
        T[i][j] = a[j]
    num += a.count("


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

    while len(que):
        x, y = que.popleft()
        if x == gx and y == gy:
            break
        for dx, dy in [(0, 1), (1, 0), (-1, 0), (0, -1)]:
            nx, ny = x + dx, y + dy

            if 0 <= nx < H and 0 <= ny < W and T[nx][ny] != "
                que.append((nx, ny))
                d[nx][ny] = d[x][y] + 1

    return d[gx][gy]


ans = bfs()
if ans < INF:
    print(H * W - ans - num - 1)
else:
    print(-1)

Solution (Python):
H,W = map(int, raw_input().split())
S = [raw_input() for _ in range(H)]
D = [[H*W]*W for _ in range(H)]
D[0][0] = 0
Q = [(0,0)]
while len(Q)>0:
  cx,cy = Q.pop(0)
  for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)]:
    x = cx+dx
    y = cy+dy
    if 0<=x<W and 0<=y<H and S[y][x]=='.' and D[cy][cx]+1<D[y][x]:
      D[y][x] = D[cy][cx]+1
      Q += [(x,y)]
if D[H-1][W-1]<H*W:
  print sum(s.count('.') for s in S)-D[H-1][W-1]-1
else:
  print -1

Solution (Python):

"""
https://abc088.contest.atcoder.jp/tasks/abc088_d

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


def bfs(grid, H, W):
    
    dy = [-1, 1, 0, 0]
    dx = [0, 0, -1, 1]

    gx, gy = W-1, H-1

    
    d = [[float('inf')] * W for _ in range(H)] 
    
    Q = deque()
    Q.append((0, 0))
    d[0][0] = 0               
    while Q:
        cx, cy = Q.popleft()        
        if cx == gx and cy == gy:
            return d[gy][gx]
        for i in range(4):
            nx = cx + dx[i]
            ny = cy + dy[i]
            
            if (0 <= nx < W) and (0 <= ny < H) and grid[ny][nx] != '
                Q.append((nx, ny))
                d[ny][nx] = d[cy][cx] + 1
    return -1



def solve(grid, H, W):
    step = bfs(grid, H, W)
    if step < 0:
        return -1

    orig_black = 0
    for row in grid:
        orig_black += row.count('
    return H*W - orig_black - step -1


def main(args):
    grid = []
    H, W = map(int, input().split())
    for _ in range(H):
        grid.append(list(input().strip()))
    ans = solve(grid, H, W)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):
import queue

def solve():
    h, w = map(int, input().split())

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

    dist = [[h*w*100 for i in range(w)] for j in range(h)]
    dist[0][0] = 1

    q = queue.Queue()
    q.put((0,0))

    dx = [-1,1,0,0]
    dy = [0,0,1,-1]
    while not q.empty() :
        (x,y) = q.get()
        for dx,dy in [(-1,0),(1,0),(0,-1),(0,1)] :
            nx = x + dx
            ny = y + dy
            if nx < 0 or nx >= h or ny < 0 or ny>= w :
                continue
            if field[nx][ny] == '
                continue
            if dist[nx][ny] > dist[x][y] + 1 :
                dist[nx][ny] = dist[x][y] + 1
                q.put((nx,ny))

    if dist[h-1][w-1] >= h*w :
        return -1

    

    ans = h*w - dist[h-1][w-1]
    for v in field:
        for c in v:
            if c == '
                ans -= 1

    return ans

if __name__ == '__main__':
    print(solve())

Solution (Python):
from collections import deque
H, W = map(int, input().split())
S = [input() for i in range(H)]
C = sum(s.count('.') for s in S)

dd = ((-1, 0), (0, -1), (1, 0), (0, 1))
que = deque([(0, 0, 0)])
used = {(0, 0)}

res = None
while que:
    s, t, cost = que.popleft()
    if s == H-1 and t == W-1:
        res = cost
        break
    for di, dj in dd:
        ni = s + di; nj = t + dj
        if (not 0 <= ni < H) or (not 0 <= nj < W) or S[ni][nj] == '
            continue
        used.add((ni, nj))
        que.append((ni, nj, cost + 1))
if res:
    print(C - 1 - res)
else:
    print(-1)

Solution (Python):
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


h, w = map(int, input().split())
field = [input() for _ in range(h)]
init_black = sum(r.count('
res = dfs(field)
if res == -1:
    print(-1)
else:
    print(h * w - res - init_black)