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:
h,w = map(int,input().split())
s = [str(input()) for i in range(h)]
num = [[-1] * w for i in range(h)]
num[0][0] = 0
now = {(0,0)}
for i in range(1,2501):
    tmp = set()
    for x,y in now:
        if x > 0:
            if s[x-1][y] == "." and num[x-1][y] == -1:
                num[x-1][y] = i
                tmp.add((x-1,y))
        if x < h-1:
            if s[x+1][y] == "." and num[x+1][y] == -1:
                num[x+1][y] = i
                tmp.add((x+1,y))
        if y > 0:
            if s[x][y-1] == "." and num[x][y-1] == -1:
                num[x][y-1] = i
                tmp.add((x,y-1))
        if y < w-1:
            if s[x][y+1] == "." and num[x][y+1] == -1:
                num[x][y+1] = i
                tmp.add((x,y+1))
    now = tmp
if num[-1][-1] == -1:
    print(-1)
else:
    print(h * w-num[-1][-1]-sum([s[i].count("#") for i in range(h)])-1)

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
p=[list("#"*(w+2))]+[list("#"+input()+"#") for i in range(h)]+[list("#"*(w+2))]
s0,s1=1,1
g0,g1=h,w
p[s0][s1]=0
d=[(1,0),(-1,0),(0,1),(0,-1)]
q=deque([[s0,s1]])
while q:
    x,y=q.popleft()
    for dx,dy in d:
        if p[x+dx][y+dy]==".":
            p[x+dx][y+dy]=p[x][y]+1
            q.append([x+dx,y+dy])
if p[g0][g1]=='.':
    print(-1)
