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:
#coding utf-8
from collections import deque
H,W=map(int,input().split())

s = [list(input().strip()) for _ in range(H)]
d = [[ 0 for i in range(W)] for j in range(H)]
q = deque([])
q.append([0,0,0])
y,x,z=q.popleft()

H = H-1
W = W-1
ans2=0
while y!=H or x!=W:
  if s[y][x]=="." and d[y][x]==0:
    if y<H:
      q.append([y+1,x,z+1])
    if x<W:
      q.append([y,x+1,z+1])
    if y>0:
      q.append([y-1,x,z+1])
    if x>0:
      q.append([y,x-1,z+1])
    d[y][x]=1
  if q==deque([]):
    ans2 = -1
    break
  y,x,z=q.popleft()
  

ans1=0
for i in range(H+1):
  for j in range(W+1):
    if s[i][j]=="#":
      ans1 +=1
      
ans = (H+1)*(W+1)-ans1-z-1
if ans2==-1:
  print(ans2)
else:
  print(ans)

Submission status: Accepted

Solution code:
from collections import Counter
from collections import deque
from functools import reduce
# from pprint import pprint
# import statistics
import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def MI(): return map(int, sys.stdin.readline().split())
def IS(): return input()

h, w = MI()
s = [IS() for _ in range(h)]
q = deque()
x_diff = [-1, 0, 1, 0]
y_diff = [0, 1, 0, -1]
require = [[0 for i in range(w)] for j in range(h)]
check = [[0 for i in range(w)] for j in range(h)]

all_grid = h * w
sharp_count = 0
for i in range(h):
    sharp_count += s[i].count('#')

q.append([0, 0])
check[0][0] = 1

while len(q) != 0:
    tmp_y, tmp_x = q.popleft()
    for i in range(4):
        next_y = tmp_y + y_diff[i]
        next_x = tmp_x + x_diff[i]
        if ( 0 <= next_x <= w-1
            and 0 <= next_y <= h-1
            and check[next_y][next_x] == 0
            and s[next_y][next_x] != '#'):
                check[next_y][next_x] = 1
                require[next_y][next_x] = require[tmp_y][tmp_x] + 1
                q.append([next_y, next_x])

hosuu = require[h-1][w-1]
# print(hosuu)
# require = [[str(require[j][i]).zfill(2) for i in range(w)] for j in range(h)]
# pprint(require, width=400)
if hosuu == 0:
    print(-1)
else:
    print(all_grid - sharp_count - hosuu -1)

Submission status: Accepted

Solution code:
def d_grid_repainting(H, W, S, INF=float('inf')):
    def bfs():
        from collections import deque
        queue = deque([(0, 0)])  # スタート座標は (0, 0) とする
        dist = [[INF for _ in range(W)] for _ in range(H)]  # スタートからの距離
        dist[0][0] = 1  # スタート地点には1歩で到達可能とする
        while queue:
            h, w = queue.pop()
            if h == H - 1 and w == W - 1:
                break  # ゴールした
            for dh, dw in ((-1, 0), (0, 1), (1, 0), (0, -1)):
                nh, nw = h + dh, w + dw  # (h, w) の上右下左
                if 0 <= nh < H and 0 <= nw < W and S[nh][nw] != '#' and dist[nh][nw] == INF:
                    # (nh, nw) はグリッド内、黒マスでない、距離が未確定
                    queue.appendleft((nh, nw))  # 探索する座標
                    dist[nh][nw] = dist[h][w] + 1
        return dist[H - 1][W - 1]

    # ゴールに最短で辿り着こうとしたときに踏んだ白マス(スタートとゴールを含む)の数を調べる。
    # 発散したなら、ゴールに到達できなかったので-1を返す。
    # 有限なら、踏まなかった白マスをすべて黒にすればいいので、
    # (初期状態の白マス - 踏んだ白マス) を返す。
    num_white_square = sum([row.count('.') for row in S])
    reach_white_square_min = bfs()
    return num_white_square - reach_white_square_min if reach_white_square_min != INF else -1

H, W = [int(i) for i in input().split()]
S = [input() for _ in range(H)]
print(d_grid_repainting(H, W, S))

Submission status: Accepted

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

start = (0,0)
goal = (H-1, W-1)

