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:
# ABC088D - Grid Repainting
import sys
input = sys.stdin.readline

from collections import deque

def bfs() -> None:
    q = [(0, 0)]
    while q:
        x, y = q.pop(0)
        for dx, dy in dxy:
            nx, ny = x + dx, y + dy  # next x, y
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "." and dist[nx][ny] == 0:
                q.append((nx, ny))
                dist[nx][ny] = dist[x][y] + 1


def main():
    global H, W, S, dist, dxy
    H, W = tuple(map(int, input().split()))
    S = tuple(input().rstrip() for _ in range(H))
    dist = [[0] * W for _ in range(H)]  # distance from (0, 0) to (x, y)
    dist[0][0] = 1
    dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    bfs()
    white, x = sum(s.count(".") for s in S), dist[-1][-1]
    ans = white - x if x else -1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# ABC088D - Grid Repainting
import sys
input = sys.stdin.readline

from collections import deque

def bfs() -> None:
    q = [(0, 0)]
    while q:
        x, y = q.pop(0)
        for dx, dy in dxy:
            nx, ny = x + dx, y + dy  # next x, y
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "." and dist[nx][ny] == 0:
                q += [(nx, ny)]
                dist[nx][ny] = dist[x][y] + 1


def main():
    global H, W, S, dist, dxy
    H, W = tuple(map(int, input().split()))
    S = tuple(input().rstrip() for _ in range(H))
    dist = [[0] * W for _ in range(H)]  # distance from (0, 0) to (x, y)
    dist[0][0] = 1
    dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    bfs()
    white, x = sum(s.count(".") for s in S), dist[-1][-1]
    ans = white - x if x else -1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# ABC088D - Grid Repainting
import sys
input = sys.stdin.readline

from collections import deque

def bfs() -> None:
    q = deque([(0, 0)])
    while q:
        x, y = q.popleft()
        for dx, dy in dxy:
            nx, ny = x + dx, y + dy  # next x, y
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "." and dist[nx][ny] == 0:
                q += [(nx, ny)]
                dist[nx][ny] = dist[x][y] + 1


def main():
    global H, W, S, dist, dxy
    H, W = tuple(map(int, input().split()))
    S = tuple(input().rstrip() for _ in range(H))
    dist = [[0] * W for _ in range(H)]  # distance from (0, 0) to (x, y)
    dist[0][0] = 1
    dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    bfs()
    white, x = sum(s.count(".") for s in S), dist[-1][-1]
    ans = white - x if x else -1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# ABC088D - Grid Repainting
import sys
input = sys.stdin.readline

from collections import deque

def bfs() -> None:
    q = deque([(0, 0)])
    while q:
        x, y = q.popleft()
        for dx, dy in dxy:
            nx, ny = x + dx, y + dy  # next x, y
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] == "." and dist[nx][ny] == 0:
                q.append((nx, ny))
                dist[nx][ny] = dist[x][y] + 1


def main():
    global H, W, S, dist, dxy
    H, W = tuple(map(int, input().split()))
    S = tuple(input().rstrip() for _ in range(H))
    dist = [[0] * W for _ in range(H)]  # distance from (0, 0) to (x, y)
    dist[0][0] = 1
    dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    bfs()
    white, x = sum(s.count(".") for s in S), dist[-1][-1]
    ans = white - x if x else -1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def bfs(S,H,W):
    stk = [(0,0)]
    cnt = 0
    seen = set()
    while True:
        nxt = []
        while stk:
            h,w = stk.pop()
            if(not (0<=h<H and 0<=w<W) or S[h][w]=='#' or (h,w) in seen):
                continue
            elif(h==H-1 and w==W-1):
                break
            seen.add((h,w))
            li=[(1,0),(-1,0),(0,-1),(0,1)]
            for x,y in li:
                nxt.append((h+y,w+x))
        else:
            stk = nxt
            cnt += 1
            if(cnt>H*W+5):return -1
            continue
        break
    return cnt

