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: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
import queue

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

    block = '#'*(w+2)
    field = [block]
    field.extend(['#' + input() + '#' for _ in range(h)])
    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('#') - 2
    ans += w*2
    return ans

print(solve())

Submission status: Accepted

Solution code:
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()
    # すべての点をINFで初期化
    for i in range(H):
        for j in range(W):
            d[i][j] = float("inf")
    # スタート地点をキューに入れて、その点の距離を0にする
    que.put((sx, sy))
    d[sx][sy] = 0
    
    # キューが空になるまでループ
    while que.qsize() > 0:
        # キューの先頭を取り出す
        p = que.get()
        # 取り出してきた状態がゴールなら探索をやめる
        if p[0] == gx and p[1] == gy:
            break
        # 移動4方向をループ
        for i in range(4):
            # 移動した後の点を(nx, ny)とする
            nx, ny = p[0] + dx[i], p[1] + dy[i]
            
            # 移動が可能かの判定とすでに訪れたことがあるかの判定
            if 0 <= nx < H and 0 <= ny < W:
                if board[nx][ny] != "#" and d[nx][ny] == float("inf"):
                    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()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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() #step, H, W
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("#") for s in S])
    print(H*W - b - s)
else:
    print(-1)

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

Solution code:
H,W = map(int, input().split())
s = [[-1 if w == "#" else 9999 for w in input()] for h in range(H)]
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])

Submission status: Accepted

Solution code:
import sys
import math
import collections
import itertools
import array
import inspect
import pprint

# Set max recursion limit
sys.setrecursionlimit(10000)

# Debug output
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))

# Binary converter
def to_bin(x):
    return bin(x)[2:]

# Set 2 dimension list
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()

Submission status: Accepted

Solution code:
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] == '#' or visited[ny][nx]: continue
        q.append((d+1,nx,ny))
        visited[ny][nx] = 1

print(-1)

Submission status: Accepted

Solution code:
def solve(H, W, s):
    from collections import deque, defaultdict
    dotcount = sum([sum([c == "." for c in row]) for row in s])
    s = [row + "#" for row in s]
    s.append("#" * (W + 1))
    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))

Submission status: Accepted

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

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')

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
h, w = (int(x) for x in input().split())
s = ['#'*(w+2)]+['#'+input()+'#' for _ in range(h)]+['#'*(w+2)]
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])

Submission status: Accepted

Solution code:
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] == '#' or g[-1][-1] == '#'):
    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])

Submission status: Accepted

Solution code:
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]] != "#" and dist[x+dx[i]][y+dy[i]] == "Fail":
            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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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] != "#" and d[nx][ny] == INF:
                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)

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
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)] #  スタート地点からの距離をINFで初期化
    # 迷路を歩いて、スタート地点からゴール地点までの距離を求める
    Q = deque()
    Q.append((0, 0))
    d[0][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]
            # 移動先が 地図からはみ出しておらず and 壁になっておらず and 既に探索済でない 場合
            if (0 <= nx < W) and (0 <= ny < H) and grid[ny][nx] != '#' and d[ny][nx] == float('inf'):
                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:])

Submission status: Accepted

Solution code:
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

    # print(dist)

    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())

Submission status: Accepted

Solution code:
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('#') for r in field)
res = dfs(field)
if res == -1:
    print(-1)
else:
    print(h * w - res - init_black)

Submission status: Runtime Error

Solution code:
import sys
import queue
input = sys.stdin.readline
h,w=map(int,input().split())
maze=[]
count=0
for i in range(h):
  str=input()
  for j in str:
    if j=='#':
      count+=1
  maze.append(str) 
dxdy=[[0,1],[1,0],[0,-1],[-1,0]]
visited=[[False]*w for _ in range(h)]
q=queue.Queue()
q.put((0,0,0))
while(not q.empty()):
  y,x,d=q.get()
  if x==w-1 and y==h-1:
    ans=d
    break
  if visited[y][x]==True:
    continue
  else:
    visited[y][x]==True
    for dx,dy in dxdy:
      if (0<=x+dx<w)and(0<=y+dy<h)and(maze[y+dy][x+dx]=='.'):
        q.put((y+dy,x+dx,d+1))
print(h*w-count-ans-1)

