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):
import math
import queue
R,C = list(map(int,input().split(" ")))


gx=C -1
gy=R - 1
mass = [input() for _ in range(R)]
tejun =[ [-1 for i in range(C)] for j in range(R)]
xy = [(1,0),(0,1),(-1,0),(0,-1)]
q = queue.Queue()
q.put((0,0))
tejun[0][0] = 0
while True:
    if q.empty():
        break
    x,y = q.get()
    if x == gx and y == gy:
        break
    for go in xy:
        xmove,ymove = go
        if 0<=x + xmove < C and 0<=y + ymove < R and mass[y + ymove][x+xmove] != "
           if tejun[y + ymove ][x + xmove ] == -1:
               tejun[y + ymove][x + xmove]  = tejun[y][x] + 1
               q.put((x + xmove,y + ymove))
if tejun[gy][gx] == -1:
    print(-1)
    exit()

sharp = 0
for temp in mass:
    sharp+= temp.count("
ans = R*C -(sharp + (tejun[gy][gx] + 1))
print(ans)

Solution (Python):
import sys
import heapq
import numpy as np
INF = 1000000000


def dijkstra(grids, s):
    pq = [(s, 0)]
    while pq:
        u, dist = heapq.heappop(pq)
        if dist >= grids[u][2]:
            continue
        grids[u][2] = dist
        for v in grids[u][1]:
            heapq.heappush(pq, (v, dist + 1))


def main():
    h, w = [int(e) for e in input().split()]
    board = [input() for _ in range(h)]
    grids = [[0, [], INF] for _ in range(h * w)]
    blocks = h * w
    for i, s in enumerate(board):
        for j, c in enumerate(s):
            if c == '.':
                grids[(i * w) + j][0] = 1
                blocks -= 1
    for i, g in enumerate(grids):
        if g[0] == 0:
            continue
        if i % w > 0 and grids[i - 1][0] == 1:
            grids[i][1].append(i - 1)
        if i % w < w - 1 and grids[i + 1][0] == 1:
            grids[i][1].append(i + 1)
        if i // w > 0 and grids[i - w][0] == 1:
            grids[i][1].append(i - w)
        if i // w < h - 1 and grids[i + w][0] == 1:
            grids[i][1].append(i + w)
    dijkstra(grids, 0)
    print(max(-1, (h * w) - (blocks + grids[(h * w) - 1][2] + 1)))


main()

Solution (Python):
from collections import deque
h,w=map(int,input().split())
field=[list(input()) for _ in range(h)]
cost=[[float('inf')]*w for _ in range(h)]
cost[0][0]=1
queue=deque([[0,0]])
count=0
for i in range(h):
    for j in range(w):
        if field[i][j]=='.':
            count+=1
def bfs():
    while queue:
        x,y=queue.popleft()
        for dx,dy in [[1,0],[-1,0],[0,1],[0,-1]]:
            if 0<=x+dx<h and 0<=y+dy<w:
                if field[x+dx][y+dy]=='.' and cost[x+dx][y+dy]==float('inf'):
                    cost[x+dx][y+dy]=cost[x][y]+1
                    queue.append([x+dx,y+dy])
bfs()

if cost[-1][-1]<float('inf'):
    print(count-cost[-1][-1])
else:
    print(-1)

Solution (Python):
from collections import deque
INF = float('inf')
H,W = map(int,input().split())
s = [input() for _ in range(H)]
cost = [[INF]*W for _ in range(H)]
cost[0][0] = 1
 
def bfs():
    que = deque([])
    que.append([0,0])
    while que:
        h,w = que.popleft()
        for dh,dw in [[1,0],[-1,0],[0,1],[0,-1]]:
            if 0<=h+dh<H and 0<=w+dw<W:
                if s[h+dh][w+dw] == '.' and cost[h+dh][w+dw] == INF:
                    cost[h+dh][w+dw] = cost[h][w]+1
                    que.append([h+dh,w+dw])
bfs()
if cost[-1][-1] == INF:
    print(-1)
else:
    ans = H*W-cost[-1][-1]
    for h in range(H):
        ans -= s[h].count('
    print(ans)

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

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

Solution (Python):
import sys
from collections import deque

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(inputs):
    H = len(inputs)
    W = len(inputs[0])
    alter = inputs
    count_dot = 0
    reached_alter = []
    for line in alter:
        a = []
        for mass in line:
            if mass == ".":
                count_dot += 1
            a.append(False)
        reached_alter.append(a)
    queue = deque([[0, 0, 0]])

    min = -1
    while len(queue) > 0:
        [x, y, step_num] = queue.popleft()
        if x == -1 or x == W or y == -1 or y == H:
            continue
        if x == W - 1 and y == H - 1:
            min = step_num
            break
        if alter[y][x] == "
            continue
        reached_alter[y][x] = True

        queue.append([x - 1, y, step_num + 1])
        queue.append([x + 1, y, step_num + 1])
        queue.append([x, y - 1, step_num + 1])
        queue.append([x, y + 1, step_num + 1])

    if min == -1:
        return -1
    return count_dot - min - 1


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    [H, W] = string_to_int(input())
    ret = solve(inputs(H))
    print(ret)

Solution (Python):
delta = [[0,1],[1,0],[0,-1],[-1,0]]
def search(s):
    visited = [[0 for _ in range(W)] for __ in range(H)]
    queue = [[0,0]]
    visited[0][0] = 1
    while queue:
        [i,j] = queue.pop(0)
        for k in range(4):
            i_next = i + delta[k][0]
            j_next = j + delta[k][1]
            if i_next in range(H) and j_next in range(W) and s[i_next][j_next]=='.' and visited[i_next][j_next]==0:
                visited[i_next][j_next] = visited[i][j]+1
                queue.append([i_next,j_next])
    if visited[-1][-1]==0:
        print(-1)


        exit()
    else:
        return visited[H-1][W-1]

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

white = 0
for i in range(H):
    white += len(s[i].replace('

print(white - search(s))

Solution (Python):
from collections import deque
d=[(0,1),(1,0),(0,-1),(-1,0)]
h,w=map(int,input().split())
v=[[0]*w for _ in range(h)]
a=[]
for i in range(h):
    s=input()
    a.append([i for i in s])

wh=sum([''.join(i).count('.') for i in a])

def bfs(t,s):
    rt=0
    q=deque([(t,s)])
    v[t][s]=1
    while q:
        y,x=q.popleft()
        if (y,x)==(h-1,w-1):  
            return
        for dx,dy in d:
            if 0<=y+dy<h and 0<=x+dx<w and v[y+dy][x+dx]==0:
                if a[y+dy][x+dx]=='.':  
                    q.append((y+dy,x+dx))
                    v[y+dy][x+dx]=v[y][x]+1
    return -1

bfs(0,0)
dis=v[-1][-1]
ans=wh-dis if dis>0 else -1
print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
sw = [input() for _ in range(H)]

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


count = [[None]*W for _ in range(H)]
q = deque([])

dy = [1, 0, -1, 0]
dx = [0, -1, 0, 1]
def BFS():
	i, j = q.popleft()
	
	for x, y in zip(dx, dy):
		ny = i + y
		nx = j + x
		if 0 <= ny <= H-1 and 0 <= nx <= W-1 and sw[ny][nx] != '
			count[ny][nx] = count[i][j] + 1
			q.append((ny, nx))

	if len(q) != 0:
		BFS()


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

BFS()


if count[H-1][W-1]:
	print(white-(count[H-1][W-1]+1))
else:
	print(-1)

Solution (Python):
import sys
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())



from queue import Queue
def bfs(field, sy, sx, wall, dir):
    h = len(field)
    w = len(field[0])
    dp = [[-1 for _j in range(w)] for _i in range(h)]
    q = Queue()

    dp[sy][sx] = 0
    q.put((sy, sx))
    
    dy = [1, -1, 0, 0, 1, 1, -1, -1]
    dx = [0, 0, 1, -1, 1, -1, 1, -1]
    def isin(x,y): return 0 <= y and y < h and 0 <= x and x < w
    
    while not q.empty():
        y, x = q.get()
        for k in range(dir):
            ny,nx = y+dy[k],x+dx[k]
            if not isin(nx, ny) or field[ny][nx] == wall:
                continue
            elif dp[ny][nx] != -1:
                continue
            dp[ny][nx] = dp[y][x] + 1
            q.put((ny,nx))
        
    return dp
    


def ABC088_D():
    h, w = mi()
    s = [['' for _j in range(w)] for _i in range(h)]
    for i in range(h):
        s[i] = li()
    dp = bfs(s, 0, 0, '
    if dp[h - 1][w - 1] < 0:
        print(-1)
    else:
        cnt = 0
        for i in range(h):
            for j in range(w):
                cnt += s[i][j] == '.'
        print(cnt - (dp[h - 1][w - 1] + 1))




if __name__ == '__main__':
    ABC088_D()

Solution (Python):
import sys
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())



from queue import Queue
def bfs(field, sy, sx, wall, dir):
    h = len(field)
    w = len(field[0])
    dp = [[-1 for _j in range(w)] for _i in range(h)]
    q = Queue()

    dp[sy][sx] = 0
    q.put((sy, sx))
    
    dy = [1, -1, 0, 0, 1, 1, -1, -1]
    dx = [0, 0, 1, -1, 1, -1, 1, -1]
    def isin(x,y): return 0 <= y and y < h and 0 <= x and x < w
    
    while not q.empty():
        y, x = q.get()
        for k in range(dir):
            ny,nx = y+dy[k],x+dx[k]
            if not isin(nx, ny) or field[ny][nx] == wall:
                continue
            elif dp[ny][nx] != -1:
                continue
            dp[ny][nx] = dp[y][x] + 1
            q.put((ny,nx))
        
    return dp
    


def ABC088_D():
    h, w = mi()
    s = [['' for _j in range(w)] for _i in range(h)]
    for i in range(h):
        s[i] = li()
    dp = bfs(s, 0, 0, '
    if dp[h - 1][w - 1] < 0:
        print(-1)
    else:
        cnt = 0
        for i in range(h):
            for j in range(w):
                cnt += s[i][j] == '.'
        print(cnt - (dp[h-1][w-1]+1))

if __name__ == '__main__':
    ABC088_D()

Solution (Python):
from collections import deque

H, W = map(int, input().split())
S = [input() for i in range(H)]
g = 0
q = deque()
q.append((0, 0))
dist = [[0 for j in range(W)] for i in range(H)]
dr = [(1,0),(-1,0),(0,1),(0,-1)]

while len(q):
    r = q.popleft()
    x = r[1]
    y = r[0]
    now = dist[y][x]
    if y == H-1 and x == W-1:
        g = 1
        break
    for d in range(4):
        nx = x + dr[d][0]
        ny = y + dr[d][1]
        if 0 <= nx < W and 0 <= ny < H:
            if S[ny][nx] != "
                dist[ny][nx] = now+1
                q.append((ny,nx))

sharp = sum([i.count("
if  g == 1:
  print(H * W - now - sharp - 1)
else:
  print(-1)

Solution (Python):


def bfs(graph,start,end):
    queue = [start]
    visited = {}
    visited[start[0],start[1]] = 1
    while queue:
        i,j = queue.pop(0)
        if (i,j) == end:
            return visited[i,j]
        for di,dj in [(1,0),(-1,0),(0,1),(0,-1)]:
            if 0 <= i+di < len(graph) and\
                0 <= j+dj < len(graph[0]) and\
                graph[i+di][j+dj] != "
                (i+di,j+dj) not in visited:
                visited[i+di,j+dj] = visited[i,j] + 1
                queue.append((i+di,j+dj))
    return -1

def get_black_cnt(graph):
    return(sum([s.count("


def solve(H,W,S):
    res = bfs(S,(0,0),(H-1,W-1))
    if res > 0:
        res = H*W-res-get_black_cnt(S)
    print(res)
    pass


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


if __name__ == '__main__':
    main()

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

Solution (Python):
from collections import namedtuple
import pdb

H, W = map(int, input().split())
s = []
visited = []
step = []

Prev = namedtuple('Prev', ('row', 'col', 'num'))
default_black = 0

for _ in range(H):
    line = input()
    for c in line:
        if c=='
            default_black += 1
    s.append(line)
    visited.append([0 for _ in range(W)])
    step.append([0 for _ in range(W)])
    

queue = []

step[0][0] = 1

Point = namedtuple('Point', ('row', 'col'))
st = Point(0, 0)
en = Point(H-1, W-1)



def valid(p):
    return (0 <= p.row and p.row < H and 0 <= p.col and p.col < W)

def around_p(p):
    around = [Point(p.row-1, p.col), Point(p.row+1, p.col), Point(p.row, p.col-1), Point(p.row, p.col+1)]
    for a in around:
        yield a

def goal(p):
    return p.row == H-1 and p.col == W-1

def bfs():
    queue = [st]

    while queue:
        cur_p = queue[0]
        queue = queue[1:]
        if goal(cur_p):
            return step[cur_p.row][cur_p.col]
        if visited[cur_p.row][cur_p.col] == 1:
            continue
        cur_step = step[cur_p.row][cur_p.col]
        visited[cur_p.row][cur_p.col] = 1

        for next_p in around_p(cur_p): 
            if not valid(next_p):
                continue
            if s[next_p.row][next_p.col] == '
                continue
            if visited[next_p.row][next_p.col] == 1:
                continue
            queue.append(next_p)
            step[next_p.row][next_p.col] = cur_step + 1
                        
    return -1

def main():
    ans = bfs()
    if ans == -1:
        print(ans)
    else:
        print(H*W - default_black - ans)


main()

Solution (Python):
h,w=map(int,input().split())
s=[]
for i in range(h):
    s.append(list(input()))
a=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='
            a+=1

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

def dfs(s,visit,h,w,a):
    stack=[[0,0,1]]
    visit[0][0]=1
    while stack:
        sh,sw,c=stack.pop(0)
        if sh==h-1 and sw==w-1:
            return h*w-a-c
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_h, new_w = sh+j, sw+k
            if new_h < 0 or new_h >= h or new_w < 0 or new_w >= w:
                continue
            elif s[new_h][new_w] != "
                visit[new_h][new_w] = 1
                stack.append([new_h,new_w,c+1])
    return -1
  
print(dfs(s,visited,h,w,a))

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 and nx < h and 0 <= ny and 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())
grid = [input() for _ in range(H)]

graph = [[float('inf')] * W for _ in range(H)]
offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def bfs(x, y):
    graph[x][y] = 0

    deq = deque()
    deq.append((x, y))
    
    while deq:
        x, y = deq.popleft()
        
        for i, j in offsets:
            if (not 0 <= x + i < H) or (not 0 <= y + j < W):
                continue
                
            if graph[x + i][y + j] < float('inf'):
                continue
                
            if grid[x + i][y + j] == '
                continue
                
            graph[x + i][y + j] = graph[x][y] + 1
            deq.append((x + i, y + j))
            

bfs(0, 0)
if graph[-1][-1] == float('inf'):
    print(-1)
else:
    black = sum(s.count('
    print(H * W - graph[-1][-1] - black - 1)

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

not_visited=[]
not_visited=[[True for i in range(W)] for j in range(H)]
need_visited=[]
need_visited=[[0 for i in range(W)] for j in range(H)]
need_visited[H-1][W-1]=True
queue=[]

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

start_point=[0, 0]
queue.append(start_point)
while len(queue)!=0:
    now_point=queue.pop(0)
    for i in range(4):
        search_point=[now_point[0]+dx[i], now_point[1]+dy[i]]
        if 0<=search_point[0]<H and 0<=search_point[1]<W:
            if graph[search_point[0]][search_point[1]]!="
                not_visited[search_point[0]][search_point[1]]=False
                queue.append(search_point)
                need_visited[search_point[0]][search_point[1]]=need_visited[now_point[0]][now_point[1]]+1

if need_visited[H-1][W-1]==True:
    print(-1)
else:
    print(road-need_visited[H-1][W-1]-1)

Solution (Python):




from collections import deque

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


class Coordinate(object):
    def __init__(self, x, y, dist=INF):
        self.x = x
        self.y = y
        self.dist = dist


if __name__ == '__main__':
    cnt = 0
    H, W = map(int, input().split())
    grid = [['
    for i in range(H):
        line = list(input())
        cnt += line.count('.')
        grid.append(['
    grid.append(['

    
    queue = deque()
    start = Coordinate(1, 1, 1) 
    goal = Coordinate(W, H)
    queue.append(start)
    distance = [[INF]*(W+2) for i in range(H+2)]
    distance[1][1] = 0

    while len(queue):
        head = queue[0]
        queue.popleft()
        if head.x == goal.x and head.y == goal.y:
            goal.dist = head.dist
            break
        for i in range(4):
            next_p = Coordinate(head.x + dx[i], head.y + dy[i], head.dist)
            if (1 <= next_p.x <= W and 1 <= next_p.y <= H and
                    grid[next_p.y][next_p.x] != '
                        and distance[next_p.y][next_p.x] == INF):
                next_p.dist = head.dist + 1
                distance[next_p.y][next_p.x] = next_p.dist
                queue.append(next_p)

    if goal.dist == INF:
        print(-1)
    else:
        print(cnt - goal.dist)

Solution (Python):
from collections import deque

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

L = []

black = 0

for i in range(H) :
    S = input()
    black += S.count("
    L.append(S)

dxy = [(-1,0),(1,0),(0,-1),(0,1)]

q = deque([(0,0)])

DISTANCE = [[float("inf") for x in range(W)] for y in range(H)]
DISTANCE[0][0] = 0

while q :
    y,x = q.popleft()
    
    for dy,dx in dxy :
        ny,nx = y+dy,x+dx
        
        if (ny < 0) or (ny >= H) or (nx < 0) or (nx >= W) :
            continue
        
        if L[ny][nx] == "
            continue
        
        if DISTANCE[y][x] + 1 >= DISTANCE[ny][nx] :
            continue
        
        DISTANCE[ny][nx] = DISTANCE[y][x] + 1
        q.append([ny,nx])

if DISTANCE[H-1][W-1] == float("inf") :
    ans = -1
else :
    ans = H*W - (DISTANCE[H-1][W-1] + 1) - black

print(ans)

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

s = [input() for i in range(H)]

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

count = 0
for i in range(H):
    for j in range(W):
        if s[i][j]==".":
            if i!=H-1:
                if s[i+1][j]==".":
                    e_list[i*W+j].append((i+1)*W+j)
                    e_list[(i+1)*W+j].append(i*W+j)
            if j!=W-1:
                if s[i][j+1]==".":
                    e_list[i*W+j].append(i*W+j+1)
                    e_list[i*W+j+1].append(i*W+j)
            count+=1

vi = 0 
from collections import deque
Q = deque([vi])
N=H*W
checked_list = [False for i in range(N)]
checked_list[vi]=True
min_path_list = [10**27 for i in range(N)] 
min_path_list[vi] = 0
while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.appendleft(v1)
            min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) 
if min_path_list[H*W-1]<10**9:
    print(count-(1+min_path_list[H*W-1]))
else:
    print(-1)

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

Solution (Python):
import queue

class BreadthFirstSearch:
    def __init__(self, h, w, start_xy, goal_xy, board):
        self.h, self.w = h, w
        (self.sx, self.sy) = start_xy
        (self.gx, self.gy) = goal_xy
        self.board = board
        self.hist = [[False] * w for i in range(h)]

    def get_step(self, wall="
        q = queue.Queue()
        q.put((self.sx, self.sy))
        step = 0
        count = 1
        next_count = 1
        ans = 0
        
        while not q.empty():
            x, y = q.get()
            count -= 1
            if count == 0:
                step += 1
                count = next_count
                next_count = 0
            
            if x == self.gx and y == self.gy:
                ans = step
                break
            for (i, j) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                if not(0 <= x+i <= w - 1) or not(0 <= y+j <= h - 1):
                    continue
                if self.board[y+j][x+i] == wall:
                    continue
                if self.hist[y+j][x+i]:
                    continue
                self.hist[y+j][x+i] = True
                q.put((x+i, y+j))
                next_count += 1
        return ans


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

s_xy = (0, 0)

g_xy = (w - 1, h - 1)

board = [[i for i in list(str(input()))] for i in range(h)]

bfs = BreadthFirstSearch(h, w, s_xy, g_xy, board)
ans = bfs.get_step()
count_black = 0
for y in range(h):
    for x in range(w):
        if board[y][x] == "
            count_black += 1
if ans == 0:
    print("-1")
else:
    print(h * w - ans - count_black)

Solution (Python):
import queue

q = queue.Queue()

h, w = map(int, input().split())
sx, sy = 0, 0
gx, gy = w - 1, h - 1
board = [[i for i in list(str(input()))] for i in range(h)]
hist = [[False] * w for i in range(h)]

q.put((sx, sy))
step = 0
count = 1
next_count = 1
ans = 0
while not q.empty():
    x, y = q.get()
    count -= 1
    if count == 0:
        step += 1
        count = next_count
        next_count = 0
    if x == gx and y == gy:
        ans = step
        break
    for (i, j) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        if not(0 <= x+i <= w - 1) or not(0 <= y+j <= h - 1):
            continue
        if board[y+j][x+i] == "
            continue
        if hist[y+j][x+i]:
            continue
        hist[y+j][x+i] = True
        q.put((x+i, y+j))
        next_count += 1
count_black = 0
for y in range(h):
    for x in range(w):
        if board[y][x] == "
            count_black += 1

if ans == 0:
    print("-1")
else:
    print(h * w - ans - count_black)

Solution (Python):
import sys
from collections import deque

def bfs(maze, visited):
    sy,sx=0,0
    gy,gx=H-1,W-1
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        if [y, x] == [gy, gx]:
            return visited[y][x]

        p=[]
        if x>0 : p.append([0,-1])
        if x<W-1: p.append([0,1])
        if y>0: p.append([-1,0])
        if y<H-1: p.append([1,0])
        for j, k in p:
            new_y, new_x = y+j, x+k
            if 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

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

visited=[[-1]*W for i in range(H)]
ans=sum(m[i].count(".") for i in range(H))
p=bfs(m,visited)
print( p if p==-1 else ans-p-1)

Solution (Python):
import sys
from collections import deque

def bfs(maze, visited):
    try:
        sy,sx=0,0
        gy,gx=H-1,W-1
        queue = deque([[sy, sx]])
        visited[sy][sx] = 0
        while queue:
            y, x = queue.popleft()
            if [y, x] == [gy, gx]:
                return visited[y][x]

            p=[]
            if x>0 : p.append([0,-1])
            if x<W-1: p.append([0,1])
            if y>0: p.append([-1,0])
            if y<H-1: p.append([1,0])
            for j, k in p:
                new_y, new_x = y+j, x+k
                if 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

    except RuntimeError:
        print(-1)
        sys.exit()


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

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

visited=[[-1]*W for i in range(H)]
p=bfs(m,visited)
print( p if p==-1 else ans-p-1)

Solution (Python):





def main():
    
    INF = 10000000

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

    d = [[INF]*W for i in range(H)]

    from collections import deque
    q = deque()

    q.appendleft([0,0])
    d[0][0] = 0

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

    while(len(q)):
        i,j = q.pop()

        for di,dj in dx:
            if(0 <= i+di < H and 0 <= j+dj < W and d[i+di][j+dj] == INF and maze[i+di][j+dj] == '.'):
                q.appendleft([i+di,j+dj])
                d[i+di][j+dj] = d[i][j]+1

    
    if(d[H-1][W-1] == INF):
        print(-1)
    else:
        print(sum([i.count('.') for i in maze]) - d[H-1][W-1] - 1)

if __name__ == '__main__':
    main()

Solution (Python):
h,w=map(int,input().split())
a=[]
for i in range(h):a.append(list(input()))
white=[flatten for inner in a for flatten in inner].count(".")
turn=1
a[-1][-1]=1
while turn in [flatten for inner in a for flatten in inner]:
    for i in range(h):
        for j in range(w):
            if a[i][j]==turn:
                if i>0 and a[i-1][j]==".":a[i-1][j]=turn+1
                if i<h-1 and a[i+1][j]==".":a[i+1][j]=turn+1
                if j>0 and a[i][j-1]==".":a[i][j-1]=turn+1
                if j<w-1 and a[i][j+1]==".":a[i][j+1]=turn+1
    turn+=1
    if a[0][0]!=".":break
print(-1 if a[0][0]=="." else white-a[0][0])

Solution (Python):
from collections import deque


def bfs(maze, visited, sy, sx, gy, gx):
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while True:
        if len(queue) > 0:
            y, x = queue.popleft()
            if [y, x] == [gy, gx]:
                return visited[y][x]
            for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
                new_y, new_x = y+j, x+k
                if 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])
        else:
            return -1


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

visited = [[-1] * (W+2) for i in range(H+2)]
shortest = bfs(s, visited, 1, 1, H, W)
if shortest > 0:
    print(white - shortest - 1)
else:
    print(-1)

Solution (Python):
from collections import deque
h,w = map(int, input().split())
maze = [list(input()) for _ in range(h)]
def repaint(maze,sx,sy):
  maze[sy][sx] = 1 
  que = deque([(sx,sy)])
  dxdy = [(1,0),(0,1),(-1,0),(0,-1)]
  while que:
    x,y = que.popleft()
    for dx,dy in dxdy:
      if 0<=x+dx<w and 0<=y+dy<h and maze[y+dy][x+dx] == ".":
        maze[y+dy][x+dx] = maze[y][x] + 1
        que.append((x+dx,y+dy))
  return True
white = 0
for x in maze:
  white += x.count(".")
repaint(maze,0,0)
if maze[h-1][w-1] == ".":
  print(-1)
else:
  print(white-maze[h-1][w-1])