def bfs():
    global H,W,maze,goal,start
    
    count = 0
    visited = [[False for _ in range(W)] for _ in range(H)]
    queue = [start]
    
    visited[start[0]][start[1]] = True
    while len(queue) > 0:
        next_queue = []
        for q in queue:
            if q == goal:
                return count
            x,y = q
            for nx,ny in [(x-1,y), (x+1,y),(x,y-1),(x,y+1)]:
                if 0<=nx<H and 0<=ny<W and not visited[nx][ny] and maze[nx][ny] == '.':
                    next_queue.append((nx, ny))
                    visited[nx][ny] = True
            
        queue = next_queue
        count+=1

    return -1

min_step = bfs()

if min_step == -1:
    print(-1)
else:
    count = 0
    for i in range(H):
        for j in range(W):
            if maze[i][j] == '.':
                count += 1
    answer = count - 1 - min_step
    print(answer)

Submission status: Accepted

Solution code:
from queue import Queue


def main():
    H, W = map(int, input().split())

    white = 0

    grid = [[-1 for _ in range(W + 2)]]
    for _ in range(H):
        line = input()
        white += line.count(".")
        grid.append([-1] + [-1 if char == "#" else -2 for char in line] + [-1])
    grid.append([-1 for _ in range(W + 2)])

    grid[1][1] = 0

    tosearch = Queue()
    tosearch.put((1, 1))

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

    while not tosearch.empty():
        y, x = tosearch.get()

        if (y, x) == (H, W):
            print(white - (grid[H][W] + 1))
            break

        for move in movement:
            ny, nx = y + move[0], x + move[1]

            if grid[ny][nx] == -2:
                grid[ny][nx] = grid[y][x] + 1
                tosearch.put((ny, nx))
    else:
        print(-1)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
field = [input() for x in range(H)]
vx = [0,0,1,-1]
vy = [1,-1,0,0]
reached = [[-1 for x in range(W)]for x in range(H)]
from collections import deque
def bfs(y,x):
    q = deque([[y,x]])
    reached[y][x] = 1

    while q:
        y,x = q.popleft()
        if [y,x] == [H-1,W-1]:
            return reached[y][x]
        for dy,dx in zip(vy,vx):
            ny,nx = y+dy,x+dx
            if not (0<=ny<H and 0<=nx<W):
                continue
            if field[ny][nx] == '.' and reached[ny][nx] == -1:
                q.append([ny,nx])
                reached[ny][nx] = reached[y][x] + 1
    return -1
bk = 0
for x in field:
    for y in x:
        if y == '#':
            bk += 1
ans = bfs(0,0)
if ans==-1:
    print(-1)
else:
    print(H*W-ans-bk)

Submission status: Accepted

Solution code:
import sys
from collections import deque

import numpy as np

sys.setrecursionlimit(10000)
INF = float('inf')

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

# distances[h, w]: (h, w) に行くまでに通る '.' の数
distances = np.empty((H, W), dtype=int)
distances.fill(-1)
que = deque()


def valid(h, w):
    return 0 <= h < H and 0 <= w < W and S[h][w] == '.' and distances[h][w] == -1


# 普通に BFS して通らなかった道を # で埋める
distances[0][0] = 1
que.append((0, 0, H - 1, W - 1))
while len(que) > 0 and distances[-1, -1] == -1:
    sh, sw, eh, ew = que.popleft()
    if valid(sh + 1, sw):
        distances[sh + 1, sw] = distances[sh, sw] + 1
        que.append((sh + 1, sw, eh, ew))
    if valid(sh - 1, sw):
        distances[sh - 1, sw] = distances[sh, sw] + 1
        que.append((sh - 1, sw, eh, ew))
    if valid(sh, sw + 1):
        distances[sh, sw + 1] = distances[sh, sw] + 1
        que.append((sh, sw + 1, eh, ew))
    if valid(sh, sw - 1):
        distances[sh, sw - 1] = distances[sh, sw] + 1
        que.append((sh, sw - 1, eh, ew))

d = distances[-1, -1]
if d == -1:
    print(-1)
else:
    print(H * W - list(S.flat).count('#') - d)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
grid=[["#"]*(w+2)]+[list("#"+input()+"#") for x in range(h)]+[["#"]*(w+2)]
sx,sy=1,1
gx,gy=w,h
loc=[[sy,sx]]
ans=sum(i.count(".")for i in grid)
for c in range(h*w):
    next_loc=[]
    for y,x in loc:
        for i,j in([0,1],[1,0],[0,-1],[-1,0]):
            if grid[y+i][x+j]=='.':
                grid[y][x]=c+1
                grid[y+i][x+j]=c+2
                next_loc.append([y+i,x+j])
    loc=next_loc
    if [gy,gx] in loc:
        ans-=grid[gy][gx]