H,W = [int(x) for x in input().split()]
S = [list(input()) for _ in range(H)]
wht = 0
for s in S:
    wht += s.count('.')
rt = bfs(S,H,W)
if(rt>=0):
    print(wht-(rt+1))
else:
    print(rt)

Submission status: Accepted

Solution code:
from collections import Counter
def main():
    H,W = map(int,input().split())
    s = [list(map(str,input())) for _ in range(H)]
    INF = 10**5
    maze_list = [[INF for _ in range(W)] for _ in range(H)]
    maze_list[0][0] = 0
    def item(array):
        return [item for sublist in array for item in sublist]

    counter = list(Counter(item(s)).items())
    num = 0
    for i in range(len(counter)):
        if counter[i][0] == ".":
            num = counter[i][1]
            break

    queue = []
    queue.insert(0,(0,0))
    while len(queue):
        x,y = queue.pop()
        if x == H-1 and y == W-1:
            break
        for i in range(4):
            nx,ny = x + [1,0,-1,0][i],y + [0,1,0,-1][i]
            if (0<=nx and nx<H and 0<=ny and ny<W and \
                s[nx][ny]!="#" and maze_list[nx][ny]==INF):
                queue.insert(0,(nx,ny))
                maze_list[nx][ny] = maze_list[x][y] + 1

    if maze_list[H-1][W-1] == INF:
        print(-1)
    else:
        print(num-maze_list[H-1][W-1]-1)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
grid = [list(input()) for _ in range(H)]
cnt = 0
INF = 10**4
dp = [[INF] * (W) for _ in range(H)]
dp[0][0] = 0
for i in range(H):
  for j in range(W):
    if grid[i][j] == '.':
      cnt += 1
dy = [1,0,-1,0]
dx = [0,1,0,-1]
que = deque([])
que.append((0, 0))
while len(que) > 0:
  cy, cx = que.popleft()
  if cy == H-1 and cx == W-1:
    break
  for i in range(4):
    ny, nx = cy+dy[i], cx+dx[i]
    if ny >= 0 and ny <= H-1 and nx >= 0 and nx <= W-1:
      if dp[ny][nx] == INF and grid[ny][nx] == '.':
        dp[ny][nx] = dp[cy][cx] + 1
        que.append((ny, nx))
if dp[H-1][W-1] == INF:
  print(-1)
else:
  print(cnt-dp[H-1][W-1]-1)

Submission status: Accepted

Solution code:
import queue
H, W = map(int, input().split())
numw = 0
S = []
for i in range(H):
  ss = input()
  numw += ss.count(".")
  S.append(ss)
#print(numw)
D = [[-1]*W for i in range(H)]
q = queue.Queue()
q.put((0, 0, 0))
D[0][0] = 0
while not(q.empty()):
  i, j, d = q.get()
  if j > 0 and S[i][j-1] == "." and D[i][j-1] < 0:
    D[i][j-1] = d+1
    q.put((i, j-1, d+1))
  if i > 0 and S[i-1][j] == "." and D[i-1][j] < 0:
    D[i-1][j] = d+1
    q.put((i-1, j, d+1))
  if j+1 < W and S[i][j+1] == "." and D[i][j+1] < 0:
    D[i][j+1] = d+1
    q.put((i, j+1, d+1))
  if i+1 < H and S[i+1][j] == "." and D[i+1][j] < 0:
    D[i+1][j] = d+1
    q.put((i+1, j, d+1))
#print(D)
if D[H-1][W-1] < 0:
  print(-1)
  exit()
