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:
def ABC106_B():
    def make_divisors(n):
        divisors = []
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                divisors.append(i)
                if i != n // i:
                    divisors.append(n // i)
        # divisors.sort()
        return divisors
    N = I()
    ans = 0
    for i in range((N+1)//2):
        cur = i*2+1
        if len(make_divisors(cur))==8:
            ans += 1
    print(ans)
    return

def ABC122_B():
    S = SI()
    ans = 0
    cur = 0
    d = {"A","C","G","T"}
    for s in S:
        if s in d:
            cur += 1
        else:
            ans = max(ans,cur)
            cur = 0
    ans = max(ans,cur)
    print(ans)
    return

def paken2019_C():
    N, M = LI()
    A = [LI()for _ in range(N)]
    T = [i for i in range(M)]
    ans = 0
    for t1,t2 in itertools.permutations(T,2):
        cur = 0
        for i in range(N):
            cur += max(A[i][t1],A[i][t2])
        ans = max(ans,cur)
    print(ans)
    return

def ABC95_C():
    A, B, C, X, Y = LI()
    if A+B<=C*2:
        ans = A*X+B*Y
    else:
        if X>Y:
            ans = Y*C*2 + min(A,C*2)*(X-Y)
        else:
            ans = X*C*2 + min(B,C*2)*(Y-X)
    print(ans)
    return

def SMTB_D():
    def flag(n,s):
        for l in range(n,N):
            if S[l]==str(s):
                return l
        return N
    N = I()
    S = SI()
    ans = 0
    for i in range(10):
        L1 = flag(0,i)
        for j in range(10):
            L2 = flag(L1+1,j)
            for k in range(10):
                L3 = flag(L2+1,k)
                if L3<N:
                    ans += 1
                    #print(i,j,k)
    print(ans)
    return

def JOI2007_3():
    N = I()
    V = [LI() for _ in range(N)]
    D = set()
    for vx,vy in V:
        D.add((vx,vy))
    ans = 0
    for i in range(N):
        a1, b1 = V[i]
        for j in range(i+1,N):
            a2, b2 = V[j]
            va, vb = a2 - a1, b2 - b1
            if (a1 + vb, b1 - va) in D and (a2 + vb, b2 - va) in D:
                ans = max(ans, va ** 2 + vb ** 2)
            if (a1 - vb, b1 + va) in D and (a2 - vb, b2 + va) in D:
                ans = max(ans, va ** 2 + vb ** 2)
    print(ans)
    return
"""
10
9 4
4 3
1 1
4 2
2 4
5 8
4 0
5 3
0 5
5 2
"""# 10

def square869120Contest():
    def length(a,b,x,y):
        if x>y:
            x,y = y,x
        rep = 0
        if a<x:
            rep += (x-a)*2
        if y<b:
            rep += (b-y)*2
        rep += (y-x)
        return rep
    N = I()
    AB = [LI()for _ in range(N)]
    ans = inf
    for i in range(N):
        s = AB[i][0]
        for j in range(N):
            g = AB[j][1]
            cur = 0
            for k in range(N):
                cur += length(AB[k][0],AB[k][1],s,g)
            ans = min(ans,cur)
    print(ans)
    return

def JOI7_D():
    M = I()
    S = [LI()for _ in range(M)]
    Ss = [(0,0)]
    curx,cury = S[0]
    for sx,sy in S[1:]:
        Ss.append((sx-curx,sy-cury))
        curx = sx; cury = sy
    #print(Ss)
    N = I()
    X = [LI()for _ in range(N)]
    D = set()
    for i in range(N):
        cur = (X[i][0],X[i][1])
        D.add(cur)
    for i in range(N):
        flag = True
        curx, cury = X[i]
        for k in range(M):
            curx += Ss[k][0]
            cury += Ss[k][1]
            #print(curx,cury)
            if not (curx, cury) in D:
                flag = False
                break
        if flag:
            #print(i,X[i])
            ansx = X[i][0] - S[0][0]
            ansy = X[i][1] - S[0][1]
            print(ansx,ansy)
            return
    return

def ABC128_C():
    N, M = LI()
    S = [[]for _ in range(N)]
    for i in range(M):
        s = LI()
        for j in s[1:]:
            S[j-1].append(i)
    P = LI()
    #print(S)
    loop = 2**N
    ans = 0
    for i in range(loop):
        p = [0]*M
        cur = []
        for j in range(N):
            if (1<<j)&i==(1<<j):
                cur.append(j)
        for k in cur:
            for l in S[k]:
                p[l] += 1
        flag = True
        for j in range(M):
            if p[j]%2!=P[j]:
                flag = False
        if flag:
            ans += 1
    print(ans)
    return

def ABC2_D():
    N, M = LI()
    V = set()
    for _ in range(M):
        x,y = LI()
        V.add((x,y))
    loop = 2**N
    ans = 0
    #print(V)
    for i in range(loop):
        cur = []
        for j in range(N):
            if (1<<j)&i==(1<<j):
                cur.append(j+1)
        flag = True
        for k1,k2 in itertools.permutations(cur,2):
            if not ((k1,k2) in V or (k2,k1) in V):
                flag = False
                break
        if flag:
            ans = max(ans,len(cur))
    print(ans)
    return

def JOI7_E():
    R, C = LI()
    A = [LI()for _ in range(R)]
    loop = 2**R
    ans = 0
    for i in range(loop):
        rev = set()
        for j in range(R):
            if (1<<j)&i==(1<<j):
                rev.add(j)
        cur = 0
        for j in range(C):
            s = 0
            for k in range(R):
                if k in rev and A[k][j]==0:
                    s += 1
                elif (not k in rev) and A[k][j]==1:
                    s += 1
            cur += max(s,R-s)
        ans = max(ans,cur)
    print(ans)
    return

def square869120Contest4_B():
    N, K = LI()
    A = LI()
    ans = inf
    loop = 2**(N-1)
    for i in range(loop):
        look = set()
        for j in range(N-1):
            if (1<<j)&i==(1<<j):
                look.add(j+1)
        if len(look)<K-1:
            continue
        high = A[0]
        cur = 0
        flag = True
        for j in range(1,N):
            if not (j in look):
                if A[j]>high:
                    flag = False
                    break
            else:
                if high >= A[j]:
                    cur += (high - A[j] + 1)
                    high += 1
                else:
                    high = A[j]
        #print(look,cur)
        if not flag:
            continue
        ans = min(ans,cur)
    print(ans)
    return

def ABC145_C():
    N = I()
    X = [LI()for _ in range(N)]
    ans = 0
    c = 0
    for x in itertools.permutations(X):
        cur = 0
        c += 1
        for i in range(N-1):
            cur += ((x[i+1][0]-x[i][0])**2 + (x[i+1][1]-x[i][1])**2)**0.5
        ans += cur
    ans /= c
    print(ans)
    return

def ABC150_C():
    N = I()
    T = [i+1 for i in range(N)]
    P = LI()
    Q = LI()
    for i,t in enumerate(itertools.permutations(T)):
        flag_P = True
        flag_Q = True
        for j in range(N):
            if t[j]!=P[j]:
                flag_P = False
            if t[j]!=Q[j]:
                flag_Q = False
        if flag_P:
            a = i
        if flag_Q:
            b = i
    ans = abs(a-b)
    print(ans)
    return

def JOI2009_2():
    d = I()
    N = I()
    M = I()
    D = [I()for _ in range(N-1)]
    K = [I()for _ in range(M)]
    D.append(0)
    D.sort()
    D.append(d)
    ans = 0
    for i in range(M):
        cur = bisect.bisect_right(D,K[i])
        ans += min(K[i]-D[cur-1],D[cur]-K[i])
    print(ans)
    return
"""
20 
4 
4 
12
8 
16 
7 
7 
11 
8
"""#3

def ARC37_C():
    N, K = LI()
    A = LI()
    B = LI()
    B.sort()
    l = 0; r = inf
    while(r-l>1):
        cur = 0
        now = (l+r)//2
        for a in A:
            if a==0:
                cur += N
            else:
                cur += bisect.bisect_right(B,now//a)
        if cur<K:
            l =now
        else:
            r = now
    ans = r
    print(ans)
    return

def ABC27_D():
    def judge(h):
        D = [0]*N
        for i in range(N):
            if h<H[i][0]:
                return False
            cur = (h-H[i][0])//H[i][1]
            if cur>=N:
                cur = N-1
            D[cur] += 1
        s = 0
        #print(D,h)
        for i in range(N):
            s += D[i]
            if s>i+1:
                return False
        return True
    N = I()
    H = [LI()for _ in range(N)]
    l = 0; r = inf
    while(r-l>1):
        now = (l+r)//2
        if judge(now):
            r = now
        else:
            l = now
    ans = r
    print(ans)
    return

def JOI2008_3():
    N, M = LI()
    P = [I()for _ in range(N)]
    P_2 = set()
    for i in range(N+1):
        if i==N:
            p1 = 0
        else:
            p1 = P[i]
        for j in range(N+1):
            if j==N:
                p2 = p1
            else:
                p2 = p1+P[j]
            P_2.add(p2)
    P_2 = list(P_2)
    P_2.sort()
    ans = 0
    for p2 in P_2:
        if M<p2:
            continue
        cur = P_2[bisect.bisect_right(P_2,M-p2)-1]+p2
        ans = max(ans,cur)
    print(ans)
    return
"""
3 21 
16 
11 
2
"""#20

def ABC138_D():
    def bfs(n,edges,s,C):
        W = [-1]*n
        que = deque()
        que.append(s)
        W[s] = C[s]
        rep = W[s]
        while(que):
            now = que.pop()
            nowW = W[now]
            for i in edges[now]:
                if W[i]==-1:
                    que.append(i)
                    W[i] = nowW + C[i]
                    rep += W[i]
        return W
    N, Q = LI()
    V = [[]for _ in range(N)]
    for _ in range(N-1):
        a,b = LI()
        a -= 1; b -= 1
        V[a].append(b)
        V[b].append(a)
    C = [0]*N
    for _ in range(Q):
        p,x = LI()
        C[p-1] += x
    ans = bfs(N,V,0,C)
    print(" ".join(map(str,ans)))
    return

def JOI8_D():
    def dfs(s, n ,rep):
        y, x = s[0],s[1]
        S[y][x] = 0
        if rep < n:
            rep = n
        for i in range(4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
            if ny>=H or ny<0 or nx>=W or nx<0:
                continue
            if S[ny][nx]==1:
                rep = dfs([ny,nx], n + 1, rep)
                #print(ny, nx, rep,n)
        S[y][x] = 1
        #print(rep,y,x)
        return rep
    W = I()
    H = I()
    S = [LI()for _ in range(H)]
    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j]==0:
                continue
            ans = max(ans,dfs((i,j),1,1))
    print(ans)
    return
"""
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
""" #5

def ABC7_C():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]
        def bfsg():
            queue = deque()
            queue.append(s)
            distance[s[0]][s[1]] = 0
            while len(queue):
                y, x = queue.popleft()
                for i in range(4):
                    nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                    if (0 <= nx < w and 0 <= ny < h and maze[ny][nx] != '#'):
                        if distance[ny][nx] <= distance[y][x] + 1:
                            continue
                        queue.append((ny, nx))
                        distance[ny][nx] = distance[y][x] + 1
            return distance

        return bfsg()
    h, w = LI()
    Sy,Sx = LI()
    Gy,Gx = LI()
    C = [SI()for _ in range(h)]
    L = bfs_grid(h,w,[Sy-1,Sx-1],C)
    #print(L)
    ans = L[Gy-1][Gx-1]
    print(ans)
    return

def JOI10_E():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]
        def bfsg():
            queue = deque()
            queue.append(s)
            distance[s[0]][s[1]] = 0
            while len(queue):
                y, x = queue.popleft()
                for i in range(4):
                    nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                    if (0 <= nx < w and 0 <= ny < h and maze[ny][nx] != 'X'):
                        if distance[ny][nx] <= distance[y][x] + 1:
                            continue
                        queue.append((ny, nx))
                        distance[ny][nx] = distance[y][x] + 1
            return distance

        return bfsg()
    H, W, N = LI()
    S = [SI()for _ in range(H)]
    G = defaultdict(set)
    for i in range(H):
        for j in range(W):
            G[S[i][j]] = (i,j)
    ans = 0
    for i in range(N):
        if i==0:
            g = G["1"]
            L = bfs_grid(H,W,G["S"],S)
            ans += L[g[0]][g[1]]
        else:
            g = G[str(i+1)]
            L = bfs_grid(H, W, G[str(i)], S)
            ans += L[g[0]][g[1]]
    print(ans)
    return

def JOI11_E():
    def grid_dfs(s, visited):
        rep = 0
        que = deque()
        que.append(s)
        while(que):
            y, x = que.pop()
            if visited[y][x]:
                continue
            visited[y][x] = True
            cur = y % 2
            for i in range(6):
                ny, nx = y + move[cur][i][0], x + move[cur][i][1]
                if ny >= H + 2 or ny < 0 or nx >= W + 4 or nx < 0:
                    continue
                if S[ny][nx] == 1:
                    rep += 1
                    continue
                que.append([ny, nx])
        return rep
    W, H = LI()
    S = [[0] * (W+4) for _ in range(H+2)]
    for i in range(H):
        S[i+1][2:W+2] = LI()
    move = [[] for _ in range(2)]
    move[0] = [[-1, -1], [-1, 0], [0, -1], [0, 1], [1, -1], [1, 0]]
    move[1] = [[-1, 0], [-1, 1], [0, -1], [0, 1], [1, 0], [1, 1]]

    visited = [[False] * (W + 4) for _ in range(H + 2)]
    ans = grid_dfs((0,0),visited)
    print(ans)
    return

"""
8 5
0 1 1 1 0 1 1 1
0 1 0 0 1 1 0 0
1 0 0 1 1 1 1 1
0 1 0 1 1 0 1 0
0 1 1 0 1 1 0 0
"""#56

def ABC88_D():
    def bfs_grid(h, w, s, maze):
        distance = [[inf] * w for _ in range(h)]
        def bfsg():
            queue = deque()
            queue.append(s)
            distance[s[0]][s[1]] = 0
            while len(queue):
                y, x = queue.popleft()
                for i in range(4):
                    nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                    if (0 <= nx < w and 0 <= ny < h and maze[ny][nx] != '#'):
                        if distance[ny][nx] <= distance[y][x] + 1:
                            continue
                        queue.append((ny, nx))
                        distance[ny][nx] = distance[y][x] + 1
            return distance

        return bfsg()
    H, W = LI()
    S = [SI()for _ in range(H)]
    B = 0
    for s in S:
        for i in range(W):
            if s[i]=="#":
                B += 1
    L = bfs_grid(H,W,(0,0),S)
    if L[H-1][W-1]==inf:
        print(-1)
    else:
        ans = H*W-B-L[H-1][W-1]-1
        print(ans)
    return


import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    ABC88_D()

"""

"""

Submission status: Accepted

Solution code:
import sys
import numpy as np
H,W = map(int, input().split())
read = sys.stdin.read
grid = np.array(list(map(str,read()))).reshape(H,-1)[:,:-1]

black_ind = np.where(grid == '#')

C = np.zeros([H,W],np.int32)
C[black_ind] = 1

num_orig_black = np.count_nonzero(C)

q = [[0,0,1]]

minimum_pass = -1
while q:
	ch,cw,cd = q.pop(0)
	if ch == H-1 and cw == W-1:
		minimum_pass = cd
		break
	if C[ch,cw] == 1:
		continue
	
	C[ch,cw] = 1

	for nh,nw in [[ch+1,cw],[ch-1,cw],[ch,cw+1],[ch,cw-1]]:
		if 0 <= nh < H and 0 <= nw < W:
			if C[nh,nw] == 0:
				q.append([nh,nw,cd+1])

if minimum_pass == -1:
	print(-1)
else:
	print(W*H - minimum_pass - num_orig_black)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys

[H, W] = [int(i) for i in input().split()]

gh = H - 1
gw = W - 1

S = []
for h in range(H):
    S.append(list(input()))

# 最短経路を求める
queue = [(0, 0, 0)]
min_route = 0
while len(queue) > 0:
    (y, x, r) = queue.pop(0)
    if S[y][x] == 'X':
        continue
    S[y][x] = 'X'
    r += 1

    if y == gh and x == gw:
        min_route = r
        break

    # 上下左右の移動可能マスをqueueにpush
    for (dy, dx) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        ny = y + dy
        nx = x + dx
        if ny >= 0 and ny < H and nx >= 0 and nx < W and S[ny][nx] == '.':
            queue.append((ny, nx, r))

if min_route == 0:
    print(-1)
    sys.exit()

#print(min_route)
# 最短経路分以外の白マスの数を回答
white_square = 0
for h in range(H):
    white_square += S[h].count('.')
    white_square += S[h].count('X')
#print(white_square)

ans = white_square - min_route
print(ans)

Submission status: Accepted

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


def bfs(field, d, sx, sy, gx, gy):
    queue = deque([(sx, sy)])
    d[sx][sy] += 1
    
    while queue:
        x, y = queue.popleft()
        if (x, y) == (gx, gy):
            return d[x][y]

        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            
            # field内かつ障害物じゃないかつ未訪問なら追加
            if (0 <= nx <= gx and 0 <= ny <= gy
                and field[nx][ny] != "#" 
                and d[nx][ny] == -1):
                d[nx][ny] = d[x][y] + 1
                queue.append((nx, ny))

def main():
    H,W = map(int, readline().split())
    s = [readline() for i in range(H)]

    #スタートからの距離(-1は未訪問)
    d = [[-1]*W for i in range(H)]

    min_path = bfs(s, d, 0, 0, H-1, W-1)
    if min_path is not None:
        min_path += 1
    else:
        print(-1)
        exit()

    black = 0
    for line in s:
        black += line.count("#")

    ans = H * W - min_path - black
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
area = [list(input()) for i in range(H)]
def calc(area):
    count = 0
    for i in range(H):
        for j in range(W):
            if area[i][j] == '#':
                count += 1
    
    return count

dist = [[-1 for i in range(W)] for i in range(H)]
dist[0][0] = 0
que = [[0,0]]

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

while len(que) != 0:
    idx = que.pop(0)
    
    for i in range(4):
        h = idx[0] + dh[i]
        w = idx[1] + dw[i]
        
        if h >= 0 and h < H and w >= 0 and w < W and dist[h][w] == -1 and area[h][w] != '#':
            que.append([h, w])
            dist[h][w] = dist[idx[0]][idx[1]] + 1
   
neededWhiteNum = dist[H-1][W-1] + 1 
if neededWhiteNum == 0:
    print(-1)
else:
    print(H*W - dist[H-1][W-1] - calc(area) -1)

Submission status: Accepted

Solution code:
def main():
    from queue import Queue
    h,w=map(int,input().split())
    grid=[list(input())  for i in range(h)]
    dx=[-1,0,1,0]
    dy=[0,1,0,-1]

    q=Queue()
    q.put([0,0])
    inf=10**5
    ans=[[inf]*w for i in range(h)]
    ans[0][0]=1
    while q.qsize()!=0:
        p=q.get()
        ny,nx=p[0],p[1]
        for i in range(4):
            y=ny+dy[i]
            x=nx+dx[i]    
            if 0<=x<w and 0<=y<h and ans[y][x]>10**4:
                if grid[y][x]=='.':
                    ans[y][x]=ans[ny][nx]+1
                    q.put([y,x])
    if ans[h-1][w-1]>10**4:
        print(-1)
    else:
        cnt_white=sum([grid[i].count('.') for i in range(h)])
        print(cnt_white-ans[h-1][w-1])

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
sys.setrecursionlimit(3000)

H,W = map(int,input().split())
maze = []
maze.append("#" * (W+2))
for i in range(H):
    k = input()
    maze.append("#" + k + "#")
maze.append("#" * (W+2))

white = 0
for m in maze:
    white += m.count(".")

d = [[1,0],[-1,0],[0,1],[0,-1]]
dist = 0
tovisit = deque()
tovisit.append([1,1]); tovisit.append([-1,-1])
visited = []
def BFS(x,y,dist):
    if x == W and y == H:
        return white - dist -1
    tovisit.popleft()
    visited.append([x,y])
    if x == -1 and y == -1:
        dist += 1
        if len(tovisit) == 0:
            return -1
        tovisit.append([-1,-1])
        return BFS(tovisit[0][0],tovisit[0][1],dist)
    for dx,dy in d:
        if maze[y+dy][x+dx] == ".":
            if [x+dx,y+dy] not in visited and [x+dx,y+dy] not in tovisit:
                tovisit.append([x+dx,y+dy])
    return BFS(tovisit[0][0],tovisit[0][1],dist)

print(BFS(1,1,0))

Submission status: Accepted

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

load=[]
for i in range(0,H):
    for j in range(0,W):
        if S[i][0][j]=='.':
            load.append((i,j))

ans=0
dp=[[500 for i in range(0,W)] for i in range(0,H)]
dp[0][0]=0
q=[]
q.append((0,0))
sub=[]
while q!=[]:
    while q!=[]:
        x=q[0]
        q.remove(x)
        s=x[0]
        t=x[1]
        if (s+1,t) in load and dp[s+1][t]>dp[s][t]+1:
            sub.append((s+1,t))
            dp[s+1][t]=dp[s][t]+1
        if (s,t+1) in load and dp[s][t+1]>dp[s][t]+1:
            sub.append((s,t+1))
            dp[s][t+1]=dp[s][t]+1
        if (s-1,t) in load and dp[s-1][t]>dp[s][t]+1:
            sub.append((s-1,t))
            dp[s-1][t]=dp[s][t]+1
        if (s,t-1) in load and dp[s][t-1]>dp[s][t]+1:
            sub.append((s,t-1))
            dp[s][t-1]=dp[s][t]+1
        if q==[]:
            q=sub
            sub=[]
            break
if dp[H-1][W-1]==500:
    print(-1)
else:
    print(len(load)-dp[H-1][W-1]-1)

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
G=[["#"]*(w+2) for i in range(h+2)]
G[0]=["#"]*(w+2)
for i in range(1,h+1):
  G[i]=["#"]+list(input())+["#"]
G[h+1]=["#"]*(w+2)
a=0
for i in range(h+2):
  for j in range(w+2):
    if G[i][j]==".":
      a=a+1
B=[[0]*(w+2) for i in range(h+2)]
for i in range(h+2):
  for j in range(w+2):
    if G[i][j]=="#":
      B[i][j]=1
INF=10**4
A=[[INF]*(w+2) for i in range(h+2)]
C=[-1,1,0,0]
D=[0,0,-1,1]
sx=1
sy=1
gx=h
gy=w
A[sx][sy]=0
E=deque([sx,sy])
while len(E)>0:
  x=E[0]
  E.popleft()
  y=E[0]
  E.popleft()
  for i in range(4):
    if B[x+C[i]][y+D[i]]==0:
      A[x+C[i]][y+D[i]]=A[x][y]+1
      B[x+C[i]][y+D[i]]=1
      E.append(x+C[i])
      E.append(y+D[i])
if A[gx][gy]==INF:
  print(-1)
else:
  print(a-A[gx][gy]-1)

Submission status: Accepted

Solution code:
import sys
import heapq
import copy
import numpy as np
from collections import deque

h,w=list(map(int,input().split()))
s=np.array([[x for x in input()] for i in range(h)])
d=[[0]*w for i in range(h)]

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

while len(q)>0:
    cnt,hh,ww=deque.popleft(q)

    if hh==h-1 and ww==w-1:
        nblack=np.sum(s=="#",dtype=np.int)
        print(h*w-nblack-cnt)
        exit(0)
    for nh,nw in [[hh+dh,ww+dw] for dh,dw in [[1,0],[-1,0],[0,1],[0,-1]]]:
        if 0>nh or nh>=h or 0>nw or nw>=w or d[nh][nw]==1 or s[nh][nw]=='#':
            continue
        d[nh][nw]=1
        deque.append(q,[cnt+1,nh,nw])

print(-1)

Submission status: Accepted

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

def main():
    H,W = map(int,input().split())
    s = [input() for _ in range(H)]
    isVisited = [[0]*W for _ in range(H)]
    queue = deque([(0,0,1)])

    while queue:
        i,j,count = queue.popleft()

        if 0<= i < H and 0<= j < W and isVisited[i][j] == 0 and s[i][j] == ".":
            isVisited[i][j] = count
            for dy,dx in [(0,1),(1,0),(-1,0),(0,-1)]:
                queue.append((i+dy,j+dx,count+1))
    
    wall_count = 0
    for i in range(H):
        wall_count += s[i].count("#")
    
    if isVisited[-1][-1]:
        print(H*W-wall_count-isVisited[-1][-1])
    else:
        print(-1)
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from collections import deque
    import sys

    input = sys.stdin.readline

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

    bk = 0
    for row in s:
        bk += row.count('#')

    def coods(r, c):
        if r > 0: yield r - 1, c
        if r < h - 1: yield r + 1, c
        if c > 0: yield r, c - 1
        if c < w - 1: yield r, c + 1

    q = deque()
    q.append((0, 0))
    count = [[-1] * w for _ in range(h)]
    count[0][0] = 1
    while q:
        r, c = q.popleft()
        k = count[r][c]
        for nr, nc in coods(r, c):
            nchar = s[nr][nc]
            if nchar == '#': continue
            if count[nr][nc] != -1: continue
            count[nr][nc] = k + 1
            if (nr, nc) == (h - 1, w - 1):
                print(h * w - (k + 1) - bk)
                return
            q.append((nr, nc))
    print(-1)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

H,W = map(int,readline().split())
maze = []
for _ in range(H):
    maze += [list(readline().rstrip().decode())]

visited = [[-1]*W for _ in range(H)]
def bfs():
    queue = deque([[0,0]])
    visited[0][0] = 0
    while queue:
        y, x = queue.popleft()
        if [y, x] == [H-1, W-1]:
            return visited[y][x]
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y+j, x+k
            if 0 <= new_y < H and \
                0 <= new_x < W and\
                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 -1 #ゴールにたどり着けない場合、-1を返す






res = bfs()
if res == -1:
    print(-1)
else:
    count = 0
    for i in range(H):
        for j in range(W):
            if maze[i][j] == ".":
                count += 1

    print(count-res-1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
inp=["#"*(2+w)]

cnt=0

for _ in range(h):
  temp=input()
  inp.append("#"+temp+"#")
  cnt+=temp.count(".")

inp.append("#"*(w+2))
result=[[-1 for _ in range(w+2)] for _ in range(h+2)]
result[1][1]=1

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

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


while not q.empty():
  temp=q.get()
  i=0
  while i <len(dx):
    x=temp[1]+dx[i]
    y=temp[0]+dy[i]
   
    ##print(result)
    if inp[y][x]=="." and result[y][x]==-1:
      
    
      q.put([y,x])
      result[y][x]=result[temp[0]][temp[1]]+1
    i+=1
    
if result[h][w]==-1:
  print(-1)
else:
  print(cnt-result[h][w])

Submission status: Accepted

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

from collections import deque
dxy = [(0,1),(1,0),(0,-1),(-1,0)]
dist = [[0]*W for i in range(H)]
visited = [[0]*W for i in range(H)]
visited[0][0] = 1
q = deque([(0,0)])
while q:
    x,y = q.popleft()
    for dx,dy in dxy:
        nx,ny = x+dx,y+dy
        if not 0 <= nx < W: continue
        if not 0 <= ny < H: continue
        if visited[ny][nx]: continue
        if S[ny][nx] == '#': continue
        visited[ny][nx] = 1
        dist[ny][nx] = dist[y][x] + 1
        q.append((nx,ny))
w = sum(row.count('.') for row in S)
if visited[-1][-1]:
    print(w - 1 - dist[-1][-1])
else:
    print(-1)

Submission status: Accepted

Solution code:
import queue

H,W=map(int,input().split())
c=["#"*(W+2)]+["#"+input()+"#" for _ in range(H)]+["#"*(W+2)]

ans=0
for i in range(H+2):
    for g in range(W+2):
        if c[i][g]==".":
            ans+=1

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

while not que.empty():
    h,w=que.get()
    direction=[(0,-1),(0,1),(1,0),(-1,0)]
    for y,x in direction:
        if c[h+y][w+x]=="." and dist[h+y][w+x]==-1:
            que.put((h+y,w+x))
            dist[h+y][w+x]=dist[h][w]+1

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

Submission status: Accepted

Solution code:
import queue

H, W = map(int, input().split())
s, count = [], 0
for _ in range(H):
    h = list(input())
    count += h.count('.')
    s.append(['#'] + h + ['#'])
s = [['#'] * (W+2)] + s + [['#'] * (W+2)]
around = [[-1, 0], [0, -1], [1, 0], [0, 1]]

ans, que, already = count + 1, queue.Queue(), set([1 + W])
que.put([1, 1, 1])
while not que.empty():
    q = que.get()
    if q[0] == W and q[1] == H:
        ans = q[2]
        break
    else:
        for a in around:
            nextx, nexty = q[0] + a[0], q[1] + a[1]
            if nextx + W*nexty not in already and s[nexty][nextx] == '.':
                que.put([nextx, nexty, q[2] + 1])
                already.add(nextx + W*nexty)

print(count - ans)

Submission status: Accepted

Solution code:
import queue

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

for i in range(H):
    s[i+1]="#"+input()+"#"
    
s[-1]="#"*(W+2)

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

q=queue.Queue()
q.put((1,1))
d=[[-1]*(W+2) for _ in range(H+2)]
d[1][1]=0

while not q.empty():
    pos=q.get()
    l=d[pos[0]][pos[1]]
    for i in range(len(dx)):
        nxt=(pos[0]+dx[i],pos[1]+dy[i])
        if d[nxt[0]][nxt[1]]==-1 and s[nxt[0]][nxt[1]]==".":
            d[nxt[0]][nxt[1]]=l+1
            q.put(nxt)
            
use=d[H][W]+1

cnt=0
for i in range(H+2):
    cnt+=s[i].count(".")



if use!=0:
    print(cnt-use)
else:
    print(-1)