#        for i in grid:
#            print(*i)
        print(ans)
        exit()
print(-1)

Submission status: Accepted

Solution code:
R,C = map(int,input().split())
sy,sx = 2,2
gy,gx = R+1,C+1

maze = [["#"]*(C+2)]
white_count = 0
for i in range(R):
    temp = list(input())
    temp.insert(0,'#')
    temp.append('#')
    maze.append(temp)
    white_count += temp.count('.')
    
maze.append(["#"]*(C+2))
#print(maze)
vx = [0,1,0,-1]
vy = [1,0,-1,0]
Q = [[sy-1,sx-1,0]]

checked = [[sy-1,sx-1]]
while True:
   if len(Q) == 0:
       length = white_count+1
       break
   now = Q.pop(0)
   if now[0] == gy-1 and now[1] == gx-1:
       length = now[2]+1
       break
   for i in range(4):
       next_y = now[0]+vy[i]
       next_x = now[1]+vx[i]
       if not [next_y,next_x] in checked and maze[next_y][next_x] == '.':
           checked.append([next_y,next_x])
           Q.append([next_y,next_x,now[2]+1])      
print(white_count-length)

Submission status: Accepted

Solution code:
import heapq
class edge:
    def __init__(self,to,cost):
        self.to=to
        self.cost=cost

H,W=map(int,input().split())
G=[list() for i in range(H*W)]
s=[]
for j in range(H):
    s.extend(input())

for i in range(H):
    for j in range(W):
        if(j<W-1 and  s[W*i+j+1]=="."):
            G[W*i+j].append(edge(W*i+j+1,1))
        if(i<H-1 and  s[W*i+j+W]=="."):
            G[W*i+j].append(edge(W*i+j+W,1))
        if(j>0 and  s[W*i+j-1]=="."):
            G[W*i+j].append(edge(W*i+j-1,1))
        if(i>0 and  s[W*i+j-W]=="."):
            G[W*i+j].append(edge(W*i+j-W,1))
            
        
        
    

def dijkstra(o):
    d=[float('inf') for i in range(H*W)]
    d[o]=0
    hq=[]
    prev=[[] for i in range(H*W)]
    heapq.heappush(hq,(0,o))
    while hq:
        p=heapq.heappop(hq)
        v=p[1]
        if(d[v]<p[0]):
            continue
        for i in G[v]:
            if(d[i.to]>d[v]+i.cost):
                d[i.to]=d[v]+i.cost
                prev[i.to]=prev[v]+[str(sorted([v,i.to]))]
                heapq.heappush(hq,(d[i.to],i.to))
    return d,prev


ans=set()
for i in range(1):
    tmp=dijkstra(i)[0]
    if(tmp[H*W-1]==float('inf')):
        print(-1)
    else:
        #-1:start
        print(H*W-s.count('#')-1-tmp[H*W-1])

Submission status: Accepted

Solution code:
from queue import Queue

#入力
H, W = map(int, input().split())

#lst = [['a']*W for _ in range(H)]
count = 0 #白色のマスの総数
lst = []
row = []
for i in range(H):
    row = list(input())
    count += row.count('.')
    lst += [row]
 
#for i in range(H):
#    for j in range(W):
#        if lst[i][j] == '.':
#            count += 1

#sx, sy = 1, 1 #スタート位置
#gx, gy = H, W #ゴール位置

move = [[-1, 0], [1,0], [0, -1], [0, 1]]

def bfs():
    q = Queue()
    INF = 10 ** 9
    d = [[INF]* W for _ in range(H)]
    q.put(0)
    q.put(0)
    d[0][0] = 0

    while True:
        if q.empty():
            break
        else:
            px = q.get()
            py = q.get()
            if px == H-1 and py == W-1:
                break
            else:
                for dx, dy in move:
                    nx = px + dx
                    ny = py + dy

                    if 0 <= nx and nx < H and 0 <= ny and ny < W and lst[nx][ny] == '.' and d[nx][ny] == INF:
                        q.put(nx)
                        q.put(ny)
                        d[nx][ny] = d[px][py] + 1
    return d[H-1][W-1]

a = bfs()

if a == 10 **9:
    print (-1)
