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

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

dist = [[0] * W for _ in range(H)]
dist[0][0] = 1
q = deque([(0, 0)])

while q:
    u, v = q.popleft()
    for i, j in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        if (not (0 <= u + i < H and 0 <= v + j < W)
                or X[u + i][v + j] == "
                or dist[u + i][v + j] > 0):
            continue
            
        dist[u + i][v + j] = dist[u][v] + 1
        q.append((u + i, v + j))

if dist[-1][-1] > 0:
    print(W * H - dist[-1][-1] - sum(s.count("
else:
    print(-1)

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


white_cells = sum([s[h].count(".") for h in range(H)])


record = [[[0,0]]]
li = []
if s[1][0] == ".":
    li.append([1,0])
if s[0][1] == ".":
    li.append([0,1])
record.append(li)

count = 1
while True:
    if record[count] == []:
        print(-1)
        break
    li = []
    for p in record[count]:
        h = p[0]
        w = p[1]
        next_to_p = []
        if h > 0 and s[h-1][w] == "." and [h-1, w] not in record[count-1] + li:
            next_to_p.append([h-1, w])
        if w > 0 and s[h][w-1] == "." and [h, w-1] not in record[count-1] + li:
            next_to_p.append([h, w-1])
        if h < H-1 and s[h+1][w] == "." and [h+1, w] not in record[count-1] + li:
            next_to_p.append([h+1, w])
        if w < W-1 and s[h][w+1] == "." and [h, w+1] not in record[count-1] + li:
            next_to_p.append([h, w+1])
        li = li + next_to_p
    if [H-1, W-1] in li:
        print(white_cells - count - 2)
        break
    record.append(li)
    count += 1

Solution (Python):
from collections import deque
h,w=map(int,input().split())
s=[list(input()) for i in range(h)]
cntW=0
for i in range(h):
  for j in range(w):
    if s[i][j]=='.':
      cntW+=1
dist=[[-1]*w for i in range(h)]
dist[0][0]=0
q=[(0,0)]
q=deque(q)
dx=[1,0,-1,0]
dy=[0,1,0,-1]
while q:
  y,x=q.pop()
  for i in range(4):
    ny,nx=y+dy[i],x+dx[i]
    if 0<=ny<h and 0<=nx<w and dist[ny][nx]==-1 and s[ny][nx]=='.':
      dist[ny][nx]=dist[y][x]+1
      q.appendleft((ny,nx))
if dist[-1][-1]==-1:
  print(-1)
else:
  print(cntW-dist[-1][-1]-1)

Solution (Python):
R, C = list(map(int, input().split()))

dist = [[0] * C for i in range(R)]

count_white = 0

for i in range(R):
    c_str = input()
    for j in range(len(c_str)):
        if c_str[j]=='
            dist[i][j] = -1
        else:
            dist[i][j] = -2
            count_white += 1

def check(x, y):
    global dist
    
    if x < 0:
        return False
    if x >= len(dist):
        return False
    if y < 0:
        return False
    if y >= len(dist[0]):
        return False
    
    if dist[x][y]!=-2:
        return False
    
    return True
    
            

q = [[0, 0]]
dist[0][0] = 0

while(q):
    x = q[0][0]
    y = q[0][1]
    
    if check(x-1,y):
        dist[x-1][y] = dist[x][y] + 1
        q.append([x-1, y])
    if check(x+1,y):
        dist[x+1][y] = dist[x][y] + 1
        q.append([x+1, y])
    if check(x,y-1):
        dist[x][y-1] = dist[x][y] + 1
        q.append([x, y-1])
    if check(x,y+1):
        dist[x][y+1] = dist[x][y] + 1
        q.append([x, y+1])
    
    q.pop(0)

if dist[-1][-1]==-2:
    print(-1)
else:
    print(count_white - dist[-1][-1] -1)

Solution (Python):
from collections import deque
 
def bfs(maze, visited, sy, sx, gy, gx):
  queue = deque([[sy, sx]])
  visited[sy][sx] = 0
  while queue:
    y,x = queue.popleft()
    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])
  return visited[gy][gx]

h,w = map(int,input().split())
wall = ''
for i in range(w+2):
  wall += '
maze = [wall]
for i in range(h) :
  m1 = input()
  maze.append('
maze .append(wall)

b_now = 0
for i in range(1,h+1) :
  for j in range(1,w+1) :
    if maze[i][j] == '
      b_now += 1

visited = [[-1]*(w+2) for _ in range(h+2)]
cnt = bfs(maze, visited, 1, 1, h, w)
b_need = h*w - cnt - 1

if cnt == -1 :
  print(-1)
else :
  print(b_need-b_now)

Solution (Python):
from collections import deque

inf = float('inf')
H,W = (int(x) for x in input().split())
maze = [['
white = 0
for i in range(1,H+1):
    line = input()
    white += line.count('.')
    maze[i] = '

dh,dw = [0,1,0,-1],[1,0,-1,0]
sh,sw = (1,1)
ans = -1

def bfs(sh,sw):
    seen = deque()
    dist = [[inf]*(W+2) for _ in range(H+2)]
    seen.append((sh,sw))
    dist[sh][sw] = 0
    while seen:
        h,w = seen.popleft()
        if (h,w) == (H,W):
            break
        for i in range(4):
            nh,nw = h+dh[i], w+dw[i]
            if nh < 1 or H < nh: continue
            if nw < 1 or W < nw: continue
            if maze[nh][nw] == '
            if dist[nh][nw] != inf: continue
            dist[nh][nw] = dist[h][w] + 1
            seen.append((nh,nw))
    return dist[H][W]

if bfs(sh,sw) != inf:
    ans = white - (bfs(sh,sw) + 1)
print(ans)

Solution (Python):
import math
import string
import collections
from collections import Counter
from collections import deque


def readints():
    return list(map(int, input().split()))


def nCr(n, r):
    return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))


def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not(item in seen):
            seen.append(item)
    return len(seq) != len(seen)


def divisor(n):
    divisor = []
    for i in range(1, n+1):
        if n % i == 0:
            divisor.append(i)
    return divisor



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

H, W = map(int, input().split())
white = 0
w = [None]*H
for i in range(H):
    w[i] = input()
    
for i in range(H):
    for j in range(W):
        if w[i][j] == '.':
            white += 1

d = deque()
d.append((0, 0))
dist = [None]*H
for i in range(H):
    dist[i] = [None]*W
dist[0][0] = 0
cost = 100
while(len(d) != 0):
    g, r = d.popleft()
    
    if w[g][r] == '.':
        if g != 0 and dist[g-1][r] == None:
            dist[g-1][r] = dist[g][r]+1
            d.append((g-1, r))
        if g != H-1 and dist[g+1][r] == None:
            dist[g+1][r] = dist[g][r]+1
            d.append((g+1, r))
        if r != 0 and dist[g][r-1] == None:
            dist[g][r-1] = dist[g][r]+1
            d.append((g, r-1))
        if r != W-1 and dist[g][r+1] == None:
            dist[g][r+1] = dist[g][r]+1
            d.append((g, r+1))
    if H-1 == g and W-1 == r:
        cost = min(cost, dist[g][r])
        print(white-(cost+1))
        exit()
if dist[H-1][W-1] == None:
    print(-1)

Solution (Python):

from collections import deque


def submit():
    h, w = map(int, input().split())
    board = [input() for _ in range(h)]

    white = 0
    for i in range(h):
        for j in range(w):
            if board[i][j] == ".":
                white += 1
    
    q = deque()
    q.appendleft((0, 0))
    dist = {(i, j): -1 for i in range(h) for j in range(w)}
    dist[(0, 0)] = 1
    while len(q):
        x, y = q.pop()
        d = dist[(x, y)]
        if (x, y) == (h - 1, w - 1):
            break

        if 0 <= x - 1 and dist[(x - 1, y)] < 0 and board[x - 1][y] == '.':
            dist[(x - 1, y)] = d + 1
            q.appendleft((x - 1, y))
        if x + 1 < h and dist[(x + 1, y)] < 0 and board[x + 1][y] == '.':
            dist[(x + 1, y)] = d + 1
            q.appendleft((x + 1, y))
        if 0 <= y - 1 and dist[(x, y - 1)] < 0 and board[x][y - 1] == '.':
            dist[(x, y - 1)] = d + 1
            q.appendleft((x, y - 1))
        if y + 1 < w and dist[(x, y + 1)] < 0 and board[x][y + 1] == '.':
            dist[(x, y + 1)] = d + 1
            q.appendleft((x, y + 1))

    if dist[(h - 1, w - 1)] < 0:
        print(-1)
    else:
        print(white - dist[(h - 1, w - 1)])

    
submit()

Solution (Python):
import sys
sys.setrecursionlimit(5000)

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




waiting=[]
dx=[1,0,-1,0]
dy=[0,1,0,-1]
def func(xy):
    x, y = xy
    for i in range(4):
        if 0<=y+dy[i]<H and 0<=x+dx[i]<W:
            if walker[y+dy[i]][x+dx[i]] == None and s[y+dy[i]][x+dx[i]]=='.':
                walker[y + dy[i]][x + dx[i]]=walker[y][x]+1
                waiting.append((x+dx[i], y+dy[i]))
    if waiting:
        func(waiting.pop(0))
    else:
        return None

walker=[]
for row in range(H):
    walker.append([None]*W)

walker[0][0]=0
func((0,0))

if walker[H-1][W-1] != None:
    minimum=walker[H-1][W-1]

    white_count=0
    for row in range(H):
        white_count += s[row].count('.')
    
    print(white_count-minimum-1)
else:
    print(-1)

Solution (Python):
from collections import deque
import sys
sys.setrecursionlimit(10 ** 6)
def input():
    return sys.stdin.readline()[:-1]

H,W=[int(i) for i in input().split()]
C=[input() for _ in range(H)]
C=[list(i) for i in C] 

ans = 10**9

visited_list = [[10**9]*W for _ in range(H)]
stack = deque([[0, 0, 0]])
visited_list[0][0] = 0

w_cnt=0
for c in C: w_cnt += c.count(".")

def dfs(town, visited_list, stack):
    global ans
    flag = 0
    while len(stack) > 0:
        h, w, cnt = stack.pop()
        if h == H-1 and w == W-1 and ans > cnt:
            ans = cnt
            flag = 1
            continue
        for j, k in ([1, 0], [0, 1], [-1, 0], [0, -1]):
            new_h, new_w = h+j, w+k
            if new_h < 0 or new_h >= H or new_w < 0 or new_w >= W:
                continue
            if  town[new_h][new_w] != "
                visited_list[new_h][new_w] = cnt + 1
                stack.append([new_h, new_w, cnt+1])
    if flag: 
        ans = w_cnt-(ans+1)
        return ans
    else: return -1

print(dfs(C, visited_list, stack))

Solution (Python):
from queue import Queue

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

def movable(S,vy,vx):
    if 0 <= vy and vy < H and 0 <= vx and vx < W:
        if S[vy][vx] == ".":
            return True
    return False

def bfs(S):
    sy,sx,gy,gx = 0,0,H,W
    Dist = [[None for _ in range(W)] for _ in range(H)]
    vec = [(-1,0),(1,0),(0,-1),(0,1)]
    q = Queue()
    q.put((sy,sx))
    Dist[sy][sx] = 0
    while not q.empty():
        p = q.get()
        py,px = p[0],p[1]
        for vy,vx in vec:
            if movable(S,py+vy,px+vx):
                q.put((py+vy,px+vx))
                Dist[py+vy][px+vx] = Dist[py][px]+1
                S[py+vy][px+vx] = "
    return Dist[H-1][W-1]

def white_sum(S):
    count = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == ".":
                count += 1
    return count

white_sum = white_sum(S)
d_H_W = bfs(S)
if d_H_W == None:
    print(-1)
else:
    print(white_sum - d_H_W - 1)

Solution (Python):
import sys
readline = sys.stdin.buffer.readline

from collections import deque
import copy

def myinput():
    return map(int,readline().split())

def mycol(data,col):
    return [ row[col] for row in data ]

h,w = myinput()

maze = [ list(input()) for _ in range(h) ]


white = 0
black = 0
for i in range(h):
    for j in range(w):
        s = maze[i][j]
        if s==".":
            white += 1
        elif s=="
            black += 1
        else:
            pass



def bfs(sy,sx):
    q = deque()
    q.append([sy,sx])
    d = [ [float("inf")]*w for _ in range(h) ]
    d[sy][sx] = 0
    while q:
        y,x = q.popleft()
        if y==(h-1) and x==(w-1):
            break
        else:
            for i,j in ([0,1],[1,0],[-1,0],[0,-1]):
                ny = y + i
                nx = x + j
                if ny==-1 or nx==-1 or ny==h or nx==w:
                    pass
                elif maze[ny][nx]=="
                    pass
                elif d[ny][nx]!=float("inf"):
                    pass
                else:
                    d[ny][nx] = d[y][x] + 1
                    q.append([ny,nx])
    return d[h-1][w-1]

path = bfs(0,0)


if path==float("inf"):
    print(-1)
    exit()
else:
    ans = white - ( path + 1 )
    print(ans)
    exit()

Solution (Python):
from collections import deque
import sys

H,W = map(int,input().split())
maze = [list(input())for _ in range(H)]
count = 0
for i in range(H):
  for j in range(W):
    if maze[i][j]==".":
      count += 1

maze[0][0]=0

patterns = [[1,0],[-1,0],[0,1],[0,-1]]
que=deque([[0,0]])
flag = True
while que:
  now = que.popleft()
  nowY = now[0]
  nowX = now[1]
  nowstep = maze[nowY][nowX]
  if nowY == H-1 and nowX == W-1:
    flag = False
    break
  for pattern in patterns:
    nextY = nowY + pattern[0]
    nextX = nowX + pattern[1]
    nextstep = nowstep + 1
    if 0<=nextY<H and 0<=nextX<W and maze[nextY][nextX]==".":
      que.append([nextY,nextX])
      maze[nextY][nextX]=nextstep
      
if flag:
  print(-1)
else:
  print(count-nowstep-1)

Solution (Python):


from collections import deque

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

    
    q = deque()
    q.append((0, 0, 1))
    queued = [[False] * w for i in range(h)]
    queued[0][0] = True
    while q:
        i, j, l = q.popleft()
        if (i, j) == (h - 1, w - 1):
            break
        for di, dj in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
            i2 = i + di
            j2 = j + dj
            if i2 < 0 or i2 >= h:
                continue
            if j2 < 0 or j2 >= w:
                continue
            if queued[i2][j2]:
                continue
            if s[i2][j2] == "
                continue
            q.append((i2, j2, l + 1))
            queued[i2][j2] = True
    else:
        print(-1)
        return

    
    num_white = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                num_white += 1
    print(num_white - l)

if __name__ == "__main__":
    main()

Solution (Python):


from collections import deque

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

    
    q = deque()
    queued = [[False] * w for i in range(h)]
    q.append((0, 0, 1))
    queued[0][0] = True
    res = None
    while q:
        i, j, l = q.popleft()
        if (i, j) == (h - 1, w - 1):
            res = l
            break
        for di, dj in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
            i2 = i + di
            j2 = j + dj
            if i2 < 0 or i2 >= h:
                continue
            if j2 < 0 or j2 >= w:
                continue
            if queued[i2][j2]:
                continue
            if s[i2][j2] == "
                continue
            q.append((i2, j2, l + 1))
            queued[i2][j2] = True

    if res is None:
        print(-1)
        return

    
    num_white = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                num_white += 1
    print(num_white - res)

if __name__ == "__main__":
    main()

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

from collections import deque
sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  

H, W = na()
g = [ns() for _ in range(H)]
d = [[-1] * W for _ in range(H)]
ct = 0
for i in range(H):
    ct += g[i].count('
d[0][0] = 1
que = deque()
que.append((0, 0))
while que:
    y, x = que.popleft()
    if y == H - 1 and x == W - 1:
        break
    for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        ny = y + dy
        nx = x + dx
        if 0 <= ny < H and 0 <= nx < W and g[ny][nx] != '
            d[ny][nx] = d[y][x] + 1
            que.append((ny, nx))
if d[H-1][W-1] == -1:
    print(-1)
else:
    print(H * W - ct - d[H-1][W-1])

Solution (Python):
import sys
from collections import deque
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)


def inpl():
    return list(map(int, input().split()))


H, W = inpl()
S = ["
S = ["
sharp = sum(len(list(filter(lambda x: x == "
sharp -= 2 * H + (W + 2) * 2

mp = [[-1] * (W + 2) for i in range(H + 2)]
mp[1][1] = 0
Q = deque()
Q.append((1, 1))
dhw = [(1, 0), (0, 1), (-1, 0), (0, -1)]
while Q:
    h, w = Q.popleft()
    for dh, dw in dhw:
        if S[h + dh][w + dw] == "
            continue
        elif mp[h + dh][w + dw] != -1:
            continue
        mp[h + dh][w + dw] = mp[h][w] + 1
        Q.append((h + dh, w + dw))

if mp[H][W] == -1:
    print(-1)
else:
    print(H * W - mp[H][W] - 1 - sharp)

Solution (Python):
import sys

h,w=map(int,input().split())
sys.setrecursionlimit(h*w+10)
s=[list(input()) for i in range(h)]
inf=1000000000000000
d=[[inf]*w for i in range(h)]


def dfs(i,j):
    global h,w,s
    nex=[(0,-1),(0,1),(-1,0),(1,0)]
    for k in range(4):
        l,m=i+nex[k][0],j+nex[k][1]
        if 0<=i+nex[k][0]<h and 0<=j+nex[k][1]<w:
            if s[l][m]=="." and d[l][m]>d[i][j]+1:
                d[l][m]=d[i][j]+1
                dfs(l,m)
d[0][0]=0
dfs(0,0)
ans=0
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            ans+=1
if d[h-1][w-1]==inf:
    print(-1)
else:
    print(ans-d[h-1][w-1]-1)

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

def main():
    H, W = map(int, input().split())
    board = [input().strip() for i in range(H)]
    check = [[False] * W for i in range(H)]

    ans = 0
    for y in range(H):
        for x in range(W):
            if board[y][x] == ".":
                ans += 1

    q = deque()
    q.append((0, 0, 0))
    check[0][0] = True
    while len(q) > 0:
        cost, x, y = q.popleft()
        if x == W-1 and y == H-1:
            print(ans - 1 - cost)
            return
        for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
            if 0 <= nx and nx < W and 0 <= ny and ny < H:
                if board[ny][nx] == "." and not check[ny][nx]:
                    q.append((cost+1, nx, ny))
                    check[ny][nx] = True
    print(-1)

if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque

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

inf = 10 ** 6

dx = [1,0,-1,0]
dy = [0,1,0,-1]
q = deque([[0,0]])
d = [[inf] * w for _ in range(h)]
d[0][0] = 0

while q:
    v = q.popleft()
    if v == [h-1, w-1]:
        break
    for i in range(4):
        x = v[0] + dx[i]
        y = v[1] + dy[i]
        if x>=0 and x<h and y>=0 and y<w and s[x][y]==".":
            if d[x][y] == inf:
                q.append([x,y])
                d[x][y] = d[v[0]][v[1]] + 1

if d[h-1][w-1] == inf:
    print(-1)
else:
    numw = 0
    for i in range(h):
        numw += s[i].count(".")
    print(numw - d[h-1][w-1] -1)

Solution (Python):


from collections import deque

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

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



def is_valid(i, j):
    cond_i = 0 <= i <= H - 1
    cond_j = 0 <= j <= W - 1
    return cond_i and cond_j


def is_reachable(i, j, ):
    if is_valid(i, j):
        if field[i][j] == '.':
            return True
    return False


def adj(i, j):
    up, down = [i - 1, j], [i + 1, j]
    left, right = [i, j - 1], [i, j + 1]
    res = []
    for i_adj, j_adj in up, down, left, right:
        if is_reachable(i_adj, j_adj):
            res.append([i_adj, j_adj])
    return res


def bfs(que, dist):
    while len(que) > 0:
        i, j = que.popleft()
        
        for i_adj, j_adj in adj(i, j):
            
            if dist[(i_adj, j_adj)] == -1:
                que.append([i_adj, j_adj])
                dist[(i_adj, j_adj)] = dist[(i, j)] + 1


que = deque()
keys = [(i, j) for i in range(H) for j in range(W)]
values = [-1 for _ in range(H * W)]
dist = dict(zip(keys, values))


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

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

if dist[(H - 1, W - 1)] == -1:
    print(-1)
else:
    steps_min = dist[(H - 1, W - 1)] + 1
    n_white = W * H - n_black
    ans = n_white - steps_min
    print(ans)

Solution (Python):


from collections import deque

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

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



def is_valid(i, j):
    cond_i = 0 <= i <= H - 1
    cond_j = 0 <= j <= W - 1
    return cond_i and cond_j


def is_reachable(i, j, ):
    if is_valid(i, j):
        if field[i][j] == '.':
            return True
    return False


def adj(i, j):
    up, down = [i - 1, j], [i + 1, j]
    left, right = [i, j - 1], [i, j + 1]
    res = []
    for i_adj, j_adj in up, down, left, right:
        if is_reachable(i_adj, j_adj):
            res.append([i_adj, j_adj])
    return res


def bfs(que, dist):
    while len(que) > 0:
        i, j = que.popleft()
        
        for i_adj, j_adj in adj(i, j):
            
            if dist[(i_adj, j_adj)] == -1:
                que.append([i_adj, j_adj])
                dist[(i_adj, j_adj)] = dist[(i, j)] + 1


que = deque()
keys = [(i, j) for i in range(H) for j in range(W)]
values = [-1 for _ in range(H * W)]
dist = dict(zip(keys, values))


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

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

if dist[(H - 1, W - 1)] == -1:
    print(-1)
else:
    steps_min = dist[(H - 1, W - 1)] + 1
    n_white = W * H - n_black
    ans = n_white - steps_min
    print(ans)

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

q = deque()
q.append([0, 0])
distance = [[1000]*W for _ in range(H)]
distance[0][0] = 0
adjacent = [[1, 0], [0, 1], [-1, 0], [0, -1]]
while len(q):
    cy, cx = q.popleft()
    for dy, dx in adjacent:
        ny, nx = cy+dy, cx+dx
        if ny < 0 or ny >= H or nx < 0 or nx >= W:
            continue
        if distance[ny][nx] != 1000:
            continue
        if grid_graph[ny][nx] == "
            continue
        distance[ny][nx] = distance[cy][cx] + 1
        q.append([ny, nx])
black = 0
if distance[H-1][W-1] == 1000:
    print(-1)
    exit()
for i in range(H):
    for j in range(W):
        if grid_graph[i][j] == "
            black += 1
print(H*W - distance[H-1][W-1] - black - 1)

Solution (Python):

from collections import deque
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
moves = ((1, 0), (0, 1), (0, -1), (-1, 0))

def bfs(sy, sx):
    q = deque([[sy, sx]])
    dist = [[float('inf')]*w for _ in range(h)]
    dist[sy][sx] = 0 

    while q:
        y, x = q.popleft()
        for dy, dx in moves:
            ny = y + dy 
            nx = x + dx 
            if 0 <= ny < h and 0 <= nx < w and dist[ny][nx] == float('inf') and s[ny][nx] != '
                dist[ny][nx] = dist[y][x] + 1 
                q += [[ny, nx]]

    return dist 

d = bfs(0, 0)[h-1][w-1]
if d == float('inf'):
    print(-1)
    exit()
block = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == '
            block += 1
print(h*w-d-block-1)

Solution (Python):
import sys
from copy import deepcopy
from collections import deque
sys.setrecursionlimit(10**6)

H, W = [int(n) for n in input().split(' ')]
S = [list(input()) for i in range(H)]

dist = [[-1]*W for i in range(H)]
dist[0][0] = 1
Q = deque([])
Q.append([0,0])
while Q:
    y, x = Q.popleft()
    if [y, x] == [H-1, W-1]:
        break
    for i, j in [[1,0], [-1,0], [0,1], [0,-1]]:
        if y+i<0 or x+j<0 or y+i>=H or x+j>=W:
            continue
        if dist[y+i][x+j]==-1 and S[y+i][x+j]==".":
            dist[y+i][x+j] = dist[y][x] + 1
            Q.append([y+i, x+j])
if dist[H-1][W-1]==-1:
    print(-1)
else:
    white = 0
    for i in range(H):
        for j in range(W):
            if S[i][j]==".":
                white += 1
    print(white-dist[H-1][W-1])

Solution (Python):

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

ans=0
for i in range(h):
    ans+=maze[i].count('.')

for i in range(h):
    maze[i]=['
maze=[['

import collections
from collections import deque
def clear_maze(sx, sy, gx, gy):

    INF=-10**9
    distance = [[INF for i in range(w+1)] for j in range(h+1)]
    
    def bfs():
        d = deque()
        d.appendleft((sx, sy))
        distance[sx][sy] = 0

        while len(d):
            x, y = d.pop()
            if x == gx and y == gy:
                break
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

                if (0 <= nx and  0 <= ny  and maze[nx][ny] != '
                    d.appendleft ((nx, ny))
                    distance[nx][ny] = distance[x][y] + 1

        return distance[gx][gy]

    return bfs()
v=clear_maze(1,1,h,w)

if v==-10**9:
    print(-1)
else:
    print(ans-v-1)

Solution (Python):
from collections import deque

import numpy as np
import sys


sys.setrecursionlimit(5000)

def bfs(point, field, target, H, W):
    visited = [[-1 for _ in range(W+2)] for _ in range(H+2)]
    visited[point[0]][point[1]] = 1
    que = deque()
    que.append(point)

    while True:
        v = que.popleft()
        depth = visited[v[0]][v[1]]
        for a in [(v[0]-1, v[1]), (v[0]+1, v[1]), (v[0], v[1]-1), (v[0], v[1]+1)]:
            if field[a[0]][a[1]] == 0 and visited[a[0]][a[1]] == -1:
                visited[a[0]][a[1]] = 1 + depth
                if a == target:
                    return visited[a[0]][a[1]]
                else:
                    que.append(a)
        if len(que) == 0:
            return 0

def main():
    H, W = list(map(int, input().split()))
    target = (H, W)
    field = [[-1] * (W+2)]
    number_of_whites = 0
    for _ in range(H):
        s = input()
        number_of_whites += s.count('.')
        field.append([-1] + [0 if c=='.' else -1 for c in s] + [-1])
    field += [[-1] * (W+2)]

    shortest_path = bfs((1, 1), field, target, H, W)
    if shortest_path > 0:
        print(number_of_whites - shortest_path)
    else:
        print(-1)
        
if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

import numpy as np
import sys


sys.setrecursionlimit(5000)

def bfs(point, field, target, H, W):
    visited = [[-1 for _ in range(W+2)] for _ in range(H+2)]
    visited[point[0]][point[1]] = 1
    que = deque()
    que.append(point)

    while True:
        v = que.popleft()
        depth = visited[v[0]][v[1]]
        for a in [(v[0]-1, v[1]), (v[0]+1, v[1]), (v[0], v[1]-1), (v[0], v[1]+1)]:
            if field[a[0]][a[1]] == 0 and visited[a[0]][a[1]] == -1:
                visited[a[0]][a[1]] = 1 + depth
                if a == target:
                    return visited[a[0]][a[1]]
                else:
                    que.append(a)
        if len(que) == 0:
            return 0

H, W = list(map(int, input().split()))
target = (H, W)
field = [[-1] * (W+2)]
number_of_whites = 0
for _ in range(H):
    s = input()
    number_of_whites += s.count('.')
    field.append([-1] + [0 if c=='.' else -1 for c in s] + [-1])
field += [[-1] * (W+2)]

shortest_path = bfs((1, 1), field, target, H, W)
if shortest_path > 0:
    print(number_of_whites - shortest_path)
else:
    print(-1)

Solution (Python):
H, W = list(map(int, input().split()))
M = [[-1]*(W+2)]
ans = 0
for _ in range(H):
    s = input()
    ans += s.count('.')
    M.append([-1]+[0 if c=='.' else -1 for c in s]+[-1])
M += [[-1]*(W+2)]

queue = [(1,1)]
M[1][1] = 1
dr = [(+1,0),(-1,0),(0,+1),(0,-1)]
turn = 1
while len(queue)>0:
    turn += 1
    queue_new = []
    for qx, qy in queue:
        for dx, dy in dr:
            x, y = qx+dx, qy+dy
            if M[y][x]==0:
                M[y][x] = turn
                queue_new.append((x,y))
    queue = queue_new

print(ans-M[H][W] if M[H][W]>0 else -1)

Solution (Python):
from collections import deque

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

    while que:
        cx,cy = que.popleft()
        if cx == w and cy == h:
            break
        for dx,dy in [[1,0],[-1,0],[0,1],[0,-1]]:
            nx, ny = cx+dx, cy+dy
            if 0 <= nx <= h and 0 <= ny <= w and s[nx][ny] != "
                que.append((nx,ny))
                d[nx][ny] = d[cx][cy] + 1
    return d[h][w]

h,w = map(int,input().split())
s = [list(input()) for _ in range(h)]
inf = float("inf")
h,w = h-1,w-1
cnt = bfs()
dot = 0
for i in s:
    dot += i.count(".")
if 0 < cnt < inf:
  print(dot-cnt-1)
else:
  print(-1)