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



Sample input:
3 3
..#
#..
...


Sample output:
2

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
black=0
for i in range(h):
    black+=s[i].count("#")




from collections import deque
stack=deque()
stack.append([0,0])
s[0][0]="#"
while stack:
    
    x=stack.pop()
    dx_dy=[[0,1],[1,0],[0,-1],[-1,0]]
    for k in range(4):
        nx=x[0]+dx_dy[k][0]
        ny=x[1]+dx_dy[k][1]
        if 0<=nx<=h-1 and 0<=ny<=w-1 and s[nx][ny]==".":
            s[nx][ny]="#"
            stack.append([nx,ny])
if s[-1][-1]=="#":
    print(h*w-(h+w-1)-black)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
maze = [list(input()) for i in range(h)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

sx, sy, gx, gy = 0, 0, h - 1, w - 1
d = [[float("inf")] * w for _ in range(h)]

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


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

##最短距離を格納
bfs = bfs()
cnt = 0
for i in range(h):
    for j in range(w):
        if maze[i][j] == ".":
            cnt += 1
if bfs == "inf":
    print(-1)    
else:
    print(cnt - (bfs + 1))

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

hwsss = [s.rstrip() for s in open(0)]
H,W = map(int, hwsss[0].split())
sss = [[int(c=='#') for c in list(l)] for l in hwsss[1:]]

from functools import lru_cache
dhw = [
    [0,1],
    [0,-1],
    [1,0],
    [-1,0],
]
passed = set()

@lru_cache(maxsize=None)
def calc(h,w):
    passed.add((h,w))
    if h == H-1 and w == W-1:
        return 1
    ans = float('inf')
    for dh, dw in dhw:
        nh, nw = h+dh, w+dw
        if 0<=nh<H and 0<=nw<W and sss[nh][nw]==0 and ((nh,nw) not in passed or dh+dw>0):
            ans = min(ans, calc(nh,nw) + 1)
    return ans
result = calc(0,0)
if calc(0,0) == float('inf'):
    print(-1)
else:
    print(H * W - sum(map(sum, sss)) - calc(0,0))

Submission status: Wrong Answer

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

from collections import deque

def bfs():
    seen = [[float('inf')]*W for _ in range(H)]
    que = deque([(0,0)])
    seen[0][0] = 0
    while que:
        a,b = que.popleft()
        if a==W-1 and b==H-1:
            break
        for x,y in [[0,1],[1,0],[0,-1],[-1,0]]:
            nx = x + a
            ny = y + b
            if 0<=nx<W and 0<=ny<H and masu[ny][nx]!='#' and seen[ny][nx] == float('inf'):
                que.append((nx,ny))
                seen[ny][nx] = seen[b][a]+1
    return seen[H-1][W-1]
saitan = bfs()+1
count = 0
for h in range(H):
    for w in range(W):
        if masu[h][w] == '#':
            count += 1
print(H*W-saitan-count)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
readline=sys.stdin.readline
read=sys.stdin.read

h,w=map(int,readline().split())
wb={'#':0,'.':1}
s=[wb[g] for g in read() if g!='\n']
dist=[0]*(h*w)
dist[0]=1
stack=deque([(0,0)])
while stack:
  cg=stack.popleft()
  for i in range(4):
    ng=(cg[0]+(1-2*(i&1))*(i>>1),cg[1]+(1-2*(i&1))*(1-(i>>1)))
    fcg=w*cg[0]+cg[1]
    fng=w*ng[0]+ng[1]
    if 0<=ng[0]<=h-1 and 0<=ng[1]<=w-1 and \
        s[fng] and dist[fng]==0:
      stack.append(ng)
      dist[fng]=dist[fcg]+1
print(sum(s)-dist[-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w=[int(x) for x in input().split()]
c=[]
b=0
for i in range(h):
  C=input()
  b+=C.count("#")
  c.append(C)

dist=[[0]*w for i in range(h)]
dist[0][0]=1
d=deque()
d.append([0,0])

dydx=[[1,0],[0,1],[-1,0],[0,-1]]

while d:
  y,x=d.popleft()
  if y==h-1 and x==w-1:
    break
  for i in range(4):
    ny,nx=y+dydx[i][0],x+dydx[i][1]
    if not(0 <= ny < h) or not(0 <= nx < w) or dist[ny][nx]!=0 or c[ny][nx]=="#":
      continue
    dist[ny][nx]=dist[y][x]+1
    d.append([ny,nx])

ans=h*w-b-dist[h-1][w-1]
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
wall = '#'
maze = [[wall] * (w + 2)]
wn = 0
for y in range(1, h+1):
    maze.append([wall] + [c for c in input()] + [wall])
    for x in range(1, w+1):
        if maze[y][x] == '.':
            wn += 1
maze.append([wall] * (w + 2))

q = deque()
q.append((1, 1, 0))
while q:
    y, x, i = q.popleft()
    if maze[y][x] == '#':
        continue
    if y == h and x == w:
        break
    maze[y][x] = '#'
    i += 1
    q.append((y+1, x, i))
    q.append((y-1, x, i))
    q.append((y, x+1, i))
    q.append((y, x-1, i))
print(wn - i - 1)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = 0
if s[0][0]=="#" or s[h-1][w-1]=="#":
  print(-1)
  exit()
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            ans += 1
s = [["#"] + i + ["#"] for i in s]
s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]]
pos = [[1, 1, 0]]
while len(pos) > 0:
    x, y, cnt = pos.pop(0)
    if x == h and y == w:
        print(ans-(cnt+1))
        break
    s[x][y] = "~"
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            ans += 1
s = [["#"] + i + ["#"] for i in s]
s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]]
pos = [[1, 1, 0]]
while len(pos) > 0:
    x, y, cnt = pos.pop(0)
    if x == h and y == w:
        print(ans-(cnt+1))
        break
    s[x][y] = "~"
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])

