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: Time Limit Exceeded

Solution code:
n,m = map(int,input().split())
from collections import deque
a = []
for _ in range(n):
    a.append(list(input()))

count = 0
for x in a:
    count += x.count("#")
#print(count)

b = [[100000 for i in range(m)] for i in range(n)]
#print(a)

x = [0, 0, -1, 1]
y = [-1, 1, 0, 0]

queue = deque([])
now = [0,0]
b[0][0] = 1
while now != [n-1, m-1]:
    for i in range(4):
        if now[0] + y[i] < 0 or now[0] + y[i] >= n or now[1] + x[i] < 0 or now[1] + x[i] >= m:
            continue
        if a[now[0]+y[i]][now[1]+x[i]] == '.':
            queue.append([now[0]+y[i],now[1]+x[i]])
        b[now[0]+y[i]][now[1]+x[i]] = min(b[now[0]][now[1]] + 1, b[now[0]+y[i]][now[1]+x[i]])
    a[now[0]][now[1]] = "#"
    
    if queue == deque([]):
        print(-1)
        exit()
    now = queue.popleft()


ans = n * m - (b[n-1][m-1] + count)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
#
# H, W = 10, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
# ]

#

H, W = map(int, input().split())
ARR = []

for i in range(H):
    ARR.append(list(input()))


def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    dist = [[0 for j in range(W)] for i in range(H)]

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

    q.append((0, 0))

    while q.__len__() > 0:
        x, y = q.popleft()
        hist[y][x] = 1

        if x == w - 1 and y == h - 1:
            distance = dist[y][x]
            return calculate(h, w,distance, arr)

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            dist[y][x-1] = dist[y][x] + 1
            q.append((x - 1, y))

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            dist[y][x+1] = dist[y][x] + 1
            q.append((x + 1, y))

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            dist[y-1][x] = dist[y][x] + 1
            q.append((x, y - 1))

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            dist[y+1][x] = dist[y][x] + 1
            q.append((x, y + 1))

    return -1


def calculate(h, w, distance, arr):
    total = h * w
    alreadyPaiting = 0

    for s in arr:
        for ss in s:
            if ss == "#":
                alreadyPaiting += 1

    return total - distance - alreadyPaiting


res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = 10, 37

ARR = [
    ".....................................",
    "...#...####...####..###...###...###..",
    "..#.#..#...#.##....#...#.#...#.#...#.",
    "..#.#..#...#.#.....#...#.#...#.#...#.",
    ".#...#.#..##.#.....#...#.#.###.#.###.",
    ".#####.####..#.....#...#..##....##...",
    ".#...#.#...#.#.....#...#.#...#.#...#.",
    ".#...#.#...#.##....#...#.#...#.#...#.",
    ".#...#.####...####..###...###...###..",
    ".....................................",
]



#

H, W = map(int, input().split())
ARR = []

for i in range(H):
    ARR.append(list(input()))


def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    q = deque()

    q.append((0, 0, 1))

    while q.__len__() > 0:
        x, y,currentStep = q.popleft()
        hist[y][x] = 1
        if x == w - 1 and y == h - 1:
            return calculate(h, w, currentStep, arr)

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            q.append((x - 1, y, currentStep+1))

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            q.append((x + 1, y, currentStep+1))

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            q.append((x, y - 1, currentStep+1))

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            q.append((x, y + 1, currentStep+1))


    return -1


def calculate(h, w, distance, arr):
    total = h * w
    alreadyPaiting = 0

    for s in arr:
        for ss in s:
            if ss == "#":
                alreadyPaiting += 1

    return total - distance - alreadyPaiting


res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

#
# H, W = 10, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
# ]


#

H, W = map(int, input().split())
ARR = []

for i in range(H):
    ARR.append(list(input()))


def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    q = deque()

    q.append([0, 0, 0, hist])

    distances = []

    while q.__len__() > 0:

        l = q.popleft()
        x = l[0]
        y = l[1]
        currentStep = l[2]
        hist = l[3]
        hist[y][x] = 1


        if x == w - 1 and y == h - 1:
            distances.append(currentStep + 1)

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            q.append([x - 1, y, currentStep + 1, hist])

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            q.append([x + 1, y, currentStep + 1, hist])

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            q.append([x, y - 1, currentStep + 1, hist])

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            q.append([x, y + 1, currentStep + 1, hist])

    if distances.__len__() == 0:
        return -1
    else:
        return calculate(h, w, min(distances), arr)


def calculate(h, w, distance, arr):
    total = h * w
    alreadyPaiting = 0

    for s in arr:
        for ss in s:
            if ss == "#":
                alreadyPaiting += 1

    return total - distance - alreadyPaiting


res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

#
# H, W = 10, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
# ]


#

H, W = map(int, input().split())
ARR = []

for i in range(H):
    ARR.append(list(input()))


#
# H, W = 20, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
#     ".....................................",
# ]