r = numw-D[H-1][W-1]-1
print(r)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000000)
from collections import deque
def bfs(Y,X,count):
    # print("now",Y+1,X+1)
    # print(count,"手目")
    reached[Y][X]=True

    if Y==goalY and X==goalX:
        result=0
        for i in range(H):
            for j in range(W):
                if F[i][j]=="#":
                    result+=1
        print(H*W - result - count -1)
        exit()

    if Y < H-1 :
        if F[Y+1][X]=="." and reached[Y+1][X]==False:
            # print(Y+1+1,X+1,"を積みます")
            yQUE.appendleft(Y+1)
            xQUE.appendleft(X)
            cQUE.appendleft(count+1)
            reached[Y+1][X]=True
    if X < W-1 :
        if F[Y][X+1]=="." and reached[Y][X+1]==False:
            # print(Y+1,X+1+1,"を積みます")
            yQUE.appendleft(Y)
            xQUE.appendleft(X+1)
            cQUE.appendleft(count+1)
            reached[Y][X+1]=True
    if 0 < Y :
        if F[Y-1][X]=="." and reached[Y-1][X]==False:
            # print(Y-1+1,X+1,"を積みます")
            yQUE.appendleft(Y-1)
            xQUE.appendleft(X)
            cQUE.appendleft(count+1)
            reached[Y-1][X]=True
    if 0 < X :
        if F[Y][X-1]=="." and reached[Y][X-1]==False:
            # print(Y+1,X-1+1,"を積みます")
            yQUE.appendleft(Y)
            xQUE.appendleft(X-1)
            cQUE.appendleft(count+1)
            reached[Y][X-1]=True    
    try:
        bfs(yQUE.pop(),xQUE.pop(),cQUE.pop())
    except IndexError:
        print("-1")

H,W = map(int,input().split())
startY=0
startX=0
goalX=W-1
goalY=H-1
F = list(list(input()) for _ in range(H))
reached = [[False for i in range(W)] for i in range(H)]
count=0
xQUE =  deque(maxlen=1000000000)
yQUE =  deque(maxlen=1000000000)
cQUE =  deque()
bfs(startY,startX,count)

Submission status: Accepted

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

H,W=map(int,input().split())
G=[[""]*W for _ in range(H)]
road=0

# print("W,H",W,H)
for y in range(H):
    s=input()
    for x in range(W):
        G[y][x]=s[x]
        if s[x]==".":
            road+=1

# print("road",road)
def bfs(pos):
    todo=[pos]
    index=1
    dx,dy=[-1,1,0,0],[0,0,-1,1]
    depth=[[0]*W for _ in range(H)]
    while True:
        x,y=pos

        # print(pos)
        if pos==(W-1,H-1):
            # print(todo)
            return depth[y][x]

        for i in range(4):
            npos=(x+dx[i],y+dy[i])
            if 0<=npos[0]<W and 0<=npos[1]<H:
                if G[npos[1]][npos[0]]=="." and not npos in todo:
                    depth[npos[1]][npos[0]]=depth[y][x]+1
                    todo.append(npos)

        if index<len(todo):
            pos=todo[index]
            index+=1
        else:
            print(-1)
            exit()
            return


d=bfs((0,0))+1

print(road-d)

Submission status: Accepted

Solution code:
H, W = map(int,input().split())
s = []
black = 0
for i in range(H):
    tmp = list(input())
    s.append(tmp)
    for j in range(W):
        if tmp[j] == "#":
            black += 1
white = H*W - black
 
 
q = [(0,0,0)]
s[0][0] = "#"
while q:
    i, j, cnt = q.pop(0)
    for di, dj in [(1,0),(0,1),(-1,0),(0,-1)]:
        ni, nj = i+di, j+dj
        if ni == H-1 and nj == W-1:
            print(white-cnt-2)
            exit(0)
        elif 0 <= ni < H and 0 <= nj < W and s[ni][nj] == ".":
            s[ni][nj] = "#"
            q.append((ni,nj,cnt+1))
print(-1)

Submission status: Accepted

Solution code:
import numpy as np
import heapq as hp
 
H, W = map(int, input().split())
s = np.array([list(input()) for _ in range(H)])
s = np.pad(s, 1, "constant")
visited = np.zeros_like(s, dtype=np.bool)

dist = np.inf
 
h = []
hp.heappush(h, (0, 1, 1))
 
while h:
    d, x, y = hp.heappop(h)
    if x == H and y == W:
        dist = d
        break
    for dx, dy in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
        nx = x + dx
        ny = y + dy
        if s[nx, ny] == "." and not visited[nx, ny]:
            visited[nx, ny] = True
            hp.heappush(h, (d + 1, nx, ny))