Submission status: Wrong Answer

Solution code:
# 白ます数 - 最短距離が答え

import sys
readline = sys.stdin.readline

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

G = [None] * H
white = 0
for i in range(H):
  G[i] = readline().rstrip()
  white += G[i].count(".")

from collections import deque
q = deque([])
# y,x, 距離
q.append([0, 0, 0])
seen = set()
cases = ((0,1),(0,-1),(1,0),(-1,0))
while q:
  y,x,d = q.popleft()
  if (y,x) in seen:
    continue
  seen.add((y,x))
  if y == H - 1 and x == W - 1:
    print(white - d - 1)
    break
  for c in cases:
    if 0 <= y + c[0] < H and 0 <= x + c[1] < W:
      q.append([y + c[0], x + c[1], d + 1])
else:
  print(-1)

Submission status: Wrong Answer

Solution code:
# 白ます数 - 最短距離が答え

import sys
readline = sys.stdin.readline

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

G = [None] * H
white = 0
for i in range(H):
  G[i] = readline().rstrip()
  white += G[i].count(".")

from collections import deque
q = deque([])
# y,x, 距離
q.append([0, 0, 0])
seen = set()
cases = ((0,1),(0,-1),(1,0),(-1,0))
while q:
  y,x,d = q.popleft()
  if (y,x) in seen:
    continue
  seen.add((y,x))
  if y == H - 1 and x == W - 1:
    print(white - d - 1)
    break
  for c in cases:
    if 0 <= y + c[0] < H and 0 <= x + c[1] < W:
      q.append([y + c[0], x + c[1], d + 1])

Submission status: Wrong Answer

Solution code:
import re
import sys
from collections import *
from functools import lru_cache
from heapq import *
from itertools import *

INF=float('inf')

sys.setrecursionlimit(2**31-1)

rfs=lambda:rl().split()
ri=lambda:int(rl())
ris=lambda:list(map(int,rfs()))
rl=lambda:next(sys.stdin)
rs=lambda:rl().strip()
rt=lambda:sys.stdin.read()

def n4(i,j):
    return [
                (i-1,j),
        (i,j+1),        (i,j-1),
                (i+1,j),
    ]

def n8(i,j):
    return [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]

inb=lambda i,j,m,n:0<=i<m and 0<=j<n

###########################################

H,W=ris()
s=rt()

que=deque([(0,0,1)])
vis=[[0]*W for _ in range(H)]
ok=False
while que:
    i,j,k=que.popleft()
    if i+1==H and j+1==W:
        ok=True
        break
    for ni,nj in n4(i,j):
        if inb(ni,nj,H,W) and not vis[ni][nj]:
            vis[ni][nj]=1
            que.append((ni,nj,k+1))

