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: Time Limit Exceeded

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

import queue

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] :
            dist[nx][ny] = dist[x][y] + 1
            q.put((nx,ny))

if dist[h-1][w-1] >= h*w :
    print(-1)
    exit(0)

# print(dist)

ans = h*w - dist[h-1][w-1]
for v in field:
    for c in v:
        if c == '#':
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())

#塗れる最大数
#すなわち、（すべての白）ー（最短経路距離）
g = [input() for _ in range(h)]
from collections import *
d = [[-1]*w for _ in range(h)]
d[0][0] = 0

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

while q:
    tx, ty = q.popleft()
    for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        nx, ny = tx + dx, ty + dy
        if 0 <= nx < h and 0 <= ny < w and g[nx][ny] == '.' and d[nx][ny] < 0:
            d[nx][ny] = d[tx][ty] + 1
            q.append((nx, ny))

if d[-1][-1] < 0:
    print(-1)
    exit()
else:
    print(sum([s.count('.') for s in g]) - d[-1][-1] - 1)

Submission status: Accepted

Solution code:
from collections import deque

def bfs(sy,sx):
  q = deque([[sy,sx]])
  d[sy][sx] = 0
  while q:
    y,x = q.popleft()
    for i,j in [(-1,0),(1,0),(0,-1),(0,1)]:
      dy,dx = y+i,x+j
      if dy < 0 or h <= dy: continue
      elif dx < 0 or w <= dx: continue
      elif s[dy][dx] == "#": continue
      elif d[dy][dx] != -1: continue
      d[dy][dx] = d[y][x]+1
      q.append([dy,dx])

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

if s[0][0] == "#" or s[h-1][w-1] == "#":
  print(-1)
  exit()

d = [[-1]*w for _ in range(h)]
bfs(0,0)
if d[h-1][w-1] == -1: print(-1)
else:
  t = 0
  for i in range(h): t += s[i].count("#")
  print(h*w-t-(d[h-1][w-1]+1))

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
num=[list(input()) for _ in range(h)]
seen=[[False]*w for _ in range(h)]
queue=deque()
queue.append([0,0])
ans=[[0]*w for _ in range(h)]
seen[0][0]=True
for i in range(h*w*100):
    if len(queue)==0:
        break
    cnt=queue.popleft()
    if num[max(0,cnt[0]-1)][cnt[1]]=="." and seen[max(0,cnt[0]-1)][cnt[1]]==False:
        queue.append([cnt[0]-1,cnt[1]])
        seen[max(0,cnt[0]-1)][cnt[1]]=True
        ans[max(0,cnt[0]-1)][cnt[1]]=ans[cnt[0]][cnt[1]]+1
    if num[min(h-1,cnt[0]+1)][cnt[1]]=="." and seen[min(h-1,cnt[0]+1)][cnt[1]]==False:
        queue.append([cnt[0]+1,cnt[1]])
        seen[min(h-1,cnt[0]+1)][cnt[1]]=True
        ans[min(h-1,cnt[0]+1)][cnt[1]]=ans[cnt[0]][cnt[1]]+1
    if num[cnt[0]][max(cnt[1]-1,0)]=="." and seen[cnt[0]][max(cnt[1]-1,0)]==False:
        queue.append([cnt[0],cnt[1]-1])
        seen[cnt[0]][max(cnt[1]-1,0)]=True
        ans[cnt[0]][max(cnt[1]-1,0)]=ans[cnt[0]][cnt[1]]+1
    if num[cnt[0]][min(w-1,cnt[1]+1)]=="." and seen[cnt[0]][min(w-1,cnt[1]+1)]==False:
        queue.append([cnt[0],cnt[1]+1])
        seen[cnt[0]][min(w-1,cnt[1]+1)]=True
        ans[cnt[0]][min(w-1,cnt[1]+1)]=ans[cnt[0]][cnt[1]]+1
if seen[-1][-1]==False:
    print(-1)