if dist == np.inf:
    print(-1)
else:
    print((s == ".").sum() - dist - 1)

Submission status: Accepted

Solution code:
import numpy as np
import heapq as hp

H, W = map(int, input().split())
s = np.array([list(input()) for _ in range(H)])
s = np.pad(s, 1, "constant")
visited = np.zeros_like(s, dtype=np.bool)

dist = np.inf

h = []
hp.heappush(h, (0, 1, 1))

while h:
    d, x, y = hp.heappop(h)
    if x == H and y == W:
        dist = d
        break
    for dx, dy in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
        nx = x + dx
        ny = y + dy
        if s[nx, ny] == "." and not visited[nx, ny]:
            visited[nx, ny] = True
            hp.heappush(h, (d + 1, nx, ny))

if dist == np.inf:
    print(-1)
else:
    print((s == ".").sum() - dist - 1)

Submission status: Accepted

Solution code:
from collections import deque

def bfs():
    memo = [[float("inf")] * w for _ in range(h)]
    memo[0][0] = 0

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

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

    while que:
        p = que.popleft()

        if p == (h-1, w-1):
            break

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

            if 0 <= nx <= h-1 and 0 <= ny <= w-1 and maze[nx][ny] == "." and memo[nx][ny] == float("inf"):
                que.append((nx, ny))
                memo[nx][ny] = memo[p[0]][p[1]] + 1
    return memo[h-1][w-1]

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

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

root = bfs()
if root == float("inf"):
    print(-1)
else:
    print(h * w - root - black - 1)

Submission status: Accepted

Solution code:
def solve():
    s = read()
    result = think(s)
    write(result)


def read():
    h, w = read_int(2)
    s = []
    for y in range(h):
        s.append(list(read_line(w)))
    return s


def read_int(n):
    return list(map(int, read_line().split(' ')))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(s):
    w, h = get_area(s)
    gx, gy = w - 1, h - 1

    invalid = w * h
    white_tile_mark = '.'

    memo = bfs(s, w, h, white_tile_mark, invalid)

    if memo[gy][gx] == invalid:
        return -1

    shortest_path = get_shortest_path(memo, w, h, gx, gy)
    white_tiles = collect_tiles(s, white_tile_mark)
    score = 0

    for w in white_tiles:
        if w not in shortest_path:
            score += 1
    return score


def get_area(s):
    w = len(s[0])
    h = len(s)
    return w, h


def bfs(s, w, h, white_tile_mark, invalid):
    sx, sy = 0, 0

    memo = [[invalid for x in range(w)] for y in range(h)]
    queue = []
    queue.append([sx, sy, 0])

    next_steps = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    while queue:
        nx, ny, nd = queue.pop(0)
        if not (0 <= nx < w and 0 <= ny < h and s[ny][nx] == white_tile_mark and memo[ny][nx] > nd):
            continue
        memo[ny][nx] = nd

        for dx, dy in next_steps:
            queue.append([nx + dx, ny + dy, nd + 1])
    return memo


def get_shortest_path(memo, w, h, gx, gy):
    next_steps = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    shortest_path = []
    cx, cy = gx, gy

    while True:
        shortest_path.append([cx, cy])
        current_distance = memo[cy][cx]
        if current_distance == 0:
            break
        for dx, dy in next_steps:
            nx, ny = cx + dx, cy + dy
            if not (0 <= nx < w and 0 <= ny < h):
                continue
            if memo[ny][nx] == current_distance - 1:
                cx, cy = nx, ny
                break

    return shortest_path


def collect_tiles(s, mark):
    w, h = get_area(s)
    tiles = []
    for y in range(h):
        for x in range(w):
            if s[y][x] == mark:
                tiles.append([x, y])
    return tiles


def write(result):
    print(result)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
##############################

from collections import deque

H, W = map(int, input().split())
maze = [ ['.' for _ in range(W)] for _ in range(H) ]
num_white = 0