if ok:
    print(H*W-s.count('#')-k)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
A=[]
for i in range(h):
    A.append(list(input()))
kabe=0
for i in range(h):
    for j in range(w):
        if A[i][j]=="#":
            kabe+=1
def bfs():
    while queue:
        x,y,d=queue.pop()
        for i in range(4):
            xx=x+dx[i] ; yy=y+dy[i]
            if xx==h-1 and yy==w-1:
                print(h*w-d-2-kabe);exit()
            if 0<=xx<h and 0<=yy<w and A[xx][yy]==".":
                A[xx][yy]="#"
                queue.append([xx,yy,d+1])


from collections import deque
dx=[-1,0,1,0] ;dy=[0,1,0,-1]
queue=deque([[0,0,0]])
bfs()
print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
INF=10**18
h,w=map(int,input().split())
e=[input() for _ in range(h)]
cnt=0
for i in range(h):
  for j in range(w):
    if e[i][j]=='.':cnt+=1
dx=[-1,0,1,0]
dy=[0,-1,0,1]
sx,sy=0,0
gx,gy=h-1,w-1
q=deque([(sx,sy)])
d=[[INF]*w for _ in range(h)]
d[sx][sy]=1
while q:
  x,y=q.popleft()
  for i in range(4):
    nx=x+dx[i]
    ny=y+dy[i]
    if 0<=nx<h and 0<=ny<w and e[nx][ny]=='.' and d[nx][ny]==INF:
      q.append((nx,ny))
      d[nx][ny]=d[x][y]+1