else:
    yy=0
    for i in range(1,h+1):
        for j in range(1,w+1):
            if p[i][j]=='#':
                yy+=1
    print(h*w-p[g0][g1]-yy-1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=['#'*(w+2)]
s+=['#'+input()+'#' for _ in range(h)]
s.append('#'*(w+2))
h+=2
w+=2
p=[[1,0],[0,1],[-1,0],[0,-1]]
st=[]
cnt=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='.':
            cnt+=1
ans=0
n=[(1,1)]
route={n[0]:0}
count=0
while n:
    count+=1
    n2=[]
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if s[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                route[np]=count
    n=n2
if route.get((h-2,w-2),-1)>=0:
    print(cnt-route.get((h-2,w-2),-1)-1)
else:
    print(-1)

Submission status: Accepted

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

field=[list(input())for i in range(h)]
cnt=0
for i in field:
    for j in i:
        if j=='#':
            cnt+=1
dp=[[0 for i in range(w)]for i in range(h)]

dydx=[[-1,0],[1,0],[0,-1],[0,1]]

queue=[]
queue.append([0,0])

while queue:
    ny,nx=queue.pop(0)
    for dy,dx in dydx:
        nny,nnx=ny+dy,nx+dx
        if 0<=nny<=h-1 and 0<=nnx<=w-1 and field[nny][nnx]!="#" and dp[nny][nnx]==0:
            dp[nny][nnx]=dp[ny][nx]+1
            queue.append([nny,nnx])
            if nny==h-1 and nnx==w-1:
                print(h*w-cnt-dp[h-1][w-1]-1)
                exit()
print(-1)

Submission status: Accepted

Solution code:
import collections
H,W=map(int,input().split())
s=[list(input()) for i in range(H)]
kuro=0
siro=0
for h in range(H):
    for w in range(W):
        if s[h][w]=="#":
            kuro+=1
        else:
            siro+=1



visited=[[0 for i in range(W)] for h in range(H)]
visited[0][0]=1
stack=collections.deque([[0,0,1]])
flag=0
while stack and not flag:

    y,x,m=stack.popleft()
    lst=[]
    if y>0:lst.append([-1,0])
    if y<H-1:lst.append([1,0])
    if x>0:lst.append([0,-1])
    if x<W-1:lst.append([0,1])
    for y1,x1 in lst:
        Y=y+y1
        X=x+x1
        if Y==H-1 and X==W-1:
            flag=1
            m+=1
            break
        if not visited[Y][X] and s[Y][X]==".":
            stack.append([Y,X,m+1])
            visited[Y][X]=1

print((siro-(m)) if flag else -1)

Submission status: Accepted

Solution code:
from collections import deque
import itertools

def bfs(graph, sh, sw):
    td = deque([[sh, sw]])
    graph[sh][sw] = "0"
    while td:
        h, w = td.popleft()
        num = int(graph[h][w])
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_h, new_w = h + j, w + k
            if new_h == gy and new_w == gx:
                return num + 1
                break
            
            if new_h < 0 or new_h >= H or new_w < 0 or new_w >= W:
                continue
            elif graph[new_h][new_w] == ".":
                graph[new_h][new_w] = str(num + 1)
                td.append([new_h, new_w])

    return -1

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

sy, sx = 0, 0
gy, gx = H - 1, W - 1

bcnt = 0

for s, t in itertools.product(range(H), range(W)):
    if ls[s][t] == "#":
        bcnt += 1

nurazu = bfs(ls, sy, sx)
nurazu = nurazu + 1

if nurazu == 0:
    print(-1)
else:
    print(H * W - (bcnt + nurazu))

Submission status: Accepted

Solution code:
# AGC088 D - Grid Repainting
from collections import deque
def bfs(sy,sx,gy,gx):
    q = deque([[sy,sx]])
    visited[sy][sx]=0
    while q:
        y,x = q.popleft()
        if [y,x]==[gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if ny<0 or ny>h-1 or nx<0 or nx>w-1 or path[ny][nx]=="#":
                continue
            if path[ny][nx]=="." and visited[ny][nx]==-1:
                visited[ny][nx]=visited[y][x]+1
                q.append([ny,nx])

h,w=map(int,input().split())
sy,sx=0,0
gy,gx=h-1,w-1
path=[input() for i in range(h)]
visited = [[-1]*w for i in range(h)]
bfs(sy,sx,gx,gy)

ans=0
black=0
for p in path:
    black+=p.count('#')
if visited[gy][gx]==-1:
    print(-1)
else:
    ans=h*w-(visited[gy][gx]+1)-black
    print(ans)

Submission status: Accepted

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [None]*h

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

d = [[10000000 for i in range(w)] for j in range(h)]
sharp = 0

sx,sy = 0,0
gx,gy = w-1 , h-1
            
dx = [1,0,-1,0]
dy = [0,1,0,-1]

for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            sharp += 1

def bfs():
    d[sy][sx] = 0
    que = deque([[sy,sx]])
    
    while que:
        y,x = que.popleft()
        
        for k in range(4):
            nx = x + dx[k]
            ny = y + dy[k]
            
            if 0<=nx and nx<w and 0<=ny and ny<h and s[y][x] != '#':
                if d[ny][nx] > d[y][x]+1:
                    d[ny][nx]=d[y][x]+1
                    que.append([ny,nx])
                    
    if d[gy][gx] == 10000000:
        print("-1")
    else:
        print(w*h - sharp - (d[gy][gx]+1))
        
bfs()

Submission status: Accepted

Solution code:
from collections import deque 
import sys
H, W = map(int, input().split())
city = []
dot_count = 0
for i in range(H):
    city.append(input())
    dot_count += city[i].count('.')
search_point = deque([[0, 0, 0]])
direction_list = [[1,0],[-1,0],[0,1],[0,-1]]
searched_point = [[False for _ in range(W)] for _ in range(H)]
while search_point:
    now_point = search_point.popleft()
    for direction in direction_list:
        next_point = [now_point[0] + direction[0], now_point[1] + direction[1], now_point[2] + 1]
        if next_point[0] < 0 or next_point[0] >= H or next_point[1] < 0 or next_point[1] >= W \
        or city[next_point[0]][next_point[1]] == '#' or searched_point[next_point[0]][next_point[1]] == True:
            continue
        if next_point[0] == H-1 and next_point[1] == W-1:
            print(dot_count - next_point[2] - 1)
            sys.exit()
        searched_point[next_point[0]][next_point[1]] = True
        search_point.append(next_point)
print("-1")

Submission status: Accepted

Solution code:
from collections import deque

def bfs(y,x):
    f=[[float("inf")]*(w+1) for i in range(h+1)]
    f[y][x]=0
    que=deque([])
    que.append((y,x))
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    while que:
        p=que.popleft()
        if p[0]==h and p[1]==w:
            break
        for i in range(4):
            nx=p[1]+dx[i]
            ny=p[0]+dy[i]
            if 0<=nx<w+1 and 0<=ny<h+1 and f[ny][nx]==float("inf") and maze[ny][nx]!="#":
                que.append((ny,nx))
                f[ny][nx]=f[p[0]][p[1]]+1
    return f[h][w]

h,w=map(int,input().split())
h-=1
w-=1
maze=[list(input()) for i in range(h+1)]
#print(maze)
cnt=0
for i in range(h+1):
    for j in range(w+1):
        if maze[i][j]==".":
            cnt+=1
route=bfs(0,0)
score=cnt-route-1
if 0<route<float("inf"):
    print(score)
else:
    print(-1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
li=[input() for i in range(h)]
black=0
for i in li:
  temp=i.count("#")
  black+=temp

zenbu="#"*w
li.insert(0,zenbu)
li.append(zenbu)

for i in range(h+2):
  li[i]="#"+li[i]
  li[i]+="#"

ys,xs=2,2
yg,xg=h+1,w+1
a=li

n=[(ys-1,xs-1)]
route={n[0]:0}
p=[[1,0],[0,1],[-1,0],[0,-1]]
count=1
while route.get((yg-1,xg-1),0)==0 and count != 10000:
    n2=[]
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                route[np]=count
    n=n2
    count+=1
if count==10000:
  print(-1)
else:
  print(h*w-black-count)

Submission status: Accepted

Solution code:
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if s[y][x]!='.':
        continue
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H:
            q_append((nx,ny,l+1))
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if s[y][x]!='.':
        continue
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H:
            q_append((nx,ny,l+1))
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
S = [0]*H
for i in range(H):
    S[i] = input()

# print(H, W, S)
T = [[0]* W for h in range(H)]
blocks = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            T[h][w] = -1
            blocks += 1

def is_inside(w, h, W, H):
    if w >= 0 and w < W and h >= 0 and h < H:
        return True
    return False

# print(T)
V = deque([(0, 0)])
while len(V) != 0:
    v = V.popleft()
    # print('v={}'.format(v))
    h = v[0]
    w = v[1]
    t = T[h][w]
    if is_inside(h - 1, w, H, W):
        if T[h - 1][w] != -1 and T[h - 1][w] == 0:
            T[h - 1][w] = t + 1
            V.append((h - 1, w))
    if is_inside(h + 1, w, H, W):
        if T[h + 1][w] != -1 and T[h + 1][w] == 0:
            T[h + 1][w] = t + 1
            V.append((h + 1, w))
    if is_inside(h, w - 1, H, W):
        if T[h][w - 1] != -1 and T[h][w - 1] == 0:
            T[h][w - 1] = t + 1
            V.append((h , w - 1))
    if is_inside(h, w + 1, H, W):
        if T[h][w + 1] != -1 and T[h][w + 1] == 0:
            T[h][w + 1] = t + 1
            V.append((h , w + 1))

t = T[H - 1][W - 1]
if t == 0:
    print(-1)
else:
    print(W * H - blocks - t - 1)

Submission status: Accepted

Solution code:
from collections import deque
import sys
input = sys.stdin.readline

H,W = map(int, input().split())
table = []
b_count = 0

for i in range(H):
    s = list(input())
    b_count += s.count("#")
    table.append(s)

Q = deque()
Q.append((0,0))
dist = [[-1]*W for i in range(H)]
dist[0][0] = 0
dx = [1,0,-1,0]
dy = [0,-1,0,1]

while Q:
    y,x = Q.popleft()
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]
        if 0<=ny<H and 0<=nx<W and table[ny][nx] == "." and dist[ny][nx] == -1:
            dist[ny][nx] = dist[y][x]+1
            Q.append((ny,nx))

if dist[-1][-1] == -1:
    print(-1)
else:
    ans = H*W-b_count-(dist[-1][-1]+1)
    print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())

s = ['#' * (W + 2)] + ['#' + input() + '#' for i in range(H)] + ['#' * (W + 2)]

# m : そこにたどり着くために必要な白マスの数
m = [[-1 for x in range(W+2)] for y in range(H+2)]
m[1][1] = 1


from collections import deque
qx = deque([1])
qy = deque([1])

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


while len(qx) > 0:
    x, y = qx.popleft(), qy.popleft()
    for d in range(4):
        nx, ny = x + dx[d], y + dy[d]
        # 訪れたことがあるなら調べない
        if m[ny][nx] != -1: continue

        if s[ny][nx] == '.':
            qx.append(nx), qy.append(ny)
            m[ny][nx] = m[y][x] + 1

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

else:
    print(sum([c.count('.') for c in s]) - m[H][W])

Submission status: Accepted

Solution code:
from collections import deque
INF = float('inf')
ROAD = '.'
WALL = '#'
STEPS = [(1, 0), (-1, 0), (0, 1), (0, -1)]


def main():
    H,W = map(int, input().split())
    maze = [None]*H
    white = 0
    
    for i in range(H):
        maze[i] = list(input())
        for j in range(W):
            if maze[i][j] == ROAD:
                white += 1
                maze[i][j] = INF
    
    # mazeにはその地点に到達するまでに必要な白の枚数を記録
    maze[0][0] = 1
    que = deque([[0, 0]])

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

        for (i, j) in STEPS:
            ny, nx = y+i, x+j
            if ny < 0 or ny >= H or nx < 0 or nx >= W:
                continue
            
            target = maze[ny][nx]
            if target != WALL:
                if target > maze[y][x]+1:
                    maze[ny][nx] = maze[y][x] + 1
                    que.append([ny,nx])
    
    if maze[H-1][W-1] == INF:
        print(-1)
    else:
        print(white - maze[H-1][W-1])
    
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
from collections import deque


def solve(*args: str) -> str:
    h, w = map(int, args[0].split())
    S = [[c for c in s] for s in args[1:]]

    total = sum(s.count('.') for s in S)

    Q = deque()
    Q.append((0, 0, 1))

    depth = 0
    while Q:
        x, y, n = Q.popleft()
        if S[y][x] == '.':
            S[y][x] = str(n)
            if (x, y) == (w-1, h-1):
                depth = n
                break

            if 0 < x:
                Q.append((x-1, y, n+1))
            if x+1 < w:
                Q.append((x+1, y, n+1))
            if 0 < y:
                Q.append((x, y-1, n+1))
            if y+1 < h:
                Q.append((x, y+1, n+1))

    return str(total-depth if depth else -1)


if __name__ == "__main__":
    print(solve(*(open(0).read().splitlines())))

Submission status: Accepted

Solution code:
H, W  = map(int, input().split())
f = []
INF = 10**10
dist = [[INF] * W for _ in range(H)]
cnt = 0
for i in range(H):
    S = list(input())
    for j,s in enumerate(S):
        if s == "#": dist[i][j] = -1
    cnt += S.count("#")
    f.append(s)
# print(cnt)

# 最短路以外を消す？
mvs = [(0,1),(0,-1),(1,0),(-1,0)]
from collections import deque
s = (0,0)
g = (H-1,W-1)
dist[0][0] = 0
q = deque()
q.append(s)
while q:
    h,w = q.popleft()
    # print(h,w)
    for dh, dw in mvs:
        if 0 <= h+dh < H and 0 <= w+dw < W: 
            # print("checked",h+dh,w+dw)
            if dist[h+dh][w+dw] == -1:
                continue
            elif dist[h+dh][w+dw] > dist[h][w] + 1:
                q.append((h+dh,w+dw))
                dist[h+dh][w+dw] = dist[h][w] + 1
# print(H*W)
# print(cnt)
# print(dist[H-1][W-1])
if dist[H-1][W-1] == INF or dist[H-1][W-1]==-1:
    print(-1)
    exit()
ans = H*W - dist[H-1][W-1] - 1 - cnt
print(ans)

Submission status: Accepted

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

ys,xs=2,2
yg,xg =h+1,w+1

a= []

a.append("".join(["#"]*(w+2)))
cnt=0
for i in range(h):
    arrc = input()
    #迷路中の黒の数
    m = int(list(arrc).count("#"))
    cnt +=m
    
    arrc = "#"+arrc+"#"
    a.append(arrc)

a.append("".join(["#"]*(w+2)))

n=[(ys-1,xs-1)]
route={n[0]:0}
p=[[1,0],[0,1],[-1,0],[0,-1]]
count=1
while route.get((yg-1,xg-1),0)==0 and count != 10000:
    n2=[]
    for i in n:
        for j in p:
            np=(i[0]+j[0],i[1]+j[1])
            if a[np[0]][np[1]]=='.' and route.get(np,-1)==-1:
                n2.append(np)
                route[np]=count
                
    n=n2
    count+=1
if list(route.keys()).count((h,w)) == 1:
    vv = h*w - max(list(route.values())) - cnt -1
    print(vv)
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
sy, sx = 1, 1
gy, gx = h, w
map = [input() for _ in range(h)]

cnt = 0
for s in map:
    cnt += s.count(".")

f_inf = float('inf')
maze = [[f_inf] * w for _ in range(h)]
maze[sy-1][sx-1] = 0
que = deque([[sy-1, sx-1]])
while que:
    y, x = que.popleft()
    for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        next_y, next_x = y + i, x + j
        if next_y > -1 and next_x > -1 and next_y < h and next_x < w and map[next_y][next_x] == ".":
            if maze[next_y][next_x] > maze[y][x] + 1:
                maze[next_y][next_x] = maze[y][x] + 1
                que.append([next_y, next_x])

if maze[gy - 1][gx - 1] != f_inf:
    print(cnt - (maze[gy - 1][gx - 1] + 1))
else:
    print(-1)

Submission status: Accepted

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

n_black = 0
for m in M:
  for n in m:
    if n == '#':
      n_black += 1

si, sj = 0, 0
gi, gj = H - 1, W - 1

queue = []
distance = [[-1 for _ in range(W)] for _ in range(H)]
queue.append((si, sj))
distance[si][sj] = 0

while queue:
  i, j = queue.pop(0)
  if i == gi and j == gj:
    print(H * W - 1 - n_black - distance[i][j])
    exit()
  for i_, j_ in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
    if i_ >= 0 and i_ < H and j_ >= 0 and j_ < W:
      if distance[i_][j_] == -1 and M[i_][j_] == '.':
        distance[i_][j_] = distance[i][j] + 1
        queue.append((i_, j_))
        
print(-1)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
maiz = []
edge = ['#'] * (w+2)
point = 0
for _ in range(h):
    line = list(input())
    line = ['#'] + line + ['#']
    point += len([i for i in line if i == '.'])
    maiz.append(line)
maiz = [edge] + maiz + [edge]

def bfs(maiz, h, w):
    queue = [[1, 1]]
    visited = [[False]*(w+2) for _ in range(h+2)]
    maiz[1][1] = 0
    while queue:
        x, y = queue.pop(0)
        visited[y][x] = True
        hjkl = [[x-1, y], [x, y-1], [x+1, y], [x, y+1]]
        for dx, dy in hjkl:
            if (maiz[dy][dx] == '.') and (visited[dy][dx] is False):
                queue.append([dx, dy])
                maiz[dy][dx] = maiz[y][x]+1
    tf = False if maiz[h][w] == '.' else True
    return maiz[h][w], tf

n, tf = bfs(maiz, h, w)
if tf is False:
    print(-1)
    exit()

print(point-n-1)

Submission status: Accepted

Solution code:
from collections import deque

def bfs():
  q = deque()
  q.append([[1,1],0])
  used = set((1,1))
  
  while len(q)>0:
    prv_pos,prv_cost = q.popleft()
    i,j = prv_pos
    for ii,jj in [[i+1,j],[i,j+1],[i-1,j],[i,j-1]]:
      if (ii,jj) in used: continue
      if S[jj][ii]=='.':
        if [ii,jj] == [W,H]:
          return prv_cost+1
        else:
          q.append([[ii,jj],prv_cost+1])
          used.add((ii,jj))
  return -1

H,W = map(int,input().split())
S = [['#' for _ in range(W+2)]] + [['#']+[s for s in input()]+['#'] for _ in range(H)] + [['#' for _ in range(W+2)]]

res = bfs()
if res == -1:
  print(-1)
else:
  cntb = sum([row.count('#') for row in S])-2*(H+2)-2*(W+2)+4
  print(H*W-res-cntb-1)

Submission status: Accepted

Solution code:
from collections import deque

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

field = [list(input()) for _ in range(h)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs(x, y):
    distance = [[-1]*w for _ in range(h)]
    que = deque([])
    que.append((y, x))
    distance[y][x] = 0
    while que:
        y, x = que.popleft()
        if x == w-1 and y == h-1:
            break
        for i, j in zip(dx, dy):
            nx = x + i
            ny = y + j
            if 0 <= nx < w and 0 <= ny < h and field[ny][nx] == "." and distance[ny][nx] == -1:
                distance[ny][nx] = distance[y][x] + 1
                que.append((ny, nx))
    return distance

d = bfs(0, 0)
if d[h-1][w-1] == -1:
    print("-1")
    exit()
cnt = 0
for row in field:
    cnt += row.count(".")

ans = cnt - d[h-1][w-1] - 1
print(ans)

Submission status: Accepted

Solution code:

from collections import deque
def bfs():
    d = [[float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

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

    return d[gx][gy]


h, w = map(int, input().split())
maze = [list(input()) for i in range(h)]
sx, sy = 0, 0
gx, gy = h - 1, w - 1

# 白いマスを数える
white = 0
for i in range(h):
    for j in range(w):
        if maze[i][j] == ".":
            white += 1

res = bfs()
if 0 < res < float("inf"):
    # 白いマスの数から最短経路でかかるコスト分を引く
    # ゴールを黒いマスに変えることはできないためその分も引く
    print(white - res - 1)
else:
    print(-1)

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    H,W = MI()
    def is_inside(to):
        return 0<=to[0]<H and 0<=to[1]<W
    S=[ST() for _ in range(H)]
    queue = deque([(0,0)])
    visited = set()
    ans=0
    for s in S:
        ans += Counter(s)["."]
    for i in range(H*W+1):
        tmp = deque()
        while queue:
            fr = queue.popleft()
            if fr in visited:
                continue
            visited.add(fr)
            for dh,dw in [(-1,0),(0,-1),(1,0),(0,1)]:
                to = (fr[0]+dh,fr[1]+dw)
                if to not in visited and is_inside(to) and S[to[0]][to[1]]==".":
                    tmp.append(to)
        queue = tmp
        if (H-1,W-1) in tmp:
            print(ans-(i+2))
            return
    print(-1)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
H,W = map(int,input().split())
meiro = []
for h in range(H):
    meiro.append(input())
from collections import deque
Q = deque([[0,0]])
ansmap = [[-1 for _ in range(W)] for __ in range(H)]
ansmap[0][0] = 0
step = 0
while Q:
    cue = Q.popleft()
    step = ansmap[cue[0]][cue[1]]
    for i in range(4):
        # 上
        if cue[0]-1 >= 0:
            if meiro[cue[0]-1][cue[1]] == "." and (ansmap[cue[0]-1][cue[1]] > step+1 or ansmap[cue[0]-1][cue[1]] == -1):
                ansmap[cue[0]-1][cue[1]] = step+1
                Q.append([cue[0]-1,cue[1]])
        # 右
        if cue[1]+1 < W:
            if meiro[cue[0]][cue[1]+1] == "." and (ansmap[cue[0]][cue[1]+1] > step+1 or ansmap[cue[0]][cue[1]+1] == -1):
                ansmap[cue[0]][cue[1]+1] = step+1
                Q.append([cue[0],cue[1]+1])
        # 下
        if cue[0]+1 < H:
            if meiro[cue[0]+1][cue[1]] == "." and (ansmap[cue[0]+1][cue[1]] > step+1 or ansmap[cue[0]+1][cue[1]] == -1):
                ansmap[cue[0]+1][cue[1]] = step+1
                Q.append([cue[0]+1,cue[1]])
        # 左
        if cue[1]-1 >= 0:
            if meiro[cue[0]][cue[1]-1] == "." and (ansmap[cue[0]][cue[1]-1] > step+1 or ansmap[cue[0]][cue[1]-1] == -1):
                ansmap[cue[0]][cue[1]-1] = step+1
                Q.append([cue[0],cue[1]-1])
cnt=0
for m in meiro:
    cnt += m.count('#')
if ansmap[H-1][W-1] == -1:
    print(-1)
else:
    print(H*W - ansmap[H-1][W-1]-1 - cnt)

Submission status: Accepted

Solution code:
from collections import deque

def bfs():
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    d = [[float("inf")] * w for _ in range(h)]
    que = deque([])
    que.append((0, 0))
    d[0][0] = 1
    
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            
            if 0 <= nx < h and 0 <= ny < w:
                if F[nx][ny] != "#" and d[nx][ny] == float("inf"):
                    d[nx][ny] = d[p[0]][p[1]] + 1
                    que.append((nx, ny))
    return d[h-1][w-1]

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

if bfs() == float("inf"):
    print(-1)
    exit()
else:
    count = 0
    for i in range(h):
        for j in range(w):
          if F[i][j] == ".":
            count += 1
    ans = count - bfs()
    print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split(" "))
grid = list()
for _ in range(H):
    l = list()
    for c in input():
        if c == ".":
            l.append(True)
        else:
            l.append(None)
    grid.append(l)


def get_neighbors(x, y):
    neighbors = ((x-1, y), (x+1, y), (x, y-1), (x, y+1))
    result = list()
    for neighbor in neighbors:
        x, y = neighbor
        if 0 <= x <= W-1 and 0 <= y <= H-1:
            result.append((x, y))
    return result


current_x = 0
current_y = 0
distance = 0
queue = list()
grid[0][0] = 0
queue.append((current_x, current_y, distance+1))
while True:
    if not queue:
        break
    current_x, current_y, distance = queue.pop(0)
    if current_y == H - 1 and current_x == W - 1:
        break
    for neighbor in get_neighbors(current_x, current_y):
        x, y = neighbor
        if grid[y][x] is not None:
            if grid[y][x] is True:
                grid[y][x] = distance
                queue.append((x, y, distance+1))


if grid[H-1][W-1] is None or grid[H-1][W-1] is True:
    print(-1)
else:
    test = [l.count(None) for l in grid]
    num_black = sum(l.count(None) for l in grid)
    print(H*W - num_black - grid[H-1][W-1] - 1)

Submission status: Accepted

Solution code:
import queue

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

def bfs():
    x = 0
    y = 0
    cnt = 0
    Q = queue.Queue()
    check = [[True for i in range(W)] for j in range(H)]
    
    Q.put((x, y, cnt))
    while Q.qsize() > 0:
        x, y , cnt = Q.get()
        for i in range(4):
            if 0 <= x + dx[i] < H and 0 <= y + dy[i] < W and check[x + dx[i]][y + dy[i]]:
                check[x + dx[i]][y + dy[i]] = False
                if field[x + dx[i]][y + dy[i]] == "#":
                    pass
                elif x + dx[i] == H - 1 and y + dy[i] == W - 1:
                    return cnt + 1
             
                else:
                    Q.put((x + dx[i], y + dy[i], cnt + 1))
                    
    return -1

nums=list(map(int,input().split()))
H = nums[0]
W = nums[1]


field = [[None for i in range(W)] for j in range(H)]

black = 0
for i in range(H):
    str1 = input()
    for j in range(W):
        field[i][j] = str1[j]
        if str1[j] == "#":
            black += 1
            
Q = queue.Queue()
res = bfs()
if res >= 0:
    result = H * W - black -(res + 1)
    print(result)
else:
    print(res)