for y in range(H):
    X = list(input().rstrip())
    for x in range(W):
        maze[y][x] = X[x]
        if X[x] == '.':
            num_white += 1

#print(maze)
# print(num_white)

# 1) まずゴールへの最短距離を求める
# 2) 全体の白ますの数 - 1) が答え

distance = [ [-1 for _ in range(W)] for _ in range(H) ]
#print(distance)

def bfs(x, y):
    distance[y][x] = 0
    q = deque([(x, y)])

    while q:
        (x, y) = q.popleft()

        if y > 0 and maze[y-1][x] != '#' and distance[y-1][x] == -1:
            distance[y-1][x] = distance[y][x] + 1
            q.append( (x, y-1) )
        if y < H-1 and maze[y+1][x] != '#' and distance[y+1][x] == -1:
            distance[y+1][x] = distance[y][x] + 1
            q.append( (x, y+1) )
        if x > 0 and maze[y][x-1] != '#' and distance[y][x-1] == -1:
            distance[y][x-1] = distance[y][x] + 1
            q.append( (x-1, y) )
        if x < W-1 and maze[y][x+1] != '#' and distance[y][x+1] == -1:
            distance[y][x+1] = distance[y][x] + 1
            q.append( (x+1, y) )

bfs(0, 0)
nearest = distance[H-1][W-1]

# 到達できない
if nearest == -1:
    print(-1)
else:
    # -1 はスタート地点の分
    print (num_white - nearest - 1)

Submission status: Accepted

Solution code:
H, W = map(int,input().split())
s = []
black = 0
for i in range(H):
    tmp = list(input())
    s.append(tmp)
    for j in range(W):
        if tmp[j] == "#":
            black += 1
white = H*W - black


q = [(0,0,0)]
s[0][0] = "#"
while q:
    i, j, cnt = q.pop(0)
    for di, dj in [(1,0),(0,1),(-1,0),(0,-1)]:
        ni, nj = i+di, j+dj
        if ni == H-1 and nj == W-1:
            print(white-cnt-2)
            exit(0)
        elif 0 <= ni < H and 0 <= nj < W and s[ni][nj] == ".":
            s[ni][nj] = "#"
            q.append((ni,nj,cnt+1))
print(-1)

Submission status: Accepted

Solution code:
import sys
from collections import deque

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

Map = [[] for _ in range(H)]
reached = [[-1]*W for _ in range(H)]
route = [[False]*W for _ in range(H)]

q = deque()
check = False
b = 0
for y in range(H):
    for x in input():
        Map[y].append(x)
        if x=="#":
            b += 1

def BFS(x, y, pre):
    global check

    if x>=W or y>=H or x<0 or y<0 or Map[y][x]=="#" or reached[y][x]>=0:
        return

    reached[y][x] = pre + 1

    if x==(W-1) and y==(H-1):
        ans =H * W - reached[y][x] + 1 - b - 2
        print(ans)
        sys.exit()

    else:
        q.append((x + 1, y, pre + 1))
        q.append((x - 1, y, pre + 1))
        q.append((x, y + 1, pre + 1))
        q.append((x, y - 1, pre + 1))

q.append((0,0,-1))
while q:
    BFS(*q.popleft())
print(-1)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

#n,x = [int(i) for i in readline().split()]
#n = int(input())
h,w = [int(i) for i in readline().split()]
b = [readline().strip() for _ in range(h)]

sx,sy = 0,0
gx,gy = h-1,w-1

dx4=[0, 1, 0,-1]
dy4=[1, 0,-1, 0]
#dx8=[0, 1, 0,-1,1,-1,1,-1]
#dy8=[1, 0,-1, 0,1,1,-1,-1]

