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:
def cal():
    import queue
    h, w = map(int, input().split())
    s, count = [], 0
    for _ in range(h):
        a = input()
        count += a.count('#')
        s.append(list(a))
    ans = float('inf')
    q = queue.Queue()
    q.put((0, 0, 1))
    while not q.empty():
        c0, c1, c2 = q.get()
        s[c0][c1] = '#'
        if c0 == h-1 and c1 == w-1:
            return h*w-count-c2
        for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            x, y = c0+i, c1+j
            if 0 <= x < h and 0 <= y < w:
                if s[x][y] != '#':
                    q.put((x, y, c2+1))

    return ans

ans = cal()
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue

h, w = map(int, input().split())
s, count = [], 0
for _ in range(h):
    a = input()
    count += a.count('#')
    s.append(list(a))

def cal():
    ans = float('inf')
    q = queue.Queue()
    q.put((0, 0, 1))
    while not q.empty():
        c0, c1, c2 = q.get()
        s[c0][c1] = '#'
        if c0 == h-1 and c1 == w-1:
            return h*w-count-c2
        for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            x, y = c0+i, c1+j
            if 0 <= x < h and 0 <= y < w:
                if s[x][y] != '#':
                    q.put((x, y, c2+1))

    return ans

ans = cal()
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue

h, w = map(int, input().split())
s, count = [], 0
for _ in range(h):
    a = input()
    count += a.count('#')
    s.append(list(a))

def cal():
    ans = float('inf')
    q = queue.Queue()
    q.put((0, 0, 1))
    while not q.empty():
        c0, c1, c2 = q.get()
        s[c0][c1] = '#'
        if c0 == h-1 and c1 == w-1:
            ans = min(ans, h*w-count-c2)
            continue
        for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            x, y = c0+i, c1+j
            if 0 <= x < h and 0 <= y < w:
                if s[x][y] != '#':
                    q.put((x, y, c2+1))

    return ans

ans = cal()
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
h, w = map(int, input().split())
s, count, ans = [], 0, float('inf')
for _ in range(h):
    a = input()
    count += a.count('#')
    s.append(list(a))

q = queue.Queue()
q.put((0, 0, 1))
while not q.empty():
    c0, c1, c2 = q.get()
    s[c0][c1] = '#'
    if c0 == h-1 and c1 == w-1:
        ans = min(ans, h*w-count-c2)
        continue
    for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        x, y = c0+i, c1+j
        if 0 <= x < h and 0 <= y < w:
            if s[x][y] == '#':
                continue
            else:
                q.put([x, y, c2+1])
if ans == float('inf'):
    print(-1)
else:
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w=map(int,input().split())
queue=deque()
s=[list(input()) for _ in range(h)]
seen=[[False]*w for _ in range(h)]
queue.append([0,0])
ans=[[10000000]*w for _ in range(h)]
ans[0][0]=1
for i in range(h*w*1000):
    if len(queue)==0:
        break
    cnt=queue.popleft()
    seen[cnt[0]][cnt[1]]=True
    if cnt[0]!=0:
        if seen[cnt[0]-1][cnt[1]]==False and s[cnt[0]-1][cnt[1]]==".":
            queue.append([cnt[0]-1,cnt[1]])
            ans[cnt[0]-1][cnt[1]]=min(ans[cnt[0]-1][cnt[1]],ans[cnt[0]][cnt[1]]+1)
    if cnt[1]!=0:
        if seen[cnt[0]][cnt[1]-1]==False and s[cnt[0]][cnt[1]-1]==".":
            queue.append([cnt[0],cnt[1]-1])
            ans[cnt[0]][cnt[1]-1]=min(ans[cnt[0]][cnt[1]-1],ans[cnt[0]][cnt[1]]+1)
    if cnt[0]!=h-1:
        if seen[cnt[0]+1][cnt[1]]==False and s[cnt[0]+1][cnt[1]]==".":
            queue.append([cnt[0]+1,cnt[1]])
            ans[cnt[0]+1][cnt[1]]=min(ans[cnt[0]+1][cnt[1]],ans[cnt[0]][cnt[1]]+1)
    if cnt[1]!=w-1:
        if seen[cnt[0]][cnt[1]+1]==False and s[cnt[0]][cnt[1]+1]==".":
            queue.append([cnt[0],cnt[1]+1])
            ans[cnt[0]][cnt[1]+1]=min(ans[cnt[0]][cnt[1]+1],ans[cnt[0]][cnt[1]]+1)
cnt2=0
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            cnt2+=1
if seen[-1][-1]==False:
    print(-1)