Submission status: Runtime Error

Solution code:
from collections import deque
H, W = map(int, input().split())
route = []
n_black = 0
for _ in range(H):
  tmp_ls = input()
  n_black += tmp_ls.count("#")
  route.append(tmp_ls)
visited = [[False]*W for _ in range(H)]
dist = [[-1]*W for _ in range(H)]
dist[0][0] = 0
tmp = [0,0]
goal = [H-1, W-1]
kouho = deque()
def rinsetsu(ls):
  x, y = ls[0], ls[1]
  ans = []
  if x-1 >= 0:
    ans.append([x-1, y])
  if x+1 <= H-1:
    ans.append([x+1, y])
  if y-1 >= 0:
    ans.append([x, y-1])
  if y+1 <= W-1:
    ans.append([x, y+1])
  return ans
for ls in rinsetsu([0,0]):
  if route[ls[0]][ls[1]] == ".":
    kouho.append([ls[0], ls[1], 0, 0])
def bfs():
  while True:
    while True:
      tmp = kouho.popleft()
      if not visited[tmp[0]][tmp[1]]:
        break
      if len(kouho) == 0:
        return
    x, y = tmp[0], tmp[1]
    visited[x][y] = True
    dist[x][y] = dist[tmp[2]][tmp[3]] + 1
    if [x, y] == goal:
      return
    for ls in rinsetsu([x,y]):
      if not visited[ls[0]][ls[1]] and route[ls[0]][ls[1]] == ".":
        kouho.append(ls + [x, y])
bfs()
if dist[H-1][W-1] == -1:
  print(-1)
else:
  white = dist[H-1][W-1] + 1
  print(H*W - white - n_black)

Submission status: Runtime Error

Solution code:
from collections import deque
H, W = map(int, input().split())
route = []
n_black = 0
for _ in range(H):
  tmp_ls = list(map(int, input().split()))
  n_black += tmp_ls.count("#")
  route.append(tmp_ls)
visited = [[False]*W for _ in range(H)]
dist = [[-1]*W for _ in range(H)]
dist[0][0] = 0
tmp = [0,0]
goal = [H-1, W-1]
kouho = deque()
def rinsetsu(ls):
  x, y = ls[0], ls[1]
  ans = []
  if x-1 >= 0:
    if y-1 >= 0:
      ans.append([x-1, y-1])
    if y+1 <= W-1:
      ans.append([x-1, y+1])
  if x+1 <= H-1:
    if y-1 >= 0:
      ans.append([x+1, y-1])
    if y+1 <= W-1:
      ans.append([x+1, y+1])
  return ans
for ls in rinsetsu([0,0]):
  if route[ls[0]][ls[1]] == ".":
    kouho.append([ls[0], ls[1], 0, 0])