from collections import deque 
#############################################################################
#   初期設定
#############################################################################
#memo: 負なら未確認、0以上なら最短距離
memo = [[-1]*w for _ in range(h)]
q = deque()
#初期状態をキューに入れる-----------------------------------------------------
#キューに入れる時点で使用したかどうかのmemoを更新-----------------------------
q.append((sx,sy)) #初期状態をキューに入れる
memo[sx][sy] = 0 #初期状態を訪問済みにする
""" "S,G"表記の場合
for i in range(h):
    for j in range(w):
        if b[i][j] == "S": 
            q.append((sx,sy)) #初期状態をキューに入れる
            memo[sx][sy] = 0 #初期状態を訪問済みにする
        if b[i][j] == "G":
            gx,gy = i,j
"""
#############################################################################
#   BFS
#############################################################################
while q: #キューが空になるまで
    x,y = q.popleft() #キューから情報を取り出す
    #(x,y)の各隣に対して処理-------------------------------------
    for i in range(4):
        nx = x + dx4[i]
        ny = y + dy4[i]
        #範囲外ならスキップ---------------------------------------------------
        if nx < 0 or nx>=h or ny <0 or ny>=w: continue
        #壁ならスキップ-------------------------------------------------------
        if b[nx][ny] == "#": continue
        #(nx,ny)が確認済みならスキップ----------------------------------------
        if memo[nx][ny] >= 0: continue
        #(nx,ny)が未確認のとき、確認済みにしてキューに入れる------------------
        memo[nx][ny] = memo[x][y]+1
        q.append((nx,ny))


res = 1+memo[gx][gy]

if res == 0:
    print(-1)
    exit()

for i in range(h):
    for j in range(w):
        if b[i][j] == ".": res -= 1

print(-res)

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
padding = ['#' for _ in range(W + 2)]
Map = tuple([padding])
Map += tuple(['#'] + list(input()) + ['#'] for _ in range(H))
Map += tuple([padding])
dxy = [(1, 0), (-1, 0), (0, 1), (0, -1)]

done = [[-1 for _ in range(W + 2)] for _ in range(H + 2)]

q = deque()
push, pop = q.append, q.popleft
push((1, 1))
done[1][1] = 0
while q:
  y, x = pop()
  for dy, dx in dxy:
    if Map[y + dy][x + dx] == '.' and done[y + dy][x + dx] == -1:
      push((y + dy, x + dx))
      done[y + dy][x + dx] = done[y][x] + 1
  if done[H][W] != -1:
    break
    
cnt = 0
for i in range(1, H + 1):
  for j in range(1, W + 1):
    if Map[i][j] == '.':
      cnt += 1
ans = cnt - done[H][W] -1

print(ans if done[H][W] != -1 else -1)

Submission status: Accepted

Solution code:
import sys
from collections import deque
INPUT = lambda: sys.stdin.readline().rstrip()
MAP = lambda: map(int, INPUT().split())
sys.setrecursionlimit(10 ** 9)


def main():
    H, W = MAP()
    dungeon = []
    walls = 0

    for _ in range(H):
        line = [0 if i == "." else 1 for i in INPUT()]
        walls += line.count(1)
        dungeon.extend([line])

    queue = deque([(0, 0, 1)])
    while queue:
        y, x, cnt = queue.popleft()
        if y == H-1 and x == W-1:
            print(H*W - walls - cnt)
            exit()
        for row, col in [(y, x-1), (y-1, x), (y, x+1), (y+1, x)]:
            if 0 <= row < H and 0 <= col < W and not dungeon[row][col]:
                dungeon[row][col] = 2
                queue.append((row, col, cnt+1))

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import queue

INF = 10000000

h, w = map(int, input().split())

d = [[INF for i in range(w)] for i in range(h)]

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

sy = 0
sx = 0
gy = h - 1
gx = w - 1

map = [[] for i in range(h)]
for i in range(h):
    map[i] = input()

# BFS: Breadth-First Search
que = queue.Queue()
que.put([sy,sx])
d[sy][sx] = 0

while not que.empty():
    p = que.get()
    if p[0] == gy and p[1] == gx:
        break
    for i in range(4):
        ny = p[0] + dy[i]
        nx = p[1] + dx[i]
        if nx<w and nx>=0 and ny<h and ny>=0 and map[ny][nx]!="#" \
            and d[ny][nx]==INF:
            d[ny][nx] = d[p[0]][p[1]] + 1
            que.put([ny, nx])