else:
    cnt3=0
    for i in range(h):
        cnt3+=num[i].count(".")
    print(cnt3-ans[-1][-1]-1)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
s = ['' for i in range(H)]
white = H*W
black = 0
for i in range(H):
    s[i] = input()
    black += s[i].count('#')
white -= black
direction = [[1,0],[0,1],[-1,0],[0,-1]]
q = [[0,0,0]]

mass = [[-1 for i in range(W)] for j in range(H)]
while len(q) > 0:
    tmp = [y,x,d] = q.pop(0)
    if mass[y][x] >= 0: 
        continue
    mass[y][x] = d
    for [dy,dx] in direction:
        ny = y + dy
        nx = x + dx
        if 0 <= ny and ny < H and 0 <= nx and nx < W:
            if s[ny][nx] == '#' or mass[ny][nx] >= 0:
                continue
            q.append([ny,nx,d+1])
# for i in mass:
#     print(i)
if mass[H-1][W-1] < 0:
    print(-1)
else:
    print(white - mass[H-1][W-1] - 1)

Submission status: Accepted

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


def solve(arr, count):
    next_arr = set()
    count += 1
    for a in arr:
        y, x = a[0], a[1]
        checked[y][x] = True
        if y == H-1 and x == W-1:
            return count
        if y < H-1:
            if not checked[y+1][x] and grid[y+1][x] == '.':
                next_arr.add((y+1, x))
        if 0 < y:
            if not checked[y-1][x] and grid[y-1][x] == '.':
                next_arr.add((y-1, x))
        if x < W-1:
            if not checked[y][x+1] and grid[y][x+1] == '.':
                next_arr.add((y, x+1))
        if 0 < x:
            if not checked[y][x-1] and grid[y][x-1] == '.':
                next_arr.add((y, x-1))
    if len(next_arr) == 0:
        return -1
    return solve(next_arr, count)


min_steps = solve([(0, 0)], 0)
if min_steps == -1:
    print(-1)
else:
    w_c = 0
    for i in grid:
        w_c += i.count('.')
    print(w_c - min_steps)

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import deque
h, w = list(map(int, input().split()))
s = [list(map(str, list(input()))) for i in range(h)]  # 文字列の二次元配列入力
cnt_sharp = 0
G = defaultdict(lambda: [])
vec = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            cnt_sharp += 1
        for dy, dx in vec:
            if 0 <= i+dy < h and 0 <= j+dx < w and s[i+dy][j+dx] == '.':
                G[(i+dy, j+dx)].append((i, j))
# G[v]: 頂点vに隣接する頂点list
dist = defaultdict(lambda: -1)
que = deque([(0, 0)])
dist[(0, 0)] = 1
while que:
    v = que.popleft()
    d = dist[v]
    for ww in G[v]:
        if dist[ww] > -1:
            continue
        dist[ww] = d + 1
        que.append(ww)
if dist[(h-1, w-1)] == -1:
    print(-1)
else:
    print(h*w-cnt_sharp-dist[(h-1, w-1)])

Submission status: Accepted