print(cnt-d[h-1][w-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
H,W = map(int,input().split())
grid = [0] * H
num_black = 0
for i in range(H):
    s = input()
    for j in range(len(s)):
        if s[j] == '#':
            num_black += 1
    grid[i] = list(s)
time_grid = [[0] * W for _ in range(H)]
queue = deque()
queue.append([0,0,0])
while queue:
    y,x,t = queue.popleft()
    for next_y, next_x in [[y+1,x],[y,x+1],[y-1,x],[y,x-1]]:
        if 0 <= next_x < W and 0 <= next_y < H and grid[next_y][next_x] == '.':
            queue.append([next_y,next_x,t+1])
            time_grid[next_y][next_x] = t+1
            grid[next_y][next_x] = '#'
print(H*W-time_grid[-1][-1]-1-num_black)

Submission status: Wrong Answer

Solution code:
from collections import deque


def bfs(sy, sx, gy, gx):
    q = deque([[sy, sx]])
    visited[sy][sx] = 0
    while q:
        y, x = q.popleft()
        if [y, x] == [gy, gx]:
            return visited[y][x]
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            ny, nx = y+j, x+k
            if ny < 0 or ny > h-1 or nx < 0 or nx > w-1 or path[ny][nx] == "#":
                continue
            if path[ny][nx] == "." and visited[ny][nx] == -1:
                visited[ny][nx] = visited[y][x]+1
                q.append([ny, nx])


h, w = map(int, input().split())
path = [input() for _ in range(h)]
visited = [[-1]*w for _ in range(h)]
sy, sx = 0, 0
gy, gx = h-1, w-1
bfs(sy, sx, gy, gx)

count = 0
for i in range(h):
    for j in range(w):
        if path[i][j] == '#':
            count += 1
print(h*w-count-(visited[gy][gx]+1))

Submission status: Wrong Answer

Solution code:
import sys
H,W=map(int,input().split())
L = [[0 for j in range(W)] for i in range(H)]
c=0
for i in range(H):
  a=list(input())
  c+=a.count(".")
  L[i]=a
#幅優先探索？
subete=[[0,0]]
ans = [[] for i in range(H*W+1)]
ans[0].append([0,0])
for i in range(H*W+1):
  for j in range(len(ans[i-1])):
    a,b=ans[i-1][j][0],ans[i-1][j][1]
    if a+1!=H:
      if [a+1,b] not in subete and L[a+1][b]==".":
        ans[i].append([a+1,b])
        subete.append([a+1,b])
    if a!=0:
      if [a-1,b] not in subete and L[a-1][b]==".":
        ans[i].append([a-1,b])
        subete.append([a-1,b])
    if b+1!=W:
      if [a,b+1] not in subete and L[a][b+1]==".":
        ans[i].append([a,b+1])
        subete.append([a,b+1])
    if b!=0:
      if [a,b-1] not in subete and L[a][b-1]==".":
        ans[i].append([a,b-1])
        subete.append([a,b-1])
  if [H-1,W-1] in subete:
    print(c-i-1)
    sys.exit()

Submission status: Wrong Answer

Solution code:
from collections import deque

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

maze = "#" * (W+2)
for _ in range(H):
  maze += "#" + input() + "#"
maze += "#" * (W+2)

dist = [-1] * (W+2) * (H+2)
q = deque()

dist[(W+2) * 1 + 1] = 0
q.append((W+2) * 1 + 1)

while len(q) != 0:
  v = q.popleft()
  
  udlr = (-W-2, W+2, -1, 1)
  for move in udlr:
    nv = v + move
    if maze[nv] == "#":
      continue
    if dist[nv] != -1:
      continue
    dist[nv] = dist[v] + 1
    q.append(nv)

print(W * H - maze.count("#") + 2 * (W + H + 2) - dist[(W+2) * H + W] -1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np

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

direction_x = [1, -1, 0, 0]
direction_y = [0, 0, 1, -1]
reached = np.zeros((H, W))
que_x = [0]
que_y = [0]
can_reach = True

# for x, y in zip(que_x, que_y):
#     if x == H - 1 and y == W - 1:
#         can_reach = True
#         break
#     for i in range(4):
#         next_x = x + direction_x[i]
#         next_y = y + direction_y[i]
#         if not(0 <= next_x < H) or not(0 <= next_y < W):
#             continue
#         if reached[next_x][next_y] == 1 or s[next_x][next_y] == '#':
#             continue
#         reached[next_x][next_y] = 1
#         que_x.append(next_x)
#         que_y.append(next_y)

res = 0
if can_reach:
    for i in range(H):
        for j in range(W):
            if s[i][j] == '.':
                res += 1
    res = res - H - W + 1
else:
    res = -1
print(res)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np

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

direction_x = [1, -1, 0, 0]
direction_y = [0, 0, 1, -1]
reached = np.zeros((H, W))
que_x = [0]
que_y = [0]
can_reach = False

for x, y in zip(que_x, que_y):
    if x == H - 1 and y == W - 1:
        can_reach = True
        break
    for i in range(4):
        next_x = x + direction_x[i]
        next_y = y + direction_y[i]
        if not(0 <= next_x < H) or not(0 <= next_y < W):
            continue
        if reached[next_x][next_y] == 1 or s[next_x][next_y] == '#':
            continue
        reached[next_x][next_y] = 1
        que_x.append(next_x)
        que_y.append(next_y)

res = 0
if can_reach:
    for i in range(H):
        for j in range(W):
            if s[i][j] == '.':
                res += 1
    res = res - H - W + 1
else:
    res = 0
print(res)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np

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

direction_x = [1, -1, 0, 0]
direction_y = [0, 0, 1, -1]
reached = np.zeros((H, W))
que_x = [0]
que_y = [0]
can_reach = False

for x, y in zip(que_x, que_y):
    if x == H - 1 and y == W - 1:
        can_reach = True
        break
    for i in range(4):
        next_x = x + direction_x[i]
        next_y = y + direction_y[i]
        if not(0 <= next_x < H) or not(0 <= next_y < W):
            continue
        if reached[next_x][next_y] == 1 or s[next_x][next_y] == '#':
            continue
        reached[next_x][next_y] = 1
        que_x.append(next_x)
        que_y.append(next_y)

res = 0
if can_reach:
    for i in range(H):
        for j in range(W):
            if s[i][j] == '.':
                res += 1
    res = res - H - W + 1
else:
    res = -1
print(res)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

root = [[float("inf") for _ in range(w)] for _ in range(h)]
root[0][0] = 1
D = deque([[0, 0]])
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

while D:
    p = D.popleft()

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

    for i in range(4):
        x = p[0]+dx[i]
        y = p[1]+dy[i]
        if 0<=x<=h-1 and 0<=y<=w-1 and root[x][y]==float("inf") and maze[x][y]==".":
            root[x][y] = root[p[0]][p[1]] + 1
            D.append([x, y])

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

if maze[h-1][w-1] ==float("inf"):
    print(-1)
else:
    print(white - root[h-1][w-1])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

root = [[float("inf") for _ in range(w)] for _ in range(h)]
root[0][0] = 1
D = deque([[0, 0]])
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

while D:
    p = D.popleft()

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

    for i in range(4):
        x = p[0]+dx[i]
        y = p[1]+dy[i]
        if 0<=x<=h-1 and 0<=y<=w-1 and root[x][y]==float("inf") and maze[x][y]==".":
            root[x][y] = root[p[0]][p[1]] + 1
            D.append([x, y])

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

print(white - root[h-1][w-1])

Submission status: Wrong Answer

Solution code:
import queue

H, W = map(int, input().split())
S = []

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

SS = []
for _ in range(H):
    SSS = []
    for __ in range(W):
        SSS.append(-1)
    SS.append(SSS)

SS[0][0] = 0

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

q = queue.Queue()
q.put(sp)

ans = -1
while not q.empty():

    n = q.get()
    if n[0] == W-1 and n[1] == H-1:
        ans = n[2]
        break

    for d in range(4):
        nx = n[0] + dx[d]
        ny = n[1] + dy[d]

        if W > nx >= 0 and H > ny >= 0 and SS[ny][nx] == -1 and S[ny][nx] != '#':
            q.put((nx, ny, n[2]+1))
            SS[ny][nx] = n[2] + 1

wcnt = 0
for _ in range(H):
    for __ in range(W):
        if S[_][__] == '.':
            wcnt += 1

print(wcnt - ans - 1)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
G = [input() for _ in range(H)]
num = 0
for i in range(H):
    for j in range(W):
        if G[i][j] == ".":
            num += 1
q = deque([(0, 0)])
done = [[-1]*W for _ in range(H)]
done[0][0] = 1
while q:
    w, h = q.popleft()
    for dw, dh in [[0,1], [0, -1], [1, 0], [-1, 0]]:
        nw, nh = w+dw, h+dh
        if not (0 <= nw < W and 0 <= nh < H and done[nh][nw] == -1): continue
        done[nh][nw] = done[h][w]+1
        q.append((nw, nh))
if done[H-1][W-1] != -1:
    print(num-done[H-1][W-1])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
H, W = list(map(int, input().split()))

city = []

for _ in range(H):
    city.append(list(input()))

dist = [[float("inf") for _ in range(W)] for _ in range(H)]

dist_count = [0 for _ in range(H*W)]

queue = deque()
queue.append((0, 0))
dist[0][0] = 0

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

while len(queue) > 0:
    now_x, now_y = queue.popleft()

    for dx_, dy_ in zip(dx, dy):

        adj_x = now_x + dx_
        adj_y = now_y + dy_

        if (not 0 <= adj_x < W) or (not 0 <= adj_y < H):
            continue

        if city[adj_y][adj_x] == "#":
            continue

        if dist[adj_y][adj_x] > H*W:
            dist[adj_y][adj_x] = dist[now_y][now_x] + 1
            queue.append((adj_x, adj_y))
            dist_count[dist[adj_y][adj_x]] += 1

#すぬけ君がどうやってもたどり着けない場合
if dist[H-1][W-1] > H*W:
    print(-1)
    sys.exit()

#すぬけ君がたどり着ける場合
max_dist = dist[H-1][W-1]

ans = 0
for i in range(1, max_dist+1):
    ans += dist_count[i] - 1
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
ss = [input() for _ in range(h)]
q = deque([(0, 0, 0)])
cost = 0
visited = [[False for _ in range(w)] for _ in range(h)]
while len(q) > 0:
    y, x, cost = q.popleft()
    if (y, x) == (h - 1, w - 1):
        break
    if 0 <= y < h and 0 <= x < w and ss[y][x] != '#' and not visited[y][x]:
        visited[y][x] = True
        q.append((y + 1, x, cost + 1))
        q.append((y - 1, x, cost + 1))
        q.append((y, x + 1, cost + 1))
        q.append((y, x - 1, cost + 1))

dots = 0
for i in range(h):
    for j in range(w):
        if ss[i][j] != '#':
            dots += 1
print(dots - cost - 1)