if d[gy][gx] == INF:
    print(-1)
else:
    count = 0
    for i in range(h):
        for j in range(w):
            if map[i][j] == ".":
                count += 1
    print(count - d[gy][gx] - 1)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
b = 0
l = [0]*h
for k in range(h):
  a = str(input())
  for k_ in range(w):
    if a[k_] == '#':
      b += 1
  l[k] = a
#l = [str(input()) for _ in range(h)]
 
from collections import deque
 
queue = deque()
visit = [[-1]*w for _ in range(h)]
queue.append([0, 0])
visit[0][0] = 1
 
while queue:
  y, x = queue.popleft()
  if y == h-1 and x == w-1:
    print(h*w-visit[y][x]-b)
    exit()
  for i, j in ([-1, 0], [1, 0], [0, 1], [0, -1]):
    new_y, new_x = y+i, x+j
    if (new_x>=0) and (new_x<w) and (new_y>=0) and (new_y<h) and l[new_y][new_x]=='.' and visit[new_y][new_x] == -1:
      visit[new_y][new_x] = visit[y][x]+1
      queue.append([new_y,new_x])
    else:
      continue
else:
  print('-1')

Submission status: Accepted

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

INF = 10**9
H,W = map(int,input().split())
G = [input() for _ in range(H)]
C = 0
for l in G:
    C += l.count("#")

def BFS(start,end,grid):
    queue = deque([])
    visited = []
    start += [1]
    dist = INF
    queue.append(start)
    while queue:
        label = queue.popleft()
        x = label[0]
        y = label[1]
        d = label[2]
        pos = [x,y]
        if pos == end:
            if d < dist:
                dist = d
        elif pos not in visited:
            visited.append(pos)
            if x+1 <= W-1:
                if [x+1,y] not in visited:
                    if grid[y][x+1] == ".":
                        queue.append([x+1,y,d+1])
            if x-1 >= 0:
                if [x-1,y] not in visited:
                    if grid[y][x-1] == ".":
                        queue.append([x-1,y,d+1])
            if y+1 <= H-1:
                if [x,y+1] not in visited:
                    if grid[y+1][x] == ".":
                        queue.append([x,y+1,d+1])
            if y-1 >= 0:
                if [x,y-1] not in visited:
                    if grid[y-1][x] == ".":
                        queue.append([x,y-1,d+1])
    return dist
res = BFS([0,0],[W-1,H-1],G)
if res == INF:
    print(-1)
else:
    print(H*W-res-C)

Submission status: Accepted

Solution code:
from collections import deque

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
H, W = map(int, input().split())
field = [input() for _ in range(H)]

dist = [[-1] * W for _ in range(H)]
que = deque()
que.append((0, 0))
dist[0][0] = 0

while len(que) > 0:
  y, x = que.popleft()
  for i in range(4):
    ny, nx = y + dy[i], x + dx[i]
    if nx < 0 or nx >= W or ny < 0 or ny >= H:
      continue
    if field[ny][nx] == '#':
      continue
    if dist[ny][nx] != -1:
      continue
    dist[ny][nx] = dist[y][x] + 1
    que.append((ny, nx))
    
count = sum([f.count('#') for f in field])
      
if dist[H - 1][W - 1] != -1:
  print(H * W - count - dist[H - 1][W - 1] - 1)
else:
  print(-1)

Submission status: Accepted

Solution code:
import queue

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
H, W = map(int, input().split())
field = [input() for _ in range(H)]

dist = [[-1] * W for _ in range(H)]
que = queue.Queue()
que.put((0, 0))
dist[0][0] = 0

while not que.empty():
  y, x = que.get()
  for i in range(4):
    ny, nx = y + dy[i], x + dx[i]
    if nx < 0 or nx >= W or ny < 0 or ny >= H:
      continue
    if field[ny][nx] == '#':
      continue
    if dist[ny][nx] != -1:
      continue
    dist[ny][nx] = dist[y][x] + 1
    que.put((ny, nx))
    