else:
    print(cnt2-ans[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque


def LI():
    return list(map(int, input().split()))


def LSH(h):
    return [list(input()) for _ in range(h)]


H, W = LI()
A = LSH(H)
MAP = [[0 for i in range(W)]for j in range(H)]
white = 0
for i in range(H):
    S = A[i]
    for j in range(W):
        if S[j] == "#":
            MAP[i][j] = "#"
        else:
            MAP[i][j] = "."
            white += 1
d = deque()
d.append([0, 0])
looked = [[0 for i in range(W)]for j in range(H)]
looked[0][0] = 1
move = [[1, 0], [0, 1], [-1, 0], [0, -1]]
count = -1

while d:
    h, w = d.popleft()
    for i in move:
        a = h+i[0]
        b = w+i[0]
        if not(0 <= a < H) or not(0 <= b < W) or looked[a][b] == 0 or MAP[a][b] == "#":
            continue
        if a == H-1 and b == W-1:
            count = looked[h][w]+1
            break
        d.append([a, b])
        looked[a][b] = looked[h][w]+1
    if count != -1:
        break
if count == -1:
    print(count)
    sys.exit()

print(white-count)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def bfs(start):
    q = deque([[start]])
    visited = set()
    while q:
        path = q.popleft()
        i, j = path[-1]
        if (i, j) == (H - 1, W - 1):
            return path
        for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ni, nj = i + di, j + dj
            if (
                0 <= ni < H
                and 0 <= nj < W
                and field[ni][nj] != "#"
                and (ni, nj) not in visited
            ):
                new_path = list(path) + [(ni, nj)]
                q.append(new_path)
                visited.add((i, j))


H, W = map(int, input().split())
field = [input() for _ in range(H)]
shortest_path = bfs((0, 0))
if shortest_path is None:
    print(-1)
    exit()
ans = 0
for i in range(H):
    for j in range(W):
        if field[i][j] == "." and (i, j) not in shortest_path:
            ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def pprint():
    [print(row) for row in field]


def bfs(start):
    q = deque([[start]])
    visited = set()
    while q:
        path = q.popleft()
        i, j = path[-1]
        if (i, j) == (H - 1, W - 1):
            return path
        for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            ni, nj = i + di, j + dj
            if (
                0 <= ni < H
                and 0 <= nj < W
                and field[ni][nj] != "#"
                and (ni, nj) not in visited
            ):
                new_path = list(path) + [(ni, nj)]
                q.append(new_path)
            visited.add((i, j))


H, W = map(int, input().split())
field = [input() for _ in range(H)]
shortest_path = bfs((0, 0))
if shortest_path is None:
    print(-1)
    exit()
ans = 0
for i in range(H):
    for j in range(W):
        if field[i][j] == "." and (i, j) not in shortest_path:
            ans += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [(-1,0),(1,0),(0,-1),(0,1)]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.pop()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.append((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [(-1,0),(1,0),(0,-1),(0,1)]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.pop()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = "#",*list(input()),"#"
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [(-1,0),(1,0),(0,-1),(0,1)]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [(-1,0),(1,0),(0,-1),(0,1)]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [[-1,0],[1,0],[0,-1],[0,1]]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in [[-1,0],[1,0],[0,0],[0,-1],[0,1]]:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = 1e15
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [[-1,0],[1,0],[0,0],[0,-1],[0,1]]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main():
    Y, X = map(int,input().split())
    # sy, sx = map(int, input().split())
    # gy, gx = map(int, input().split())
    sy,sx = 1,1
    gy,gx = Y,X
    s = [["#"]*(X+2) for _ in range(Y+2)]
    for y in range(Y):
        s[y+1] = list("#"+input()+"#")
    inf = Y*X
    c = [[inf]*X for _ in range(Y)]
    c[sy-1][sx-1] = 0
    drs = [[-1,0],[1,0],[0,0],[0,-1],[0,1]]
    q = deque([(sy-1, sx-1)])

    while q:
        y,x = q.popleft()
        cost = c[y][x]
        for dx,dy in drs:
            x2 = x+dx
            y2 = y+dy
            if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
                c[y2][x2] = cost+1
                q.appendleft((y2,x2))
    if c[gy-1][gx-1] == inf:
        print("-1")
    else:
        dots = 0
        for s1 in s:
            dots +=s1.count(".")
        print(dots-c[gy-1][gx-1]-1)
        
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [[-1,0],[1,0],[0,0],[0,-1],[0,1]]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.append((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
# AC if using deque
from collections import deque

Y, X = map(int,input().split())
# sy, sx = map(int, input().split())
# gy, gx = map(int, input().split())
sy,sx = 1,1
gy,gx = Y,X
s = [["#"]*(X+2) for _ in range(Y+2)]
for y in range(Y):
    s[y+1] = list("#"+input()+"#")
inf = Y*X
c = [[inf]*X for _ in range(Y)]
c[sy-1][sx-1] = 0
drs = [[-1,0],[1,0],[0,0],[0,-1],[0,1]]
q = deque([(sy-1, sx-1)])

while q:
    y,x = q.popleft()
    cost = c[y][x]
    for dx,dy in drs:
        x2 = x+dx
        y2 = y+dy
        if s[y2+1][x2+1] == "." and c[y2][x2] > cost:
            c[y2][x2] = cost+1
            q.appendleft((y2,x2))
if c[gy-1][gx-1] == inf:
    print("-1")
else:
    dots = 0
    for s1 in s:
        dots +=s1.count(".")
    print(dots-c[gy-1][gx-1]-1)

Submission status: Time Limit Exceeded

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from functools import reduce
from bisect import bisect_left, insort_left
from heapq import heapify, heappush, heappop

INPUT = lambda: sys.stdin.readline().rstrip()
INT = lambda: int(INPUT())
MAP = lambda: map(int, INPUT().split())
S_MAP = lambda: map(str, INPUT().split())
LIST = lambda: list(map(int, INPUT().split()))
S_LIST = lambda: list(map(str, INPUT().split()))

sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7


def main():
    H, W = MAP()
    S = []
    walls = 0
    for _ in range(H):
        line = INPUT()
        walls += line.count('#')
        S.append(line)

    dist = [[INF]*W for _ in range(H)]
    dist[0][0] = 1
    queue = deque([[0, 0]])
    while queue:
        y, x = queue.popleft()
        if y == H - 1 and x == W - 1:
            print(H*W - walls - dist[y][x])
            sys.exit()

        for dy, dx in [(y, x-1), (y-1, x), (y, x+1), (y+1, x)]:
            if 0 <= dy < H and 0 <= dx < W and S[dy][dx] == '.' and dist[dy][dx] > dist[y][x]:
                dist[dy][dx] = dist[y][x] + 1
                queue.append([dy, dx])

    print(-1)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = 0
for i in range(h):
    ans += s[i].count(".")
s = [["#"] + i + ["#"] for i in s]
s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]]
s[h][w] = "$"
pos = [[1, 1, 0]]
while len(pos) > 0:
    x, y, cnt = pos.pop(0)
    if "$" in [s[x-1][y], s[x+1][y], s[x][y+1], s[x][y-1]]:
        print(ans-(cnt+2))
        exit()
    s[x][y] = "~"
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            ans += 1
s = [["#"] + i + ["#"] for i in s]
s = [["#"]*(w+2)] + s + [["#"]*(w+2)]
pos = [[1, 1, 0]]
pos=deque(pos)
while len(pos) > 0:
    x, y, cnt = pos.popleft()
    if x == h and y == w:
        print(ans-(cnt+1))
        exit()
    s[x][y] =0
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
if s[0][0]=="#" or s[h-1][w-1]=="#":
  print(-1)
  exit()
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            ans += 1
s = [["#"] + i + ["#"] for i in s]
s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]]
pos = [[1, 1, 0]]
for i in range(h*w):
  for j in range(len(pos)):
    x, y, cnt = pos[j]
    if x == h and y == w:
        print(ans-(cnt+1))
        sys.exit()
    s[x][y] = "~"
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            ans += 1
s = [["#"] + i + ["#"] for i in s]
s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]]
pos = [[1, 1, 0]]
for i in range(h*w):
  for j in range(len(pos)):
    x, y, cnt = pos[j]
    if x == h and y == w:
        print(ans-(cnt+1))
        sys.exit()
    s[x][y] = "~"
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == ".":
            ans += 1
