Problem:


Score: 400 points

Problem statement

We have an H \times W grid whose squares are painted black or white. The square at the i-th row from the top and the j-th column from the left is denoted as (i, j).

Snuke would like to play the following game on this grid. At the beginning of the game, there is a character called Kenus at square (1, 1). The player repeatedly moves Kenus up, down, left or right by one square. The game is completed when Kenus reaches square (H, W) passing only white squares.

Before Snuke starts the game, he can change the color of some of the white squares to black. However, he cannot change the color of square (1, 1) and (H, W). Also, changes of color must all be carried out before the beginning of the game.

When the game is completed, Snuke's score will be the number of times he changed the color of a square before the beginning of the game. Find the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed, that is, Kenus can never reach square (H, W) regardless of how Snuke changes the color of the squares.  

The color of the squares are given to you as characters s_{i, j}. If square (i, j) is initially painted by white, s_{i, j} is .; if square (i, j) is initially painted by black, s_{i, j} is #.

Constraints

H is an integer between 2 and 50 (inclusive).

W is an integer between 2 and 50 (inclusive).

s_{i, j} is . or # (1 \leq i \leq H, 1 \leq j \leq W).

s_{1, 1} and s_{H, W} are ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2, 1}s_{2, 2}s_{2, 3} ... s_{2, W}
 :   :
s_{H, 1}s_{H, 2}s_{H, 3} ... s_{H, W}

Output

Print the maximum possible score that Snuke can achieve, or print -1 if the game cannot be completed.

Sample Input 1

3 3
..#
#..
...

Sample Output 1

2

The score 2 can be achieved by changing the color of squares as follows:

Sample Input 2

10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Sample Output 2

209



Sample input:
3 3
..#
#..
...


Sample output:
2

Submission status: Accepted

Solution code:
# 経路復元

from collections import deque
from sys import setrecursionlimit

setrecursionlimit(10 ** 9)

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

field = [list(input()) for i in range(H)]

queue = deque([])
seen = [[0] * W for i in range(H)]
prev_x = [[0] * W for i in range(H)]
prev_y = [[0] * W for i in range(H)]
direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]


def bfs(y, x):
    queue.append([y, x])
    seen[y][x] = 1
    prev_x[y][x] = -1
    prev_y[y][x] = -1

    while len(queue) != 0:
        y, x = queue.popleft()

        for dy, dx in direction:
            next_x = x + dx
            next_y = y + dy

            if next_x < 0 or next_x >= W or next_y < 0 or next_y >= H:
                continue
            elif field[next_y][next_x] == "#":
                continue
            elif seen[next_y][next_x] != 0:
                continue
            else:
                seen[next_y][next_x] = 1
                prev_x[next_y][next_x] = x
                prev_y[next_y][next_x] = y
                queue.append([next_y, next_x])


shortest_path = [[0] * W for i in range(H)]


def path_restoration(y, x):
    shortest_path[y][x] = 1

    if prev_x[y][x] == -1 and prev_y[y][x] == -1:
        return
    else:
        next_y = prev_y[y][x]
        next_x = prev_x[y][x]
        path_restoration(next_y, next_x)


bfs(0, 0)
path_restoration(H - 1, W - 1)

ans = 0

for i in range(H):
    for j in range(W):
        if field[i][j] == "." and shortest_path[i][j] == 0:
            field[i][j] = "#"
            ans += 1