else:
    print (count - a - 1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[]
ans=0
white=0
for i in range(h):
    s.append(input())
    for j in s[-1]:
        if j==".":
            white+=1
    
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

ans=dfs(s)

if ans==-1:
    print(-1)
else:
    print(white-ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
import heapq
import copy
import itertools

inf = float('inf')
a = '.'
b = '#'

def solve(H, W, s):
    white_count = sum([line.count(a) for line in s])
    
    field = [[b for w in range(W+2)] for h in range(H+2)]
    for h in range(H):
        field[1+h][1:W+1] = s[h]

    D = {(h, w): inf for h, w in itertools.product(range(H+2), range(W+2))}
    start = (1, 1)
    D[start] = 1
    Q = [(D[start], start)]
    direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
    
    while len(Q) > 0:
        Du, u = heapq.heappop(Q)
        for d in direction:
            v = (u[0]+d[0], u[1]+d[1])
            if field[u[0]+d[0]][u[1]+d[1]] == b:
                continue
            if Du + 1 < D[v]:
                D[v] = Du + 1
                heapq.heappush(Q, (D[v], v))

    path_length = D[(H, W)]
    if path_length == inf:
        print(-1)
        return
    print(white_count - path_length)
    return

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    s = [[c for c in next(tokens)] for _ in range(H)]  # type: "List[str]"
    solve(H, W, s)
    pass

if __name__ == '__main__':
    main()

Submission status: Accepted

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


def bfs(startx: int, starty: int) -> set:
    dxdy = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    queue = deque()
    queue.appendleft((startx, starty, 0))
    reached = set()
    while queue:
        d = queue.pop()
        if d[0] == W - 1 and d[1] == H - 1:
            return d[2]
        for a in dxdy:
            x = d[0] + a[0]
            y = d[1] + a[1]
            if (x, y) not in reached and 0 <= x < W and 0 <= y < H and maze[y][x] != '#':
                reached.add((x, y))
                queue.appendleft((x, y, d[2] + 1))
    return -1


d = bfs(0, 0)
if d == -1:
    print(-1)
    exit()
cnt = 0
for c in maze:
    cnt += c.count('#')
print(H * W - cnt - d - 1)

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
s = ['#' * (W + 2)] + [('#' + input() + '#') for _ in range(H)] + ['#' * (W + 2)]
Q = deque()
Q.append((1, 1))
M = [[-1 for _ in range(W + 2)] for _ in range(H + 2)]
L = [[1, 0], [-1, 0], [0, -1], [0, 1]]
c = 0
for i in range(H + 1):
    for j in range(W + 1):
        if s[i][j] == '.':
            c += 1
M[1][1] = 1
while Q:
    y, x = Q.popleft()
    if y == H and x == W:
        print(c - M[H][W])
        exit()
    else:
        for i, j in L:
            if M[y + i][x + j] == -1 and s[y + i][x + j] == '.':
                Q.append((y + i, x + j))
                M[y + i][x + j] = M[y][x] + 1

print(-1)

Submission status: Accepted

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

total_white = 0
for i in s:
  total_white += i.count(".")

sh = 0
sw = 0
gh = H-1
gw = W-1

s[sh][sw] = 0
q = [[sh, sw]]
min_path = 0

while len(q) > 0:
  h, w = q.pop(0)
  if h == gh and w == gw:
    min_path = s[h][w]
    print(total_white - min_path -1)
    exit()
  for dh, dw in ([0, 1], [0, -1], [1, 0], [-1, 0]):
    if 0 <= h + dh < H and 0 <= w + dw < W:
      if s[h+dh][w+dw] == ".":
        s[h+dh][w+dw] = s[h][w] + 1
        q.append([h+dh, w+dw])

print(-1)

Submission status: Accepted

Solution code:
import sys

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

sys.setrecursionlimit(100000)

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1 and cost[y+1][x] == float('inf'):
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1 and cost[y-1][x] == float('inf'):
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1 and cost[y][x+1] == float('inf'):
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1 and cost[y][x-1] == float('inf'):
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Accepted

Solution code:
import sys

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

sys.setrecursionlimit(100000)

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Accepted

Solution code:
import sys

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

sys.setrecursionlimit(100000)

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(y,x):
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move(y+1,x)
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move(y-1,x)
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move(y,x+1)
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move(y,x-1)
  

move(1,1)

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Accepted

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

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

white = 0
black = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            white += 1
        else:
            black += 1
cnt = [[-1]*W for _ in range(H)]

def bfs():
    queue = deque([[0, 0]])
    cnt[0][0] = 0
    while queue:
        y, x = queue.popleft()
        for dy, dx in [[1,0], [-1,0], [0,1], [0,-1]]:
            if y+dy >= 0 and y+dy < H and x+dx >= 0 and x+dx < W:
                if cnt[y+dy][x+dx] == -1 and S[y+dy][x+dx] == ".":
                    cnt[y+dy][x+dx] = cnt[y][x] + 1
                    queue.append([y+dy,x+dx])

bfs()
if cnt[H-1][W-1] == -1:
    print("-1")
else:
    print(white-cnt[H-1][W-1]-1)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
s = [["#"]*(W+2)] + [["#"] + [c for c in input()] + ["#"] for _ in [0]*H] + [["#"]*(W+2)]
ans = sum([sum([int(c == ".") for c in row]) for row in s])
s[1][1] = 1
ij = [[1,1]]
d = [[0,1],[0,-1],[1,0],[-1,0]]
cnt = 0
while ij[cnt:]:
    i,j = ij[cnt]
    for di,dj in d:
        if s[i+di][j+dj] == ".":
            s[i+di][j+dj] = s[i][j] + 1
            ij.append([i+di,j+dj])
            if i+di == H and j+dj == W:
                break
    cnt += 1
if s[H][W] == ".":
    ans = -1
else:
    ans -= s[H][W]
print(ans)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import deque

def bfs(grid):
    h = len(grid)
    w = len(grid[0])
    
    dist = [[float('inf')]*w for _ in range(h)]
    
    que = deque([])
    que.append(((0,0), 1))
    dist[0][0] = 0
    
    drs = [-1,0,1,0]
    dcs = [0,-1,0,1]
    
    while que:
        (rcur, ccur), cost = que.popleft()
        if rcur == h-1 and ccur == w-1:
            return dist[h-1][w-1]
    
        for dr, dc in zip(drs, dcs):
            if not (0 <= rcur+dr < h and 0 <= ccur+dc < w):
                continue
            
            elif grid[rcur+dr][ccur+dc] == '#':
                continue
            
            elif dist[rcur+dr][ccur+dc] != float('inf'):
                continue
            
            dist[rcur+dr][ccur+dc] = cost + 1
            que.append(((rcur+dr, ccur+dc), cost+1))
            
    return -1
            

h,w = li()
grid = [lc() for _ in range(h)]

white = 0
for row in grid:
    for col in row:
        if col == '.':
            white += 1

route = bfs(grid)
print(-1 if route == -1 else white - route)

Submission status: Accepted

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

white = 0
for d in map:
    white += d.count('.')

memory = [(0,0)]
data = [[0] * W for _ in range(H)]
data[0][0] = 1
direction = [(0,1), (0,-1), (1,0), (-1,0)]
while True:
    if len(memory) == 0:
        print(-1)
        exit()
    x, y = memory.pop(0)
    for dx, dy in direction:

        if x + dx == H - 1 and y + dy == W-1:
            print(white - (data[x][y] + 1))
            exit()
        if 0 <= x + dx < H and 0 <= y + dy < W:
            if map[x+dx][y+dy] == '.' and data[x+dx][y+dy] == 0:
                data[x+dx][y+dy] = data[x][y] + 1
                memory.append((x+dx, y+dy))

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
MA = [list(input().strip()) for _ in range(H)]
VI = [[-1] * W for _ in range(H)]

kabe = 0
for i in range(H):
    kabe += MA[i].count("#")

from collections import deque


def bfs(ma, vi):
    Q = deque([(0,0)])
    sy, sx = (0,0)
    vi[sy][sx] = 0
    while True:
        if Q == deque([]):
            return -1
        q = Q.popleft()
        y, x = q
        if q == (H-1,W-1):
            return vi[y][x]
        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            nq = y + dy, x + dx
            ny, nx = nq
            if 0 <= ny < H and 0 <= nx < W and vi[ny][nx] == -1:
                if ma[ny][nx] == '.':
                    Q.append(nq)
                    vi[ny][nx] = vi[y][x] + 1


score = bfs(MA,VI)

if score != -1:
    print(H * W - kabe - score - 1)
else:
    print(-1)

Submission status: Accepted

Solution code:
INF=10*10
H,W=map(int, input().split())
s=[list(input()) for _ in range(H)]
wall=sum(map(lambda x: x.count("#"), s))
d=[[INF for _ in range(W)] for _ in range(H)]
def bfs(h, w, c):
	if d[h][w] <= c:
		return
	d[h][w] = c
	for dh,dw in [(0, -1), (-1, 0), (0, 1), (1, 0)]:
		if h+dh >= 0 and w+dw >= 0 and h+dh < H and w+dw < W and s[h+dh][w+dw] == ".":
			bfs(h+dh, w+dw, c+1)
bfs(0, 0, 1)
print(-1 if d[H-1][W-1] == INF else H*W - d[H-1][W-1] - wall)

Submission status: Accepted

Solution code:
import sys
from queue import Queue  # put/get


def parse(file):
    height, width = map(int, file.readline().split())
    maze = []
    for y in range(height):
        row = file.readline().strip()
        maze.append(row)

    return height, width, maze


def main(height, width, maze):
    traversed = [(0, 0)]
    queue = Queue()  # get/put

    queue.put((0, 0, 0))

    nwhite = 0
    for r in maze:
        nwhite += r.count('.')

    while not queue.empty():
        (y, x, count) = queue.get()

        if (y, x) == (height - 1, width - 1):
            return nwhite - count - 1
        for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):
            if ny >= height or nx >= width or ny < 0 or nx < 0:
                continue
            if (ny, nx) in traversed:
                continue
            if maze[ny][nx] == '.':
                queue.put((ny, nx, count + 1))
                traversed.append((ny, nx))
    return -1


if __name__ == '__main__':
    print(main(*parse(sys.stdin)))

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
grid = [[c == "." for c in input()] for i in range(h)]
q = deque()
q.append((0,0,1))
visited = set()
min_dist = 0
while q:
    y, x, d = q.popleft()
    # 訪問済み、黒マスならスキップ
    if (y,x) in visited or not grid[y][x]:
        continue
    visited.add((y,x))
    # 終了条件
    if y == h-1 and x == w-1:
        min_dist = d
        break

    for dy, dx in [[-1,0],[1,0],[0,1],[0,-1]]:
        yn = y + dy
        xn = x + dx
        if 0<=yn<h and 0<=xn<w:
            q.append((yn, xn, d+1))
if min_dist:
    white = sum(sum(i) for i in grid)
    #print(white, min_dist)
    print(white - min_dist)
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
Map = [list(-1 if s=='.' else -2 for s in input()) for _ in range(H)]
ttl=H*W*2
for i in range(H):
  ttl += sum(Map[i])

Map[0][0]=0
sy, sx = 0, 0
  
dq = deque()
dq.append([sy, sx])
d = [[1,0],[0,1],[-1,0],[0,-1]]

ans=-1
while(len(dq)>0):
  y, x = dq.popleft()
  cnt = Map[y][x]+1
  for i in range(4):
    ytmp, xtmp = y+d[i][0], x+d[i][1]
    if ytmp<0 or ytmp>=H or xtmp<0 or xtmp>=W:
      continue
    elif Map[ytmp][xtmp]==-1:
      Map[ytmp][xtmp]=cnt
      dq.append([ytmp, xtmp])
      if ytmp==H-1 and xtmp==W-1:
        ans=cnt
        dq.clear()
        break
if ans==-1:
  print(ans)
else:
  print(ttl-ans-1)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
cnt = [[-1] * w for _ in range(h)]

def bfs():
    queue = deque([[0, 0]])
    cnt[0][0] = 0
    while queue:
        i, j = queue.popleft()
        if [i, j] == [h - 1, w - 1]:
            return cnt[i][j]
        for di, dj in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            if (0 <= i + di < h and 0 <= j + dj < w and s[i + di][j + dj] == "." and cnt[i + di][j + dj] == -1):
                cnt[i + di][j + dj] = cnt[i][j] + 1
                queue.append([i + di, j + dj])

bfs()
ans = -1
if cnt[h - 1][w - 1] != -1:
    ans = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                ans += 1
    ans = ans - (cnt[h - 1][w - 1] + 1)
print(ans)

Submission status: Accepted

Solution code:
import collections

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

p = [[None] * w for _ in range(h)]
q = collections.deque()
reachable = False

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

while len(q) > 0:
    x, y = q.popleft()
    for dx, dy in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
        if x + dx == w - 1 and y + dy == h - 1:
            reachable = True
            break
        if 0 <= x + dx < w and 0 <= y + dy < h:
            if M[y + dy][x + dx] == '.':
                if p[y + dy][x + dx] is None:
                    p[y + dy][x + dx] = p[y][x] + 1
                    q.append((x + dx, y + dy))

    if reachable:
        print(sum(row.count('.') for row in M) - p[y][x] - 2)
        break
else:
    print(-1)