s = [["#"] + i + ["#"] for i in s]
s = [["#" for i in range(w+2)]] + s + [["#" for i in range(w+2)]]
pos = [[1, 1, 0]]
while len(pos) > 0:
    x, y, cnt = pos.pop(0)
    if x == h and y == w:
        print(ans-(cnt+1))
        sys.exit()
    s[x][y] = "~"
    if s[x-1][y] == ".":
        pos.append([x-1, y, cnt+1])
    if s[x+1][y] == ".":
        pos.append([x+1, y, cnt+1])
    if s[x][y-1] == ".":
        pos.append([x, y-1, cnt+1])
    if s[x][y+1] == ".":
        pos.append([x, y+1, cnt+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
m=[]
for _ in range(h): m.append(list(input()))
black=0
white=0
for i in range(h):
    for j in range(w):
        if m[i][j]=="#": black+=1
white=h*w-black
node=[[0,0,1]]
dx,dy=[-1,0,1,0],[0,1,0,-1]
while node:
    temp=node.pop(0)
    if temp[0]==h-1 and temp[1]==w-1:
        print(h*w-black-temp[2])
        exit()
    m[temp[0]][temp[1]]="#"
    for i in range(4):
        if 0<=temp[0]+dx[i]<h and 0<=temp[1]+dy[i]<w:
            if m[temp[0]+dx[i]][temp[1]+dy[i]]==".":
                node.append([temp[0]+dx[i],temp[1]+dy[i],temp[2]+1])
print(-1)

Submission status: Time Limit Exceeded

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

from collections import deque
def cango(x,y):
    cand =[]
    if x+1<=H-1:
        cand.append((x+1,y))
    if x-1>=0:
        cand.append((x-1,y))
    if y+1<=W-1:
        cand.append((x,y+1))
    if y-1>=0:
        cand.append((x,y-1))
    return cand
    
q = deque([(-1,-1,0,0,0)]) 
been = [[False]*W for _ in range(H)]

reach=False
while q:
    x_old,y_old,x_now,y_now,time = q.popleft()
    been[x_now][y_now]=True
    cand = cango(x_now,y_now)
    
    if x_now==H-1 and y_now==W-1:
        reach=True
        break
    
    for x_new,y_new in cand:
        if not been[x_new][y_new] and s[x_new][y_new]==".":
            q.append((x_now,y_now,x_new,y_new,time+1))
if reach:
    print( sum(ss.count(".") for ss in s)-time-1 )
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
def read():
    H, W = map(int, input().split(' '))
    Ss = []
    for _ in range(H):
        Ss.append(input())
    return H, W, Ss
 
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
 
def add(p1, p2):
    return (p1[0] + p2[0], p1[1] + p2[1])
 
def ans(H, W, Ss):
    if Ss[0][0] == '#':
        print('0,0 #')
        return -1
    ds =[ [-1 for _ in range(W)] for _ in range(H)]
    ds[0][0] = 1
    q = [(0, 0)]
    while q:
        p = q.pop()
        d = ds[p[1]][p[0]]
        for dr in DIRS:
            x, y = add(p, dr)
            if x < 0 or x >= W or y < 0 or y >= H:
                continue # 範囲外へは移動できない
            if Ss[y][x] == '#':
                continue # 行き止まりへは移動できない
            if ds[y][x] >= 0 and ds[y][x] < d + 1: # すでに訪れていて短縮にもなっていない
                continue
            ds[y][x] = d + 1
            q.append((x, y))
    if ds[H-1][W-1] < 0:
        return -1
    # 白マスを数える
    ws = sum([l.count('.') for l in Ss])
    return ws - ds[H-1][W-1]
 
if __name__ == '__main__':
    H, W, Ss = read()
    print(ans(H, W, Ss))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

d = deque([[0, 0]])
dist = [[0] * w for _ in range(h)]
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
goal_flag = False
while d:
    x, y = d.popleft()
    if x == h - 1 and y == w - 1:
        goal_flag = True
        break
    for i in range(4):
        pos_x, pos_y = x + dx[i], y + dy[i]
        if 0 <= pos_x < h and 0 <= pos_y < w and s[pos_x][pos_y] == '.':
            d.append([pos_x, pos_y])
            dist[pos_x][pos_y] = dist[x][y] + 1
    s[x][y] = '#'

if goal_flag:
    print(cnt_white - dist[h-1][w-1] - 1)
else:
    print(-1)

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 = [[-1 for i in range(m)] for i in range(n)]
#print(a)

x = [0, 0, -1, 1]
y = [-1, 1, 0, 0]
now = [0,0]
queue = deque([[0,0]])
b[0][0] = 1
while queue:
    now = queue.popleft()
    if now == [n-1,m-1]:
        print(n * m - (b[n-1][m-1] + count))
        exit()
    a[now[0]][now[1]] = "#"
    for i in range(4):
        if 0 <= now[0] + y[i] < n and 0 <= now[1] + x[i] < m:
            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]] = b[now[0]][now[1]] + 1

print(-1)

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([[0,0]])
b[0][0] = 1
while queue:
    now = queue.popleft()
    a[now[0]][now[1]] = "#"
    for i in range(4):
        if 0 <= now[0] + y[i] < n and 0 <= now[1] + x[i] < m:
            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]] = b[now[0]][now[1]] + 1


if b[n-1][m-1] == 100000:
    print(-1)
    exit()

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

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([[0,0]])
b[0][0] = 1
while queue:
    now = queue.popleft()
    a[now[0]][now[1]] = "#"
    for i in range(4):
        if 0 <= now[0] + y[i] < n and 0 <= now[1] + x[i] < m:
            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]])


if b[n-1][m-1] == 100000:
    print(-1)
    exit()

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

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([[0,0]])
b[0][0] = 1
while queue:
    now = queue.popleft()

    for i in range(4):
        if 0 <= now[0] + y[i] < n and 0 <= now[1] + x[i] < m:
            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 b[n-1][m-1] == 100000:
    print(-1)
    exit()

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

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([[0,0]])
b[0][0] = 1
while queue:
    now = queue.popleft()

    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 b[n-1][m-1] == 100000:
    print(-1)
    exit()

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

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)