Solution code:
class Grid:
    def __init__(self, H, W, grid, road_wall=(".", "#"), destroy=False):
        self.road, self.wall = road_wall
        self.H = H
        self.W = W
        self.destroy = destroy
        self.grid = grid
        self.parent = [[(-1,-1)] * self.W for _ in range(self.H)]
        self.move = [(1, 0), (-1, 0), (0, 1), (0, -1)]     # 動ける場所の候補

    def bfs(self, start=(0,0), goal=-3, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if save:
            parent = self.parent
        else:
            parent = [[-1] * self.W for _ in range(self.H)]
        p, t = start, time
        parent[p[0]][p[1]] = -2
        next_set = deque([(p, t)])
        while next_set:
            p, t = next_set.popleft()
            h0, w0 = p
            for dh, dw in self.move:
                h, w = (h0 + dh, w0 + dw)
                if h < 0 or h >= self.H or w < 0 or w >= self.W:
                    continue
                if self.grid[h][w] == self.wall:         # 壁があったら進まない
                    continue
                if parent[h][w] != -1:
                    continue
                #### (debug code) ######
                # self.debug(start, goal, (h,w), t)
                ########################
                if (h,w) == goal:
                    return t + 1
                parent[h][w] = p
                next_set.append(((h, w), t + 1))
        return -1

    def connection_counter(self):
        """
        :return: 連結成分の個数。有効グラフではあまり意味がない。
        """
        cnt = 0
        self.parent = [[-1] * self.W for _ in range(self.H)]
        for h in range(self.H):
            for w in range(self.W):
                if self.parent[h][w] == -1:
                    cnt += 1
                    self.bfs(start=(h,w), save=True)
        return cnt

    def distance_list(self, start=(0,0), save=False):
        """
        :param start: スタート地点
        :return: スタート地点から各点への距離のリスト
        """
        dist = [[-1] * self.W for _ in range(self.H)]
        if save:
            parent = self.parent
        else:
            parent = [[-1] * self.W for _ in range(self.H)]
        p, t = start, 0
        parent[p[0]][p[1]] = -2
        dist[p[0]][p[1]] = 0
        next_set = deque([(p, t)])

        while next_set:
            p, t = next_set.popleft()
            h, w = p
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         # 壁があったら進まない
                    continue
                if parent[q[0]][q[1]] != -1:
                    continue
                dist[q[0]][q[1]] = t + 1
                parent[q[0]][q[1]] = p
                next_set.append((q, t + 1))
        return dist

    def most_distant_point(self, start=(0, 0), save=False):
        """
        :param start:
        :return: start 地点から最も遠い点を ((h,w), 距離) として出力
        """
        res = (start, 0)
        temp = 0
        dist = self.distance_list(start, save=save)
        for h in range(self.H):
            for w in range(self.W):
                if dist[h][w] > temp:
                    temp = dist[h][w]
                    res = ((h, w), temp)
        return res

    def diameter(self, start=(0,0), save=False):
        """
        :return:　木の直系（最も離れた二頂点間の距離）を返す
        """
        p = self.most_distant_point(start, save=False)
        res = self.most_distant_point(start=p[0], save=save)
        return res[1]

    def diameter2(self):
        """
        :return:　連結ではない時に、最大の直系を返す
        """
        res = 0
        for h in range(self.H):
            for w in range(self.W):
                if self.grid[h][w] == self.road and self.parent[h][w] == -1:
                    temp = self.diameter(start=(h, w), save=False)
                    if temp > res:
                        res = temp
        return res

    def dfs(self, start=(0, 0), goal=-3, time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: ゴール地点までの距離。存在しなければ -1。ループがある時は最短距離とは限らないため注意。
        """

        if save:
            parent = self.parent
        else:
            parent = [[-1] * self.W for _ in range(self.H)]
        move2 = [[marshal.loads(marshal.dumps(self.move)) for _ in range(self.W)] for _ in range(self.H)]

        p, t = start, time
        parent[p[0]][p[1]] = -2
        while True:
            if move2[p[0]][p[1]]:
                h, w = p
                dh, dw = move2[p[0]][p[1]].pop()
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         # 壁があったら進まない
                    continue
                if q == parent[p[0]][p[1]]:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if parent[q[0]][q[1]] != -1:
                    """ サイクルで同一点を訪れた時の処理 """
                    """"""""""""""""""""
                    continue
                #### (debug code) ######
                # self.debug(start, goal, q, t)
                # self.show_visited(start, goal, q, t, parent)
                ########################
                if q == goal:
                    """ ゴール時の処理"""
                    """"""""""""""""""""
                    return t + 1
                """ p から q への引継ぎ"""
                """"""""""""""""""""
                parent[q[0]][q[1]] = p
                p, t = q, t + 1
            else:
                if p == start and t == time:
                    break
                p_temp = p
                p, t = parent[p[0]][p[1]], t-1
                """ p から進める点がもう無い時の点 p における処理 """
                # parent[p_temp[0]][p_temp[1]] = -1
                # move2[p_temp[0]][p_temp[1]].extend(marshal.loads(marshal.dumps(self.move)))
                """"""""""""""""""""
                """ 点 p から親ノードに戻ってきた時の親ノードにおける処理 """
                """"""""""""""""""""
        return -1

    def dfs2(self, start=(0, 0), goal=-3, time=0):
        visited = [[-1] * self.W for _ in range(self.H)]
        p, t = start, time
        res = 0
        def rec(p, past_p, t, visited, res):
            h, w = p
            visited[p[0]][p[1]] = 1
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if grid[q[0]][q[1]] == self.wall:
                    continue
                if q == past_p:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if visited[q[0]][q[1]] == 1:
                    """ サイクルで同一点を訪れた時の処理 """
                    """"""""""""""""""""
                    continue
                """ (debug code) """
                # self.debug(start, goal, q, t)
                # self.show_visited(start, goal, q, t, visited)
                """"""""""""""""""""
                if q == goal:
                    """ ゴール時の処理"""
                    """"""""""""""""""""
                    return t+1
                res = max2(rec(q, p, t + 1, visited, res), t + 1)
            """ 帰り際の処置（壊した道を元に戻す等)"""
            # visited[p[0]][p[1]] = -1
            """"""""""""""""""""
            return res
        return rec(p, -1, t, visited, res)

    def debug(self, start, goal, p, t):
        player = p
        debug_grid = list(list(self.grid[h]) for h in range(self.H))
        if start != (None, None):
            debug_grid[start[0]][start[1]] = "S"
        if goal != -3:
            debug_grid[goal[0]][goal[1]] = "G"
        debug_grid[player[0]][player[1]] = "P"
        print("~~~~~~~~~ t = " + str(t + 1) + "  ~~~~~~~~")
        for debug_h in range(self.H):
            print("".join(str(debug_grid[debug_h][debug_w]) for debug_w in range(self.W)))

    def show_visited(self, start, goal, p, t, parent):
        player = p
        debug_grid = list(list(self.grid[h]) for h in range(self.H))
        for h in range(H):
            for w in range(W):
                if parent[h][w] != -1:
                    debug_grid[h][w] = "V"
        if start != (None, None):
            debug_grid[start[0]][start[1]] = "S"
        if goal != -3:
            debug_grid[goal[0]][goal[1]] = "G"
        debug_grid[player[0]][player[1]] = "P"
        print("~~~~~~~~~ t = " + str(t + 1) + "  ~~~~~~~~")
        for debug_h in range(self.H):
            print("".join(str(debug_grid[debug_h][debug_w]) for debug_w in range(self.W)))

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

from collections import deque
import sys
import marshal
input = sys.stdin.readline



road, wall = ".", "#"                         # (進行可能を意味する記号, 進行不可を意味する記号)

H, W = map(int,input().split())                # 左上は(h,w)=(0,0)、右下は(h,w)=(H-1,W-1)

grid = []
cnt = 0
for h in range(H):
    grid.append(input().rstrip())
    cnt += grid[-1].count(".")
start = (0,0)
goal = (H-1, W-1)

g = Grid(H, W, grid, (road, wall), destroy=False)
res = g.bfs(start, goal)
if res == -1:
    print(-1)
else:
    print(cnt - res - 1)

Submission status: Accepted

Solution code:
from collections import deque

def bfs(sy,sx):
  queue = deque([[sy,sx]])
  d[sy][sx] = 0
  while queue:
    y,x = queue.popleft()
    for i,j in [(-1,0),(1,0),(0,-1),(0,1)]:
      dy,dx = y+i,x+j
      if dy < 0 or h <= dy: continue
      elif dx < 0 or w <= dx: continue
      elif s[dy][dx] == "#": continue
      elif d[dy][dx] != -1: continue
      d[dy][dx] = d[y][x] + 1
      queue.append([dy,dx])

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

if s[0][0] == "#" or s[h-1][w-1] == "#":
  print(-1)
  exit()

d = [[-1]*w for _ in range(h)]
bfs(0,0)
if d[h-1][w-1] == -1: print(-1)
else:
  t = 0
  for i in s: t += i.count("#")
  print(h*w - t - d[h-1][w-1] -1)

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
s_l = [input() for _ in range(H)]
dist = [(-1, 0), (1, 0), (0, -1), (0, 1)]
results = [[0 for _ in range(W)] for _ in range(H)]
results[0][0] = 1

queue = deque()
queue.append((0, 0))

while queue:
    y, x = queue.popleft()
    if H - 1 == y and W - 1 == x:
        break
    for dy, dx in dist:
        ny = y + dy
        nx = x + dx
        if nx < 0 or nx >= W or ny < 0 or ny >= H:
            continue
        if s_l[ny][nx] != "#" and results[ny][nx] == 0:
            results[ny][nx] = results[y][x] + 1
            queue.append((ny, nx))

ans = 0
if results[H - 1][W - 1] == 0:
    ans = -1
else:
    ans = sum([s.count(".") for s in s_l]) - results[H - 1][W - 1]

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque


def IN_I(): return int(sys.stdin.readline().rstrip())
def IN_LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def IN_S(): return sys.stdin.readline().rstrip()
def IN_LS(): return list(sys.stdin.readline().rstrip().split())


H, W = IN_LI()
s = [IN_S() for _ in range(H)]

dh = [-1, 0, 1, 0]
dw = [0, -1, 0, 1]

dist = [[-1] * W for j in range(H)]
dist[0][0] = 0

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

while q:
    now = q.popleft()
    now_h = now[0]
    now_w = now[1]

    for i in range(4):
        next_h = now_h + dh[i]
        next_w = now_w + dw[i]

        if not (0 <= next_h < H and 0 <= next_w < W):
            continue
        if s[next_h][next_w] == '#':
            continue

        if dist[next_h][next_w] == -1:
            q.append([next_h, next_w])
            dist[next_h][next_w] = dist[now_h][now_w] + 1

if dist[-1][-1] == -1:
    print(-1)
    exit()

white = sum([i.count('.') for i in s])
ans = white - (dist[-1][-1] + 1)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque


def IN_I(): return int(sys.stdin.readline().rstrip())
def IN_LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def IN_S(): return sys.stdin.readline().rstrip()
def IN_LS(): return list(sys.stdin.readline().rstrip().split())


H, W = IN_LI()
s = [IN_S() for _ in range(H)]

dh = [-1, 0, 1, 0]
dw = [0, -1, 0, 1]

dist = [[-1] * W for j in range(H)]
dist[0][0] = 0

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

while q:
    now = q.popleft()
    now_h = now[0]
    now_w = now[1]

    for i in range(4):
        next_h = now_h + dh[i]
        next_w = now_w + dw[i]

        if not (0 <= next_h < H and 0 <= next_w < W):
            continue
        if s[next_h][next_w] == '#':
            continue

        if dist[next_h][next_w] == -1:
            q.append([next_h, next_w])
            dist[next_h][next_w] = dist[now_h][now_w] + 1

if dist[-1][-1] == -1:
    print(-1)
    exit()

black = sum([i.count('#') for i in s])
ans = (H * W - black) - (dist[-1][-1] + 1)
print(ans)

Submission status: Accepted

Solution code:
#
# abc088 d
#
import sys
from io import StringIO
import unittest
from collections import deque


class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """3 3
..#
# ..
..."""
        output = """2"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
....................................."""
        output = """209"""
        self.assertIO(input, output)


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

    F = [[-1]*W for _ in range(H)]

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

    Q = deque()
    Q.append([0, 0])
    F[0][0] = 1

    while Q:
        p = Q.popleft()
        x, y = p

        if x == W-1 and y == H-1:
            break

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= W or ny < 0 or ny >= H or S[ny][nx] == "#" or F[ny][nx] != -1:
                continue

            Q.append([nx, ny])
            F[ny][nx] = F[y][x] + 1

    if F[H-1][W-1] == -1:
        print(-1)
    else:
        NS = 0
        for s in S:
            NS += s.count("#")
        print(W*H-F[H-1][W-1]-NS)


if __name__ == "__main__":
    # unittest.main()
    resolve()

Submission status: Accepted

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:
      if len(kouho) == 0:
        return
      tmp = kouho.popleft()
      if not visited[tmp[0]][tmp[1]]:
        break
    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: Accepted

Solution code:
h, w = map(int, input().split())

matrix = [list('#' * (w + 2))]
count_sharp = 0
for _ in range(h):
    C = list(input())
    count_sharp += C.count('#')
    matrix.append(['#'] + C + ['#'])
matrix.append(list('#') * (w + 2))

B = [[] for _ in range(10000)]


for i in range(h+2):
    for j in range(w+2):
        if matrix[i][j] == '.':
            if matrix[i-1][j] == '.':
                B[100*i+j].append(100*(i-1) + j)
            if matrix[i][j-1] == '.':
                B[100*i+j].append(100*i + j - 1)
            if matrix[i][j+1] == '.':
                B[100*i+j].append(100*i + j + 1)
            if matrix[i+1][j] == '.':
                B[100*i+j].append(100*(i+1) + j)

# print(matrix)
def solver(matrix, h, w, count_):
    path = [10000000] * 10000
    depth = 0
    path[101] = 0
    reached = [101]
    stack = []
    stack.append(101)
    while len(stack) > 0:
        depth += 1
        for _ in range(len(stack)):
            val = stack.pop(0)
            for j in matrix[val]:
                if j not in set(reached):
                    path[j] = min(depth, path[j])
                    reached.append(j)
                    stack.append(j)

    if path[h*100 + w] == 10000000:
        print(-1)
    else:
        print(h * w - path[h*100+w] - 1 - count_)
solver(B, h, w, count_sharp)

Submission status: Accepted

Solution code:
from collections import deque


def main():
    H, W = map(int, input().split())
    field = [list(input().rstrip()) for _ in range(H)]

    black = 0

    for f in field:
        for s in f:
            if s == "#":
                black += 1

    dir_h = [0, 0, 1, -1]
    dir_w = [1, -1, 0, 0]

    print(H * W - black - bfs(H, W, field, dir_h, dir_w))


def bfs(H, W, field, dir_h, dir_w):
    q = deque([])
    seen = [[-1 for _ in range(W)] for _ in range(H)]

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

    while q:
        h, w = q.popleft()

        for dh, dw in zip(dir_h, dir_w):
            nh, nw = h + dh, w + dw

            if nh < 0 or nh >= H or nw < 0 or nw >= W:
                continue
            elif field[nh][nw] == "#":
                continue
            elif seen[nh][nw] != -1:
                continue

            seen[nh][nw] = seen[h][w] + 1
            q.append([nh, nw])

    if seen[H - 1][W - 1] == -1:
        print(-1)
        exit()

    return seen[H - 1][W - 1]


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

h, w = [int(i) - 1 for i in input().split()]
ans = 0
maze = []
for i in range(h + 1):
    s = list(input())
    maze.append(s)
    ans += s.count(".")

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

while pos:
    y, x, b = pos.popleft()
    for ny, nx in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        if y + ny == h and x + nx == w:
            print(ans - b - 2)
            exit()
        if 0 <= y + ny <= h and 0 <= x + nx <= w and maze[y + ny][x + nx] == ".":
            pos.append([y + ny, x + nx, b + 1])
            maze[y + ny][x + nx] = "#"
print(-1)

Submission status: Accepted

Solution code:
from collections import deque

h, w = [int(i) - 1 for i in input().split()]
ans = 0
maze = []
for i in range(h + 1):
    s = list(input())
    maze.append(s)
    ans += s.count(".")

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

while pos:
    y, x, b = pos.popleft()
    if y == h and x == w:
        print(ans - b - 1)
        exit()
    for ny, nx in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        if 0 <= y + ny <= h and 0 <= x + nx <= w and maze[y + ny][x + nx] == ".":
            pos.append([y + ny, x + nx, b + 1])
            maze[y + ny][x + nx] = "#"
print(-1)

Submission status: Accepted

Solution code:
#キューのクラス
class Queue:
    def __init__(self,data = []):
        self.data = data
    def enqueue(self,x):
        self.data.append(x)
        return self.data
    def dequeue(self):
        if len(self.data) == 0:
            return "Queue is Empty!"
        else:
            cell = self.data[0]
            del self.data[0]
            return self.data

H, W = map(int, input().split())
s = [list(input()) for i in range(H)]
#4近傍探索のために用意
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
#最小距離のリスト(Falseで初期化)
min_dis = [[False for i in range(W)] for j in range(H)]
min_dis[0][0] = 1#スタート位置を1にする(注意!!)
#キューのインスタンスQ作成
Q = Queue()
Q.enqueue([0, 0])
#キューの中身がなくなるまでループ
while Q.data:
    y = Q.data[0][0]
    x = Q.data[0][1]
    #4近傍探索
    for i, j in zip(dy, dx):
        if  (0 <= y + i < H) and  (0 <= x + j <W) and s[y + i][x + j] == ".":#（範囲内にあった場合）かつ（道だった場合）
            if min_dis[y+i][x+j] == False:#最小距離がFalseだった場合
                min_dis[y+i][x+j] = min_dis[y][x] + 1
                Q.enqueue([y+i, x+j])#値を更新したマスをQにプッシュ
    Q.dequeue()#探索し終わったマスをQからプル

if not min_dis[H-1][W-1]:
    print(-1)
    exit()

##マスをカウント
num_shap = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == "#":
            num_shap += 1
#スコア＝（全マス)-(#マス)-(gへの最短経路)
score = (H*W) - num_shap - (min_dis[H-1][W-1])
print(score)

Submission status: Accepted

Solution code:
from collections import deque

H, W = [int(x) for x in input().split()]
board = []
for _ in range(H):
    board.append(input())

white = sum([board[h].count('.') for h in range(H)])

dist = {(x, y):white + 1 for x in range(W) for y in range(H)}
q = deque([(0, 0)])
dist[(0, 0)] = 1
while q:
    x, y = q.popleft()
    for d in range(4):
        nx, ny = x + int(((1j)**d).real), y + int(((1j)**d).imag)
        if nx < 0 or W <= nx or ny < 0 or H <= ny:
            continue
        if board[ny][nx] == '#':
            continue
        if dist[(nx, ny)] <= white:
            continue
        dist[(nx, ny)] = dist[(x, y)] + 1
        q.append((nx, ny))

lenofpath = dist[(W - 1, H - 1)]
ans = white - lenofpath
print(ans)

Submission status: Accepted

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

def bfs():
	sx, sy = 0, 0
	gx, gy = H-1, W-1
	dx = [1, 0, -1, 0]
	dy = [0, 1, 0, -1]

	que=deque()
	que.append([sx, sy])
	visit=[[float("inf")]*W for _ in range(H)]
	visit[sx][sy]=1

	while que:
		x, y = que.popleft()
		for i in range(4):
			nx, ny = x+dx[i], y+dy[i]
			if 0<=nx and nx<H and 0<=ny and ny<W and visit[nx][ny]==float("inf") and C[nx][ny]!="#":
				que.append([nx,ny])
				visit[nx][ny]= visit[x][y]+1
	return visit[gx][gy]

black=0
white=0
for i in range(H):
	for j in range(W):
		if C[i][j]=="#":
			black+=1
		else:
			white+=1

temp=bfs()
if temp==float("inf"):
	print(-1)
else:
	ans=white-temp
	print(ans)