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:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h,w = LI()
s = [input() for _ in range(h)]
cnt = h*w-1
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            cnt -= 1

dx,dy = [1,0,-1,0],[0,1,0,-1]
que = deque()
que.append((0,0))
d = [[0]*w for _ in range(h)]
check = [[True]*w for _ in range(h)]
check[0][0] = False
while que:
    x,y = que.popleft()
    for i in range(4):
        nx,ny = x+dx[i], y+dy[i]
        if 0 <= nx < w and 0 <= ny < h:
            if check[ny][nx] and s[ny][nx] == '.':
                check[ny][nx] = False
                d[ny][nx] = d[y][x] + 1
                que.append((nx,ny))
if d[h-1][w-1] == 0:
    print(-1)
else:
    print(cnt-d[h-1][w-1])

Submission status: Accepted

Solution code:
from collections import deque

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

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

def bfs():
  m = [[float('inf')]*w for _ in range(h)]
  que = deque([])
  que.append([0,0])
  m[0][0] = 0
  
  while que:
    cur = que.popleft()
    #if cur[0] == h and cur[1] == w:
    #  break
    
    for i in range(4):
      nh = cur[0] + dh[i]
      nw = cur [1] + dw[i]
      
      if nh >= 0 and nh < h and nw >= 0 and nw < w and \
          m[nh][nw] == float('inf') and par[nh][nw] == '.':
        que.append([nh,nw])
        m[nh][nw] = m[cur[0]][cur[1]] + 1
        
  return m

m = bfs()

if m[h-1][w-1] == float('inf'):
  print(-1)
  exit()

cnt = 0
for i in range(h):
  for j in range(w):
    if par[i][j] == '.':
      cnt += 1

print(cnt - m[h-1][w-1] -1)

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(10 ** 6)
def input():
    return sys.stdin.readline()[:-1]
 
H,W=[int(i) for i in input().split()]
C=[input() for _ in range(H)]
C=[list(i) for i in C] 
 
ans = 10**9
 
visited_list = [[10**9]*W for _ in range(H)]
stack = deque([[0, 0, 0]])
visited_list[0][0] = 0
 
w_cnt=0
for c in C: w_cnt += c.count(".")
 
def dfs(town, visited_list, stack):
    global ans
    flag = 0
    while len(stack) > 0:
        h, w, cnt = stack.pop()
        if h == H-1 and w == W-1 and ans > cnt:
            ans = cnt
            flag = 1
            continue
        for j, k in ([1, 0], [0, 1], [-1, 0], [0, -1]):
            new_h, new_w = h+j, w+k
            if new_h < 0 or new_h >= H or new_w < 0 or new_w >= W:
                continue
            if  town[new_h][new_w] != "#" and visited_list[new_h][new_w] > cnt + 1:
                visited_list[new_h][new_w] = cnt + 1
                stack.append([new_h, new_w, cnt+1])
    if flag: 
        ans = w_cnt-(ans+1)
        return ans
    else: return -1
 
print(dfs(C, visited_list, stack))

Submission status: Accepted

Solution code:
import sys
from io import StringIO
import unittest
import queue


def resolve():
    # ★get input
    h, w = map(int, input().split())

    grid = [["" for i in range(w)] for j in range(h)]

    for i in range(h):
        line = input()
        for j in range(w):
            grid[i][j] = line[j:j+1]

    # ★exec
    # 最短経路を求める
    distance = [[-1 for i in range(w)] for j in range(h)]
    que = queue.Queue()

    # スタート地点の情報を設定
    que.put([0, 0])
    distance[0][0] = 0

    while not que.empty():

        now = que.get()

        # 上下左右のマスを確認
        for move_y, move_x in ((1, 0), (-1, 0), (0, 1), (0, -1)):

            # 迷路の範囲外なら何もしない
            target = [now[0] + move_y, now[1] + move_x]
            if not h > target[0] >= 0 or not w > target[1] >= 0:
                continue

            # 黒塗りされているなら何もしない
            if grid[target[0]][target[1]] == '#':
                continue

            # 距離が設定済みなら何もしない
            if not distance[target[0]][target[1]] == -1:
                continue

            # キューに追加
            que.put(target)

            # 最短距離を設定
            distance[target[0]][target[1]] = distance[now[0]][now[1]] + 1

    # 最短経路までの距離を取得
    shortest_distance = distance[h-1][w-1]
    # 到達不可能の場合、ここで終了
    if shortest_distance == -1:
        print("-1")
        return

    # 塗りつぶしできないマスの個数を取得
    # 初期値1(スタート地点は塗りつぶし不可能であるため
    not_repaint_count = 1
    # 最初黒で塗られているマスの数を加算
    for i in range(h):
        not_repaint_count += grid[i].count("#")

    # 最初白のマス - 最短経路 = 塗りつぶしできるマス数。
    a = len(grid) * len(grid[0]) - not_repaint_count - shortest_distance
    print(a)


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)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
a = ["#"]*(w+2)
maze = [a]
nsum = 0
for i in range(h):
  b = list(input())
  nsum += b.count(".")
  maze.append(["#"] + b + ["#"])