if seen[H - 1][W - 1] == 0:
    # たどりつけない場合
    print(-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

A, B = [-1, 0, 0, 1], [0, -1, 1, 0]


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

GRID = []
black = 0
for _ in range(h):
    s = input()
    black += s.count("#")
    GRID.append("#" + s + "#")
GRID = ["#" * (w + 2)] + GRID + ["#" * (w + 2)]


DISTANCE = [[0] * (w + 2) for _ in range(h + 2)]

DISTANCE[1][1] = 1
QUEUE = deque([(1, 1)])
while QUEUE:
    i, j = QUEUE.popleft()
    for a, b in zip(A, B):
        if GRID[i + a][j + b] == "#":
            continue
        if DISTANCE[i + a][j + b] != 0:
            continue
        DISTANCE[i + a][j + b] = DISTANCE[i][j] + 1
        QUEUE.append((i + a, j + b))


if DISTANCE[h][w] == 0:
    print(-1)
else:
    print(h * w - DISTANCE[h][w] - black)

Submission status: Accepted

Solution code:
def bfs(queue, visited):
  while len(queue) > 0:
    y, x = queue.pop(0)
    for delta_y, delta_x in [[1,0],[-1,0],[0,1],[0,-1]]:
      new_y , new_x = y + delta_y, x + delta_x 
      if new_y < 0 or new_x < 0 or new_y >= h or new_x >= w:
        continue 
      if c[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


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

cnt = 0
for tate in c:
    for yoko in tate:
        if yoko == ".":
            cnt +=1

visited = [[-1]*w for _ in range(h)]
queue = []
sy, sx = 0, 0
visited[sy][sx] = 0 
queue.append([sy,sx])
visited = bfs(queue, visited)

if visited[h-1][w-1] == -1:
    print(-1)
else:
    print(cnt-visited[h-1][w-1]-1)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
maze = [list(input()) for _ in range(h)]
visited = [[-1] * w for _ in range(h)]
move = [(1,0), (0,1), (-1,0), (0,-1)]

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

queue = deque([(sy, sx, 0)])

while queue:
    y, x, dist = queue.popleft()
    for dy, dx in move:
        if maze[y+dy:y+dy+1] and maze[y+dy][x+dx:x+dx+1]:
            if maze[y+dy][x+dx] == "." and visited[y+dy][x+dx] == -1:
                visited[y+dy][x+dx] = dist + 1
                queue.append((y+dy, x+dx, dist+1))
shortest_distance = visited[gy][gx]

if shortest_distance == -1:
    print("-1")
else:
    white_count = 0
    for row in maze:
        for cell in row:
            if cell == ".":
                white_count += 1

    score = white_count - 1 - shortest_distance
    print(score)

Submission status: Accepted

Solution code:
def main():
    height, width = map(int, input().split())
    grid = []
    initial_white = 0
    for _ in range(height):
        g = input()
        initial_white += g.count(".")
        grid.append(list(g))
    count = [[0 for _ in range(width)] for _ in range(height)]
    next_search = [(0, 0)]
    grid[0][0] = "#"
    while not next_search == []:
        now = next_search.pop(0)
        for d in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            next_index = (now[0] + d[0], now[1] + d[1])
            if next_index[0] < 0 or height <= next_index[0] or next_index[1] < 0 or width <= next_index[1]:
                continue
            elif grid[next_index[0]][next_index[1]] == ".":
                grid[next_index[0]][next_index[1]] = "#"
                count[next_index[0]][next_index[1]] = count[now[0]][now[1]] + 1
                next_search.append(next_index)
    print(initial_white - count[-1][-1] - 1 if count[-1][-1] > 0 else -1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
field = []
ans = 0
white = 0
for i in range(h):
    t = list(input())
    white += t.count(".")
    field.append(t)

next_point = []
next_point_cand = []

start = (0, 0)
d = [(0, 1), (0, -1), (1, 0), (-1, 0)]
count = 1 
next_point.append(start)
field[0][0] = 0

while True:
    for (y, x) in next_point:
        for (dy, dx) in d:
            if 0 <= (x + dx) <= (w - 1) and 0 <= (y + dy) <= (h - 1):
                if field[y + dy][x + dx] == ".":
                    field[y + dy][x + dx] = count
                    next_point_cand.append((y + dy, x + dx))
    next_point.clear()
    next_point.extend(next_point_cand)
    next_point_cand.clear()
    count += 1

    if len(next_point) == 0:
        ans = -1
        break

    if (h - 1, w - 1) in next_point:
       ans = count 
       break


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

else:
    print(white - count)

Submission status: Accepted

Solution code:
H,W=map(int, input().split())
S=[]
S.append(list(['X']*(W+2)))
for h in range(H):
    S.append(['X']+list(input())+['X'])
S.append(list(['X']*(W+2)))

from collections import deque
q=deque([[1,1]])
d=[(1,0),(-1,0),(0,1),(0,-1)]
S[1][1]=0

cnt_nm=0
for h in range(H+2):
    for w in range(W+2):
        if S[h][w]=='#':
            cnt_nm+=1

while q:
    y,x = q.popleft()
#     S[y][x]='X'
    for dy,dx in d:
        if S[y+dy][x+dx]=='.':
            q.append([y+dy,x+dx])
            S[y+dy][x+dx]=S[y][x]+1

if S[H][W]=='.':
    print('-1')
else:
    print(H*W-cnt_nm-S[H][W]-1)

Submission status: Accepted

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

que = deque([[0,0]])
seen = [[-1]*W for _ in range(H)]
seen[0][0] = 0
count = 0
for i in range(H):
    for j in range(W):
        if map[i][j]=="#":
            seen[i][j] = -2
        else:
            count +=1

while que:
    y, x = que.popleft()
    for dy, dx in ([0,1],[1,0],[0,-1],[-1,0]):
        ny, nx = y+dy, x+dx
        if 0<=ny<H and 0<=nx<W and seen[ny][nx]==-1 and map[ny][nx] != "#":
            seen[ny][nx] = seen[y][x] + 1
            que.append([ny, nx])

#print(*seen, sep="\n")
#print("\n")
max = seen[H-1][W-1]
if max >=0:
    cnt = count-max-1
elif max ==-1:
    cnt = -1
print(cnt)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
maze = [list(input()) for _ in range(h)]
from collections import deque
def bfs(maze, sy, sx, gy, gx):
    d = [[-1] * w for _ in range(h)]
    que = deque([[sy, sx]])
    #print(que)
    d[sy][sx] = 0
    while que:
        y, x = que.popleft()
        if y == gy and x == gx:
            break
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            ny, nx = y + j, x + k
            if 0 <= nx < w  and 0 <= ny < h  and d[ny][nx] == -1 and maze[ny][nx] != "#":
                d[ny][nx] = d[y][x] + 1
                que.append([ny, nx])
                
    return d
gx, gy = w - 1, h - 1
def counting(maze, h, w, aim):
    cnt = 0
    for i in range(h):
        for j in range(w):
            if maze[i][j] == aim:
                cnt += 1
    return cnt
a = bfs(maze, 0, 0, gy, gx)
if a[gy][gx] == -1:
    print(-1)
else:
    print(h * w - (counting(maze, h, w, '#') + (a[gy][gx] + 1)))

Submission status: Accepted

Solution code:
from collections import deque

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

c = [[-1 for _ in range(W)] for _ in range(H)]
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
q = deque()
q.append((0, 0))
c[0][0] = 1

while q:
    x, y = q.popleft()
    for dx, dy in d:
        nx = x + dx
        ny = y + dy
        if nx < 0 or nx >= W or ny < 0 or ny >= H:
            continue
        if S[ny][nx] == "." and c[ny][nx] is -1:
            c[ny][nx] = c[y][x] + 1
            q.append((nx, ny))

c_min = c[H - 1][W - 1]

if c_min == -1:
    ans = -1
else:
    ans = sum([s.count(".") for s in S]) - c_min

print(ans)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
g=[list(input()) for _ in range(h)]
dyx=[(1,0),(-1,0),(0,1),(0,-1)]
from collections import deque
q=deque()
q.append((0,0))
g[0][0]=0
while q:
    ny,nx=q.popleft()
    for dy,dx in dyx:
        y=ny+dy
        x=nx+dx
        if 0<=y<h and 0<=x<w and g[y][x]==".":
            g[y][x]=1+g[ny][nx]
            q.append((y,x))
if g[h-1][w-1]=="." or g[h-1][w-1]=="#":
    print(-1)
    exit()

d={}
ans=0
x=g[h-1][w-1]
for i in range(h):
    for j in range(w):
        if g[i][j]==".":
            ans+=1
            g[i][j]="@"
            continue
        if g[i][j]=="#":
            continue
        if g[i][j] in d:
            ans+=1
            g[i][j]="@"
        else:
            if g[i][j]>x:
                ans+=1
                g[i][j]="@"
            d[g[i][j]]=1

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
edges = ['#']*(W+2)
field = [edges]
dyx = [(0, 1), (0, -1), (1, 0), (-1, 0)]
bk = 0
for _ in range(H):
    line = list(input())
    bk += line.count('#')
    field.append(['#'] + line + ['#'])
field.append(edges)

steps = 1
q = deque()
field[1][1] = 1
q.append((1, 1, 1))

while q:
    cy, cx, lv = q.popleft()

    for dy, dx in dyx:
        ny, nx = dy+cy, dx+cx

        if field[ny][nx] == '.':
            field[ny][nx] = lv+1
            q.append((ny, nx, lv+1))
steps = str(field[H][W])
if steps.isnumeric():
    print(W*H-bk-int(steps))
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
bord = [list(input()) for _ in range(h)]
visit = [[-1 for _ in range(w)] for _ in range(h)]
visit[0][0] = 1


q = deque([[0,0]])
visit[0][0] = 1
while q:
    px, py = q.popleft()
    for i, j in ([1,0],[-1,0],[0,1],[0,-1]):
        if px+i >= 0 and px+i < h and py+j >= 0 and py+j < w:
            if bord[px+i][py+j] == "." and visit[px+i][py+j] < 0:
                visit[px+i][py+j] = visit[px][py]+1
                q.append([px+i, py+j])
if visit[h-1][w-1] < 0:
    print(-1)
else:
    c = [i.count(".") for i in bord]
    print(sum(c)-visit[h-1][w-1])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
 
H, W = [int(x) for x in input().split()]
s = []
W_count = 0
for _ in range(H):
    tmp = list(input().rstrip())
    s.append(tmp)
    W_count += tmp.count('.')

from collections import deque
D = [[-1] * W for _ in range(H)]

def bfs():
    queue = deque([(0, 0, 0, 0)])
    D[0][0] = 0
    while queue:
        u = queue.popleft()
        x = u[0]
        y = u[1]
        D[x][y] = D[u[2]][u[3]] + 1
        for i in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if 0 <= i[0] < H and 0 <= i[1] < W and D[i[0]][i[1]] < 0 and s[i[0]][i[1]] == ".":
                queue.append((i[0], i[1], x, y))
                s[i[0]][i[1]] = "#"
    return D

D = bfs()
if D[-1][-1] == -1:
    print(-1)
    sys.exit()
print(W_count - D[-1][-1])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
 
H, W = [int(x) for x in input().split()]
s = []
W_count = 0
for _ in range(H):
    tmp = list(input().rstrip())
    s.append(tmp)
    W_count += tmp.count('.')

from collections import deque
D = [[-1] * W for _ in range(H)]

def bfs():
    queue = deque([(0, 0, 0, 0)])
    D[0][0] = 0
    while queue and D[-1][-1] < 0:
        u = queue.popleft()
        x = u[0]
        y = u[1]
        D[x][y] = D[u[2]][u[3]] + 1
        for i in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if 0 <= i[0] < H and 0 <= i[1] < W and D[i[0]][i[1]] < 0 and s[i[0]][i[1]] == ".":
                queue.append((i[0], i[1], x, y))
                s[i[0]][i[1]] = "#"
    return D

D = bfs()
if D[-1][-1] == -1:
    print(-1)
    sys.exit()
print(W_count - D[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque 
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
moves = ((1, 0), (0, 1), (0, -1), (-1, 0))
dist = [[-1]*W for _ in range(H)] 

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

    while q:
        y, x = q.popleft()
        for dy, dx in moves:
            ny = y + dy 
            nx = x + dx 
            if 0 <= ny < H and 0 <= nx < W and visited[ny][nx] == 0 and s[ny][nx] == '.':
                visited[ny][nx] = 1 
                dist[ny][nx] = dist[y][x] + 1 
                q += [[ny, nx]]

bfs()
ans = H * W
if dist[H-1][W-1] == -1:
    print(-1)
    exit()
for i in range(H):
    for j in range(W):
        if s[i][j] =='#':
            ans -= 1 

print(ans-dist[H-1][W-1]-1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)

H,W=map(int, input().split())  
S=[]
initB=0
for i in range(H):
    s=[0 if j=='.' else 1 if j=='#' else None for j in input()]
    initB+=sum(s)
    S.append(s)
#print(S)
from collections import deque
que=deque([(0,0)])
di=[-1,1,0,0]
dj=[0,0,-1,1]
S[0][0]=1
while que:
    h,w=que.popleft()
    for i,j in zip(di,dj):
        if 0<=h+i<H and 0<=w+j<W and S[h+i][w+j]==0:
            S[h+i][w+j]= S[h][w]+1
            que.append((h+i,w+j))

if S[H-1][W-1]<2:
    print(-1)
else:
    print(H*W-S[H-1][W-1]-initB)
#print(S)

Submission status: Accepted

Solution code:
from collections import deque

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

deque = deque()
deque.append([0,0])
Visited=[[-1 for _ in range(w)] for _ in range(h)]
Visited[0][0] = 0

while deque:
    now = deque.popleft()
    x_now = now[0]
    y_now = now[1]

    Cands = []
    For_cands = [-1,0,1]
    for i in For_cands:
        for j in For_cands:
            if i == j or i == j*-1:
                continue
            if x_now + i < w and x_now +i >=0 and y_now +j < h and y_now + j >=0:
                if S[y_now+j][x_now+i] == '.':
                    Cands.append([x_now+i, y_now+j])
    for cands in Cands:
        if Visited[cands[1]][cands[0]] != -1:
            continue
        deque.append(cands)
        Visited[cands[1]][cands[0]] = Visited[y_now][x_now] + 1

goal_dist = Visited[h-1][w-1]

white = 0
for i in range(h):
    white += S[i].count('.')

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

Submission status: Accepted

Solution code:
import queue
H, W = map(int, input().split())
S = [input() for _ in range(H)]
white = sum(map(lambda x: x.count("."), S))
dxs = (0,1,0,-1)
dys = (1,0,-1,0)

goal = False
reached = [[None for _ in range(W)] for _ in range(H)]
reached[0][0] = 0

q = queue.Queue()
q.put((0,0))
while not q.empty():
    now = q.get()
    now_val = reached[now[1]][now[0]]
    
    for dx,dy in zip(dxs,dys):
        x = now[0] + dx
        y = now[1] + dy
        # 範囲外
        if x < 0 or y < 0 or x >= W or y >= H: continue
        # 到達済    
        if reached[y][x] is not None: continue
        # マスが黒の場合
        if S[y][x] == "#":
            reached[y][x] = -1
            continue
        # マスが城の場合
        else:
            if x == W-1 and y == H-1: goal = True
            reached[y][x] = now_val + 1
            q.put((x, y))

print((white - reached[H-1][W-1] -1) if goal else -1)

Submission status: Accepted

Solution code:
from collections import deque

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

l = [input() for i in range(h)]
memo = [[-1]*w for i in range(h)]

black_cells = deque()
memo[0][0] = 0
black_cells.append((0, 0))
for i in range(h):
    for j in range(w):
        if l[i][j] == "#":
            memo[i][j] = -2

count = 0
while black_cells:
    nh, nw = black_cells.popleft()
    count = memo[nh][nw]
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        new_nh = nh + dy
        new_nw = nw + dx
        if new_nh < 0 or h <= new_nh or new_nw < 0 or w <= new_nw:
            continue
        if memo[new_nh][new_nw] == -1:
            memo[new_nh][new_nw] = count + 1
            black_cells.append((new_nh, new_nw))
        if new_nh == h-1 and new_nw == w-1:
            count += 1
            break
    if new_nh == h-1 and new_nw == w-1:
        break

if new_nh == h-1 and new_nw == w-1:
    sc = 0
    for i in l:
        sc += i.count("#")
    print(h*w-sc - count - 1)
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque
def mbfs(S,H,W,sh,sw):
    dist=[[-1]*W for i in range(H)]
    dist[sh][sw]=0

    d=deque()
    d.append([sh,sw])
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    while(len(d)!=0):
        h=d[0][0]
        w=d[0][1]
        d.popleft()
        for dir in range(4):
            nh=h+dx[dir]
            nw=w+dy[dir]
            if(nh>H-1 or nh<0 or nw>W-1 or nw<0):
                continue
            if(dist[nh][nw]!=-1 or S[nh][nw]=='#'):
                continue
            dist[nh][nw]=dist[h][w]+1
            S[nh][nw]=='#'
            d.append([nh,nw])
    return dist

H,W=map(int,input().split())
S=[]
for i in range(H):
    S.append(input())
cnt=0
for i in range(H):
    for j in range(W):
        if(S[i][j]=='#'):
            cnt+=1


li=mbfs(S,H,W,0,0)
if(li[H-1][W-1]!=-1):
    print(H*W-cnt-(li[H-1][W-1]+1))
else:
    print(-1)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
S = [input() for i in range(H)]
T = [[False]*W for i in range(H)]
Q = [(1,0,0)]
cnt = 0
while Q:
    q = Q.pop(0)
    if min(q)<0 or q[1]>=H or q[2]>=W:continue
    if S[q[1]][q[2]]=="#" or T[q[1]][q[2]]:continue
    if q[1]==H-1 and q[2]==W-1:
        cnt = q[0]
        break
    T[q[1]][q[2]]=True
    Q.append((q[0]+1,q[1]+1,q[2]))
    Q.append((q[0]+1,q[1]-1,q[2]))
    Q.append((q[0]+1,q[1],q[2]+1))
    Q.append((q[0]+1,q[1],q[2]-1))
ans = 0
for s in S:ans+=s.count(".")
print(ans-cnt if cnt else -1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
a=['*'*(w+2)]+['*'+input()+'*' for _ in range(h)]+['*'*(w+2)]
s=0
for i in range(1,h+1):
  s+=a[i].count('.')
from collections import deque
d=deque()
d.append([1,1])
c=[[10000]*w for _ in range(h)]
c[0][0]=1
di=[[0,1],[1,0],[-1,0],[0,-1]]
while d:
  g=d.popleft()
  for i in di:
    x=g[0]+i[0]
    y=g[1]+i[1]
    if a[x][y]=='.':
      if c[x-1][y-1]==10000:
        d.append([x,y])
        c[x-1][y-1]=c[g[0]-1][g[1]-1]+1
if c[h-1][w-1]==10000:
  print(-1)
else:
  print(s-c[h-1][w-1])

Submission status: Accepted

Solution code:
import sys
from collections import deque

H, W = map(int, sys.stdin.readline().strip().split())
grid = [[]] * H
movable = 0
for i in range(H):
    grid[i] = list(sys.stdin.readline().strip())
    for j in grid[i]:
        if j == ".":
            movable += 1
# print(movable)

q = deque()
q.append((0, 0, 0))
visited = set()
goal = False
# BFS
while q:
    x, y, c = q.popleft()
    for dx, dy in ((-1, 0), (0, 1), (1, 0), (0, -1)):
        if 0 <= x+dx < W and 0 <= y+dy < H:
            if x+dx == W-1 and y+dy == H-1:
                goal = True
                c += 1
                break
            elif grid[y+dy][x+dx] == "." and (x+dx, y+dy) not in visited:
                q.append((x+dx, y+dy, c+1))
                visited.add((x+dx, y+dy))

    if goal:
        break

if goal:
    print(movable - (c + 1))
else:
    print(-1)

Submission status: Accepted

Solution code:
import sys
import queue
input = sys.stdin.readline

h,w = map(int,input().split())
maze = [input() for _ in range(h)]
black = sum(x.count('#') for x in maze)
count = [[0 for _ in range(w)] for _ in range(h)]

count[0][0] = 1
q = queue.Queue()
q.put((0,0))

while not q.empty():
    y, x = q.get()
    for dy, dx in ((1,0),(0,1),(-1,0),(0,-1)):
        ny = y + dy
        nx = x + dx
        if 0 <= ny < h and 0 <= nx < w:
            if maze[ny][nx] == '.' and count[ny][nx] == 0:
                count[ny][nx] = count[y][x] + 1
                q.put((ny,nx))
if count[h-1][w-1] == 0:
    print (-1)
else:
    print (h*w - black - count[h-1][w-1])

Submission status: Accepted

Solution code:
from collections import deque
from collections import defaultdict
import sys

H,W=map(int,input().split())
maze=[[0]*W for _ in range(H)]
b=0                  # ブロックの数
for i in range(H):
  a=str(input())
  for j in range(W):
    if a[j]=='#':
      b+=1
    maze[i][j]=a[j]
def BFS(maze,s,g):
  que=deque()
  sy,sx=s[0],s[1]
  gy,gx=g[0],g[1]
  que.append([sx,sy])
  dist=[[0]*W for _ in range(H)]
  seen=[]
  seen.append([sx,sy])   
  Next=[[-1,0],[1,0],[0,1],[0,-1]]
  while len(que)!=0:
    l=que.popleft()
    for n in Next:
      x,y=l[0]+n[0],l[1]+n[1]
      if (x<0 or x>=W or y<0 or y>=H) or maze[y][x]=='#':
        pass
      else:
        if [x,y] not in seen:
          seen.append([x,y])
          que.append([x,y])
          dist[y][x]=dist[l[1]][l[0]]+1
  return dist[gy][gx]

d=BFS(maze,[0,0],[H-1,W-1])
if d==0:
  print(-1)   # この時たどり着けない
else:
  print(H*W-(d+1)-b)

Submission status: Accepted

Solution code:
from collections import deque


h,w=map(int,input().split())
s=[list(input()) for i in range(h)]
dist=[[0 for i in range(w)] for j in range(h)]
que=deque([])
que.append([0,0])
dyx=[[1,0],[0,-1],[-1,0],[0,1]]
ndot=0
for i in range(h):
  for j in range(w):
    if s[i][j]==".":
      ndot+=1
s[0][0]="#"

while que:
  y,x=que.popleft()
  for dy,dx in dyx:
    nx=x+dx
    ny=y+dy
    if (nx<0 or nx>w-1 or ny<0 or ny>h-1):
      continue
    if s[ny][nx]==".":
      dist[ny][nx]=dist[y][x]+1
      que.append([ny,nx])
      s[ny][nx]="#"

ans=ndot-dist[h-1][w-1]-1
if dist[h-1][w-1]==0:
  ans=-1
print(ans)

Submission status: Accepted

Solution code:
# 最短でゴールして残った黒をぜんぶ白に変えれば最大のポイントをもらえそう
# ってなふうに雑に考えてたけど、探索・最短経路復元・解答それぞれで1度ずつBFSをしなきゃならんのか？？？？

h, w = map(int, input().split())
table = [[] for _ in range(h)]
for y in range(h):
    table[y] = list(input())
# ステップ更新用
my_table = [[-1 for _ in range(w)] for _ in range(h)]
my_table[0][0] = 0
yo = [(0, 0)]
steps = [0, -1, 0, 1, 0]
while len(yo) > 0:
    p = yo[0]
    yo = yo[1:]
    for i in range(4):
        next_x, next_y = steps[i + 1] + p[1], steps[i] + p[0]
        if next_x < 0 or w <= next_x or next_y < 0 or h <= next_y:
            continue
        if table[next_y][next_x] == "#":
            continue
        if my_table[next_y][next_x] >= 0:
            continue
        my_table[next_y][next_x] = my_table[p[0]][p[1]] + 1
        yo.append((next_y, next_x))
if my_table[h - 1][w - 1] == -1:
  print(-1)
  exit()
  
# 経路を逆からたどって最短経路復元
restore_table = [["o" for _ in range(w)] for _ in range(h)]
restore_table[h - 1][w - 1] = "x"
now = my_table[h - 1][w - 1]
cur = (h - 1, w - 1)
while now != 0:
    for i in range(4):
        next_y, next_x = steps[i] + cur[0], steps[i + 1] + cur[1]
        if next_x < 0 or w <= next_x or next_y < 0 or h < next_y:
            continue
        if my_table[next_y][next_x] == now - 1:
            restore_table[next_y][next_x] = "x"
            cur = (next_y, next_x)
            now -= 1
            break

# やっと答え
ans = 0
for y in range(h):
    for x in range(w):
        if restore_table[y][x] == "o" and table[y][x] == ".":
            ans += 1
print(ans)

Submission status: Accepted

Solution code:
# #の数を数えておいて、最初の.の数-最短距離
# 最短経路なので幅優先でやる
from collections import deque

h, w = map(int, input().split())
table =[]
default_dot = 0
for _ in range(h):
  line = list(input())
  default_dot+=line.count(".")
  table.append(line)

default_dot-=2  # スタートとゴール
table[0][0] = 0

cur = [0, 0]   # x, y
queue = deque()
queue.append(cur)
steps = [0, 1, 0, -1, 0]

minimum_step = 0

while True:
  if len(queue)==0:
    print(-1)
    exit()
  now = queue.popleft()
  if now[0] == w-1 and now[1] == h-1:
    minimum_step = table[now[1]][now[0]]-1
    break
  for i in range(4):
    next_y, next_x = now[1]+steps[i], now[0]+steps[i+1]
    if 0<=next_y<h and 0<=next_x<w and table[next_y][next_x] == ".":
      table[next_y][next_x] = table[now[1]][now[0]]+1
      queue.append([next_x, next_y])


print(default_dot-minimum_step)

Submission status: Accepted

Solution code:
from collections import deque
INFTY = 10**4
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
cnt = 0
for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            cnt += 1
dist = [[INFTY for _ in range(W)] for _ in range(H)]
hist = [[0 for _ in range(W)] for _ in range(H)]
dist[0][0] = 0
que = deque([(0,0)])
while que:
    i,j = que.popleft()
    if j+1<W and hist[i][j+1]==0 and S[i][j+1]==".":
        dist[i][j+1] = dist[i][j]+1
        que.append((i,j+1))
        hist[i][j+1] = 1
    if i-1>=0 and hist[i-1][j]==0 and S[i-1][j]==".":
        dist[i-1][j] = dist[i][j]+1
        que.append((i-1,j))
        hist[i-1][j] = 1
    if j-1>=0 and hist[i][j-1]==0 and S[i][j-1]==".":
        dist[i][j-1] = dist[i][j]+1
        que.append((i,j-1))
        hist[i][j-1] = 1
    if i+1<H and hist[i+1][j]==0 and S[i+1][j]==".":
        dist[i+1][j] = dist[i][j]+1
        que.append((i+1,j))
        hist[i+1][j] = 1
if dist[H-1][W-1]==INFTY:
    print(-1)
else:
    print(cnt-2-dist[H-1][W-1]+1)