count = sum([f.count('#') for f in field])
      
if dist[H - 1][W - 1] != -1:
  print(H * W - count - dist[H - 1][W - 1] - 1)
else:
  print(-1)

Submission status: Accepted

Solution code:
import queue

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
H, W = map(int, input().split())
field = [input() for _ in range(H)]

dist = [[-1] * W for _ in range(H)]
que = queue.Queue()
que.put((0, 0))
dist[0][0] = 0

while not que.empty():
  y, x = que.get()
  for i in range(4):
    ny, nx = y + dy[i], x + dx[i]
    if nx < 0 or nx >= W or ny < 0 or ny >= H:
      continue
    if field[ny][nx] == '#':
      continue
    if dist[ny][nx] != -1:
      continue
    dist[ny][nx] = dist[y][x] + 1
    que.put((ny, nx))
    
count = 0
for y in range(H):
  for x in range(W):
    if field[y][x] == '#':
      count += 1
      
if dist[H - 1][W - 1] != -1:
  print(H * W - count - dist[H - 1][W - 1] - 1)
else:
  print(-1)

Submission status: Accepted

Solution code:
from collections import deque

dd = [[1, 0], [-1, 0], [0, 1], [0, -1]]
H, W = list(map(int, input().split()))
field = [input() for _ in range(H)]
def bfs():
  dist = [[float('inf')] * W for _ in range(H)]
  que = deque()
  que.append((0, 0))
  dist[0][0] = 0
  while len(que) > 0:
    y, x = que.popleft()
    if y == H - 1 and x == W - 1:
      break
    for dx, dy in dd:
      ny, nx = y + dy, x + dx
      if 0<=nx<W and 0<=ny<H and field[ny][nx]=='.' and dist[ny][nx]==float('inf'):
        dist[ny][nx] = dist[y][x] + 1
        que.append((ny, nx))
  return dist[H - 1][W - 1]
    
count = sum([f.count('#') for f in field])
need = bfs()
      
if need == float('inf'):
  print(-1)
else:
  print(H * W - count - need - 1)

Submission status: Accepted

Solution code:
from collections import deque

R,C = list(map(int,input().split()))
Sx,Sy = 0,0
Gx,Gy = R-1,C-1
Mize = [input() for _ in range(R)]
dd = [[1, 0], [-1, 0], [0, 1], [0, -1]]

def bfs():
    d = [[float('inf')] * C for i in range(R)]
    q = deque([])
    d[Sx][Sy] = 0
    q.append((Sx,Sy))
    while(len(q) != 0):
        x,y = q.popleft()
        if x == Gx and y == Gy:
            break
        for dx,dy in dd:
            
            if -1<x+dx<R and -1<y+dy<C and Mize[x+dx][y+dy]=='.' and d[x+dx][y+dy] == float('inf'):
                q.append([x+dx,y+dy])
                d[x+dx][y+dy] = d[x][y] + 1
    return d[Gx][Gy]

white = sum([m.count('#') for m in Mize])
need = bfs()
if need == float('inf'):
    print(-1)
else:
    print(R*C-white-need-1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(3000)
import queue
h,w=map(int,input().split())
s=['#'*(w+2)]+['#'+input()+'#' for _ in [0]*h]+['#'*(w+2)]
l=[[0]*(w+2) for _ in [0]*(h+2)]
for i in range(h+2):
    for j in range(w+2):
        if s[i][j]=='#':
            l[i][j]=-1
L=queue.Queue()
L.put([1,1])
while not L.empty():
    n=L.get()
    for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
        if l[n[0]+dx][n[1]+dy]==0 and [n[0]+dx,n[1]+dy]!=[1,1]:
            l[n[0]+dx][n[1]+dy]=l[n[0]][n[1]]+1
            L.put([n[0]+dx,n[1]+dy])

if l[h][w]==0:print(-1)
else:print(h*w-l[h][w]-(sum(x.count('#') for x in s)-2*h-2*w-4)-1)