maze.append(a)
d = [[-1]*(w+2) for i in range(h+2)]  
def bfs(i, j):
  q = deque()
  q.append([i, j])
  d[i][j] = 0
  while q:
    p = q.popleft()
    if p[0] == h and p[1] == w:
      break
    for i, j in ([-1, 0], [0, -1], [1, 0], [0, 1]):
      np = [p[0]+i, p[1]+j]
      if maze[np[0]][np[1]] != "#" and d[np[0]][np[1]] == -1:
        q.append(np)
        d[np[0]][np[1]] = d[p[0]][p[1]] + 1
  if d[h][w] == -1:
    return -1
  if d[h][w] != -1:
    return nsum - d[h][w] - 1
print(bfs(1, 1))

Submission status: Accepted

Solution code:
from collections import deque
def gridbfs(grid,sy,sx):
    INF = 10**18
 
    gridy = len(grid)
    gridx = len(grid[0])
 
    dist = [[INF]*gridx for _ in range(gridy)]
    dist[sy][sx] = 0
    q = deque([(sy,sx)])
 
    while q:
        y,x = q.popleft()
        for dy,dx in [(-1,0),(1,0),(0,-1),(0,1)]:
            yy,xx = y+dy, x+dx
            if not (0 <= yy < gridy and 0 <= xx < gridx):
                continue
            if grid[yy][xx] == '#':
                continue
            if dist[yy][xx] != INF:
                continue
            dist[yy][xx] = dist[y][x] + 1
            q.append((yy,xx))
 
    return dist
 
H,W = map(int,input().split())
grid = [input() for i in range(H)]
d = gridbfs(grid,0,0)
b = 0
for h in range(H):
    for w in range(W):
        if grid[h][w] == '#':
            b += 1
 
print(max(H*W-b-d[H-1][W-1]-1,-1))

Submission status: Accepted

Solution code:
from collections import deque

def resolve():
    H, W = map(int, input().split())
    grid = [["#"]*(W+2) for _ in range(H+2)]
    cnt = 0
    for i in range(1,H+1):
        g = list(input())
        cnt += g.count(".")
        grid[i][1:-1] = g

    q = deque()
    q.append((1, 1))
    dxy = [(-1, 0), (0, 1), (1, 0), (0, -1)]
    visited = [[0] * (W + 2) for _ in range(H + 2)]
    visited[1][1] = 1

    while q:
        x, y = q.popleft()
        for dx, dy in dxy:
            nx = dx + x
            ny = dy + y
            if grid[ny][nx] == "." and visited[ny][nx] == 0:
                visited[ny][nx] += 1 + visited[y][x]
                q.append((nx, ny))
    if visited[H][W] > 0:
        ans = cnt - visited[H][W]
    else:
        ans = -1

    return print(ans)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
from queue import Queue

H, W = map(int, input().split())
field = [list(input()) for _ in range(H)]
dist = [[-1 for _ in range(W)] for __ in range(H)]
searched = [[False for _ in range(W)] for __ in range(H)]
bfq = Queue()