def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    q = deque()

    q.append((0, 0, 0))

    distances = []

    while q.__len__() > 0:
        x, y, currentStep = q.popleft()
        hist[y][x] = 1

        if x == w - 1 and y == h - 1:
            distances.append(currentStep + 1)

            if currentStep + 1 <= h + w:
                break

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            q.append((x - 1, y, currentStep + 1))

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            q.append((x + 1, y, currentStep + 1))

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            q.append((x, y - 1, currentStep + 1))

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            q.append((x, y + 1, currentStep + 1))

    if distances.__len__() == 0:
        return -1
    else:
        return calculate(h, w, min(distances), arr)


def calculate(h, w, distance, arr):
    total = h * w
    alreadyPaiting = 0

    for s in arr:
        for ss in s:
            if ss == "#":
                alreadyPaiting += 1

    return total - distance - alreadyPaiting


res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

s = [[] for _ in range(h)]
dis = [[-1] * w for _ in range(h)]

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

white_cnt = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            white_cnt += 1

q = deque()
q.append([0, 0, 1])  # x,y,d

while len(q) > 0:
    x, y, d = q.popleft()
    dis[y][x] = d
    dxy = [[0, 1], [0, -1], [1, 0], [-1, 0]]

    for dx, dy in dxy:
        nx = x + dx
        ny = y + dy
        if 0 > nx or w <= nx or 0 > ny or h <= ny:
            continue
        if dis[ny][nx] != -1 or s[ny][nx] == "#":
            continue
        q.append([nx, ny, d + 1])

if dis[h - 1][w - 1] == -1:
    print(-1)