def bfs():
  while True:
    while True:
      tmp = kouho.popleft()
      if not vivited[[tmp[0]][tmp[1]]:
        break
      if len(kouho) == 0:
        return
    x, y = tmp[0], tmp[1]
    visited[x][y] = True
    dist[x][y] = dist[tmp[2]][tmp[3]] + 1
    if [x, y] == goal:
      return
    for ls in rinsetsu([x,y]):
      if not visited[ls[0]][ls[1]] and route[ls[0]][ls[1]] = ".":
        kouho.append(ls + [x, y])
bfs()
if dist[H-1][W-1] == -1:
  print(-1)
else:
  white = dist[H-1][W-1] + 1
  print(H*W - white - n_black)

Submission status: Runtime Error

Solution code:
from collections import deque
H, W = map(int,input().split())
G = [input() for _ in range(H)]
white = 0
dist = [(-1, 0), (1, 0), (0, -1), (0, 1)]
visited = set()
for line in G:
  white+=line.count('.')

D = deque()
D.append((0,0,1))
rout = -1
while D:
  h, w, c = D.popleft()
  if h == H-1 and w == W-1:
    rout = c
    break
  if (h, w) in visited or G[h][w] == '#':
    continue
  else:
    visited.add((h, w))
  for dh, dw in dist:
    if (0<=h+dh<H) and (0<=w+dw<W):
      if (h+dh, w+dw) not in visited and G[h+dh][w+dh] != '#':
        D.append((h+dh, w+dw, c+1))
        
if rout == -1:
  print(rout)
else:
  print(white-rout)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
G = [input() for _ in range(H)]
sy, sx, gy, gx = 0, 0, H - 1, W - 1
seen = [[-1] * W for _ in range(H)]

if G[sy][sx] == '#' or G[gy][gx] == '#':
    print(-1)
    exit()

from collections import deque
que = deque()
que.append([sy, sx])
seen[sy][sx] = 0
while que:
    y, x = que.popleft()
    for d in [-1, 0], [1, 0], [0, -1], [0, 1]:
        dy = y + d[0]
        dx = x + d[1]
        if dy < 0 or H <= dy or dx < 0 or W <= dx:
            continue
        if G[dy][dx] == '#':
            continue
        if seen[dy][dx] > -1:
            continue
        que.append([dy, dx])
        seen[dy][dx] = seen[y][x] + 1

count = 0
bunpu = [0] * (H * W + 1)
if seen[gy][gx] == -1:
    print(-1)
else:
    all = H * W
    black = 0
    for i in range(H):
        for j in range(W):
            if G[i][j] == '#':
                black += 1
    #start point = 0,0 
    ans = all - black - seen[gy][gx] - 1
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

def bfs():
    # たどり着くまでにかかった回数をいれる多重リスト。
    d = [[float("inf")] * w for i in range(h)]
    # 1ノード降りるときにforで回せるようリスト化しておく
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    # 接したポイントを取り込む用のqueを定義
    que = deque([])
    # スタート地点をqueに加える。探索の際はqueから取り出すループを回すので最初だけ先に入れておく
    que.append(sx,sy)
    # スタートからスタートにかかる距離は0なのでinfを0にかえる。
    d[sx][sy] = 0
    # queがあるかぎり続ける
    while que:
        p = que.popleft()
        # 取り出した点がゴールなら終了
        if p[0] == gy and p[1] == gx:
            break
        #　それ以外の時は，接している点を4方向順に取得。一つずつ処理する。
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            # 新しく取得した座標に対しての処理
            # 迷路内に存在する座標であり，壁ではなく，まだ通ったことがなくdがinfの点なら処理する = 新しく取得した道候補の1つ
            if 0 <= nx < r and 0 <= ny < c and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                # 道候補をqueに加える。
                que.append((nx, ny))
                # その道候補への経路までにかかった経路をdに加える。
                d[nx][ny] = d[p[0]][p[1]] + 1
    return d[gy][gx]

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)

Submission status: Runtime Error

Solution code:
from collections import deque
inf = 1000000000
h, w = map(int, input().split())
root = [[-np.inf]*w for i in range(h)]
root[0][0] = 1
s = [[] for i in range(h)]

cnt = 0
for i in range(h):
    s[i] = input()
    for j in range(w):
        if s[i][j] == '#': cnt+=1
dw = [-1, 0, 1, 0]
dh = [0, 1, 0, -1]
que = deque()
que.append([0, 0])
while que:
    x, y = que.pop()
    for dx, dy in zip(dw, dh):
        nx, ny = x+dx, y+dy
        if 0<=nx<w and 0<=ny<h and root[ny][nx]<=0 and s[ny][nx]=='.':
                que.append([nx, ny])
                root[ny][nx] = root[y][x] + 1
if root[h-1][w-1]<0:
    print(-1)
else:
    print(h*w - cnt - root[h-1][w-1])

Submission status: Runtime Error

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
root = [[-np.inf]*w for i in range(h)]
root[0][0] = 1
s = [[] for i in range(h)]

cnt = 0
for i in range(h):
    s[i] = input()
    for j in range(w):
        if s[i][j] == '#': cnt+=1
dw = [-1, 0, 1, 0]
dh = [0, 1, 0, -1]
que = deque()
que.append([0, 0])
while que:
    x, y = que.pop()
    for dx, dy in zip(dw, dh):
        nx, ny = x+dx, y+dy
        if 0<=nx<w and 0<=ny<h and root[ny][nx]<=0 and s[ny][nx]=='.':
                que.append([nx, ny])
                root[ny][nx] = root[y][x] + 1
if root[h-1][w-1]<0:
    print(-1)
else:
    print(h*w - cnt - root[h-1][w-1])