def search(x, y, d):
    if not (0 <= x < W and 0 <= y < H):
        return
    if searched[y][x]:
        return
    searched[y][x] = True
    if field[y][x] == '#':
        return
    dist[y][x] = d
    bfq.put([x, y, d])
    return

search(0, 0, 0)

while not (searched[H-1][W-1] or bfq.empty()):
    x, y, d = bfq.get()
    search(x-1, y, d+1)
    search(x+1, y, d+1)
    search(x, y-1, d+1)
    search(x, y+1, d+1)

walls = sum(list(map(lambda x: x.count('#'), field)))

print(W*H - walls - dist[H-1][W-1] - 1 if searched[H-1][W-1] else "-1")

Submission status: Accepted

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

from collections import deque

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

dist = [[0] * W for _ in range(H)]
dist[0][0] = 1 #マスの数なので、初期値は1
q = deque([(0, 0)])

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

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

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc088/tasks/abc088_d

from collections import deque

if __name__ == "__main__":
    H, W = list(map(int, input().split()))
    A = []
    A.append('#' * (W + 2))
    for i in range(H):
        A.append('#' + input() + '#')
    A.append('#' * (W + 2))

    # for row in A:
    #     print(row)

    queue = deque()
    queue.appendleft((1, 1, 1))
    checked = set()
    goal = (H, W)

    dist = -1
    while queue:
        i, j, d = queue.pop()
        if (i, j) in checked:
            continue
        checked.add((i, j))

        if (i, j) == goal:
            dist = d

        for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            ii = i + dx
            jj = j + dy
            if A[ii][jj] == '.':
                queue.appendleft((ii, jj, d+1))

    if dist == -1:
        result = -1
    else:
        white = sum([row.count('.') for row in A])
        result = white - dist
    print(result)

Submission status: Accepted

Solution code:
from collections import deque

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

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

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

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

Submission status: Accepted

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

# Number of white cells
white_cells = sum([s[h].count(".") for h in range(H)])

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

count_white = 0

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

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

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

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

Submission status: Accepted

Solution code:
from collections import deque
 
def bfs(maze, visited, sy, sx, gy, gx):
  queue = deque([[sy, sx]])
  visited[sy][sx] = 0
  while queue:
    y,x = queue.popleft()
    for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
      new_y, new_x = y+j, x+k
      if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1:
        #　移動回数の計算
        visited[new_y][new_x] = visited[y][x] + 1
        queue.append([new_y, new_x])
  return visited[gy][gx]

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

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

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

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

Submission status: Accepted

Solution code:
from collections import deque

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

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

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

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

Submission status: Accepted

Solution code:
import math
import string
import collections
from collections import Counter
from collections import deque


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


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


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


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


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

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

Submission status: Accepted

Solution code:

from collections import deque


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

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

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

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

    
submit()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(5000)

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



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

walker=[]
for row in range(H):
    walker.append([None]*W)
#print(walker)
walker[0][0]=0
func((0,0))
#print(walker)
if walker[H-1][W-1] != None:
    minimum=walker[H-1][W-1]

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

Submission status: Accepted

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

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

ans = 10**9

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

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

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

print(dfs(C, visited_list, stack))

Submission status: Accepted

Solution code:
from queue import Queue

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

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

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

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

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

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline

from collections import deque
import copy

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

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

h,w = myinput()

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

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

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

path = bfs(0,0)
# print(path)

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

Submission status: Accepted

Solution code:
from collections import deque
import sys

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

maze[0][0]=0

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

Submission status: Accepted

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

from collections import deque

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

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

    # (number of white) - (minimum path length)
    num_white = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                num_white += 1
    print(num_white - l)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

from collections import deque

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

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

    if res is None:
        print(-1)
        return

    # (number of white) - (minimum path length)
    num_white = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                num_white += 1
    print(num_white - res)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

stdin = sys.stdin

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

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

Submission status: Accepted

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


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


H, W = inpl()
S = ["#" + input().strip() + "#" for _ in range(H)]
S = ["#" * (W + 2)] + S + ["#" * (W + 2)]
sharp = sum(len(list(filter(lambda x: x == "#", s))) for s in S)
sharp -= 2 * H + (W + 2) * 2

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

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