else:
    print(white_cnt - dis[h - 1][w - 1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

#
# H, W = 10, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
# ]


#

H, W = map(int, input().split())
ARR = []

for i in range(H):
    ARR.append(list(input()))


def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    q = deque()

    q.append((0, 0, 0, hist))

    distances = []

    while q.__len__() > 0:
        x, y, currentStep, hist = q.popleft()
        hist[y][x] = 1


        if x == w - 1 and y == h - 1:
            distances.append(currentStep + 1)

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            q.append((x - 1, y, currentStep + 1, hist))

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            q.append((x + 1, y, currentStep + 1, hist))

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            q.append((x, y - 1, currentStep + 1, hist))

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            q.append((x, y + 1, currentStep + 1, hist))

    if distances.__len__() == 0:
        return -1
    else:
        return calculate(h, w, min(distances), arr)


def calculate(h, w, distance, arr):
    total = h * w
    alreadyPaiting = 0

    for s in arr:
        for ss in s:
            if ss == "#":
                alreadyPaiting += 1

    return total - distance - alreadyPaiting


res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

#
# H, W = 10, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
# ]


#

ALREADYPAITING = 0
H, W = map(int, input().split())
ARR = []

for i in range(H):
    l = input()
    ALREADYPAITING += l.count("#")
    ARR.append(l)


def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    q = deque()

    q.append((0, 0, 0, hist))

    distances = []

    while q.__len__() > 0:
        x, y, currentStep, hist = q.popleft()

        if x == w - 1 and y == h - 1:
            distances.append(currentStep + 1)

        hist[y][x] = 1

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            q.append((x - 1, y, currentStep + 1, hist))

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            q.append((x + 1, y, currentStep + 1, hist))

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            q.append((x, y - 1, currentStep + 1, hist))

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            q.append((x, y + 1, currentStep + 1, hist))

    if distances.__len__() == 0:
        return -1
    else:
        return calculate(h, w, min(distances))


def calculate(h, w, distance):
    total = h * w

    # for s in arr:
    #     for ss in s:
    #         if ss == "#":
    #             alreadyPaiting += 1

    return total - distance - ALREADYPAITING


res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
#
# H, W = 10, 37
#
# ARR = [
#     ".....................................",
#     "...#...####...####..###...###...###..",
#     "..#.#..#...#.##....#...#.#...#.#...#.",
#     "..#.#..#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#..##.#.....#...#.#.###.#.###.",
#     ".#####.####..#.....#...#..##....##...",
#     ".#...#.#...#.#.....#...#.#...#.#...#.",
#     ".#...#.#...#.##....#...#.#...#.#...#.",
#     ".#...#.####...####..###...###...###..",
#     ".....................................",
# ]


#
H, W = map(int, input().split())
ARR = []

for i in range(H):
    ARR.append(input())


def calculateDistance(h, w, arr):
    hist = [[0 for j in range(W)] for i in range(H)]

    q = deque()

    q.append((0, 0, 0, hist))

    distances = []

    while q.__len__() > 0:
        x, y, currentStep, hist = q.popleft()

        if x == w-1 and y == h - 1:
            distances.append(currentStep + 1)

        hist[y][x] = 1

        # left
        if x > 0 and (hist[y][x - 1] == 0) and (arr[y][x - 1] == "."):
            q.append((x - 1, y, currentStep + 1, hist))

        # right
        if x < w - 1 and (hist[y][x + 1] == 0) and (arr[y][x + 1] == "."):
            q.append((x + 1, y, currentStep + 1, hist))

        # up
        if y > 0 and (hist[y - 1][x] == 0) and (arr[y - 1][x] == "."):
            q.append((x, y - 1, currentStep + 1, hist))

        # down
        if y < h - 1 and (hist[y + 1][x] == 0) and (arr[y + 1][x] == "."):
            q.append((x, y + 1, currentStep + 1, hist))

    if distances.__len__() == 0:
        return -1
    else:
        return calculate(h,w,min(distances),arr)


def calculate(h, w, distance, arr):
    total = h * w
    alreadyPaiting = 0

    for s in arr:
        for ss in s:
            if ss == "#":
                alreadyPaiting += 1

    return total - distance - alreadyPaiting

res = calculateDistance(H, W, ARR)

print(res)

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin,setrecursionlimit
setrecursionlimit(10**6)
def S(): return stdin.readline().rstrip()
def LI(): return list(map(int,stdin.readline().rstrip().split()))

def BFS(table,s,step,next,w,h):
    if table[h-1][w-1] != -2:
        return
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    nnext = []
    for rep in next:
        for j in range(4):
            nx = rep[0] + dx[j]
            ny = rep[1] + dy[j]
            if nx<0  or ny<0 or w<=nx or h<=ny:
                continue
            else:
                if s[ny][nx]=='#':
                    continue
                if table[ny][nx]==-2 or step+1<table[ny][nx]:
                    table[ny][nx] = step+1
                    nnext.append([nx,ny])
    BFS(table,s,step+1,nnext,w,h)

def main():
    tmp = LI()
    w,h = tmp.pop(),tmp.pop()
    s = [S() for _ in range(h)]
    table = [[-2]*w for _ in range(h)]
    BFS(table,s,0,[[0,0]],w,h)
    step = table[h-1][w-1]
    c = 0
    for rep in s:
        c += rep.count('#')
    ans = w*h-step-c-1
    print(ans)
    return

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
score = H * W
S = [[] for i in range(H)]
for i in range(H):
    for s in input():
        if s == "#":
            score -= 1
        S[i].append(s)


ls = deque([[0, 0, 0]])
dir = [[1,0], [-1,0], [0,1], [0,-1]]
while len(ls) > 0:
    x, y, depth = ls.popleft()

    if x == H-1 and y == W-1:
        print(score-depth-1)
        break
    
    S[x][y] = "#"

    for dx, dy in dir:
        if (x+dx < 0) or (x+dx > H-1) or (y+dy < 0) or (y+dy > W-1):
            continue
        else:
            if S[x+dx][y+dy] == ".":
                ls.append([x+dx, y+dy, depth+1])

else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
h,w=map(int,input().split())
a=[input() for _ in range(h)]
b=[[h*w]*w for _ in range(h)]
b[0][0]=1
d=deque([[0,0]])
while d:
    y,x=d.pop()
    for i,j in([1,0],[-1,0],[0,1],[0,-1]):
        t,u=y+i,x+j
        if h>t>=0<=u<w:
            if a[t][u]=="." and b[t][u]>b[y][x]+1:
                d.append([t,u])
                b[t][u]=b[y][x]+1
print(max(-1,sum([i.count(".") for i in a])-b[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
h,w=map(int,input().split())
a=[input() for _ in range(h)]
b=[[h*w]*w for _ in range(h)]
b[0][0]=1
d=deque([[0,0]])
while d:
    y,x=d.pop()
    for i,j in([1,0],[-1,0],[0,1],[0,-1]):
        t,u=y+i,x+j
        if 0<=t<h and 0<=u<w:
            if a[t][u]=="." and b[t][u]>b[y][x]+1:
                d.append([t,u])
                b[t][u]=b[y][x]+1
c=sum([i.count(".") for i in a])
print(max(-1,c-b[-1][-1]))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
h,w=map(int,input().split())
a=[input() for _ in range(h)]
b=[[h*w]*w for _ in range(h)]
b[0][0]=1
d=deque([[0,0]])
while d:
    y,x=d.pop()
    for i,j in([1,0],[-1,0],[0,1],[0,-1]):
        t,u=y+i,x+j
        if 0<=t<h and 0<=u<w:
            if a[t][u]=="." and b[t][u]>b[y][x]:
                d.append([t,u])
                b[t][u]=b[y][x]+1
c=sum([i.count(".") for i in a])
print(max(-1,c-b[-1][-1]))

Submission status: Time Limit Exceeded

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def bfs(current):
        q = deque()
        q.append([current, 1])
        while q:
            (x, y), dist = q.popleft()
            visited[x][y] = True
            if x == h and y == w:
                return dist
            for i in range(4):
                nx, ny = x + dx[i], y + dy[i]
                if expanded_grid[nx][ny] == '.' and not visited[nx][ny]:
                    q.append([(nx, ny), dist+1])
        return 0

        

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    d = bfs((1, 1))
    if d > 0:
        print(h*w - d - initial_black)
    else:
        print(-1)



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def dfs(current):
        x, y = current
        if x == h and y == w:
            return True
        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]
            if expanded_grid[next_x][next_y] == '.' and not visited[next_x][next_y]:
                res = dfs((next_x, next_y))
                if res:
                    return True

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    print(max(h*w - (h+w-1) - initial_black, 0)) if dfs((1, 1)) else print(-1)



if __name__ == "__main__":
    main()