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:
# 必要なライブラリのインポート
import queue


def f(x,y):
    if x < 0 or y < 0 or x >= r or y >= c:
        return False
    if m[x][y] == "#":
        return False
    elif not (x,y) in done:
        if (x,y) == (gx,gy):
            return True
        else:
            done.add((x,y))
            q.put((x,y))
            return False
    else:
        return False          

# FIFOキューの作成
q = queue.Queue()

r,c = map(int,input().split())
sx,sy = 1,1
gx,gy = r,c

sx -= 1
sy -= 1
gx -= 1
gy -= 1


m = ["" for _ in range(r)] 
sharp_counter = 0
for i in range(r):
    m[i] = input()
    sharp_counter += m[i].count("#")
    
    
q.put((sx,sy))
done = set()
counter = 1
while True:
    q_list = []
    for _ in range(q.qsize()):
        tx,ty = q.get()
        q_list.append((tx,ty))
        
    for one in q_list:
        tx,ty = one
        flags = [f(tx,ty-1),f(tx,ty+1),f(tx-1,ty),f(tx+1,ty)]
        if sum(flags) == 1:
            print(r*c -sharp_counter -(counter-1)-2)
            break
            
    if sum(flags) == 1:
        break
    else:
        counter += 1

Submission status: Time Limit Exceeded

Solution code:
#%%
def search(x, y, z):
    return [[x-1, y, z+1], [x, y-1, z+1], [x, y+1, z+1], [x+1, y, z+1]]
    
h, w = map(int, input().split())
s = [[] for _ in range(h)]
for i in range(h):
    s[i] = list(input())

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

check = [[0] * w for _ in range(h)]
que = [[0,0,1]]
check[0][0] == 1
flag = False

while len(que) > 0:
    tmp = que.pop(-1)
   #print(tmp)
    for i in search(tmp[0], tmp[1], tmp[2]):
        if 0 <= i[0] <= h-1 and 0 <= i[1] <= w-1 and s[i[0]][i[1]] == '.':
            if check[i[0]][i[1]] == 0:
                que.append(i)
                check[i[0]][i[1]] == 1
    if tmp[0] == h-1 and tmp[1] == w-1:
        key = tmp[2]
        flag = True
        break
#print(key)

if flag:
    print(h*w - sharp - key)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
#Grid Repainting
from collections import deque
import sys
h,w=map(int,input().split())
field=[list(input()) for _ in range(h)]
white=0
for i in range(h):
    for j in range(w):
        if field[i][j]==".":
            white+=1
start=[0,0]
goal=[h-1,w-1]
dx=[1,0,-1,0]
dy=[0,1,0,-1]
count=0
que=deque([[[0,0]]])
field[0][0]="#"
while que:
    q=que.popleft()
    count+=1
    k=[]
    while q:
        p=q.pop()
        x=p[0]
        y=p[1]
        if x==h-1 and y==w-1:
            break
        for i in range(4):
            nx=x+dx[i]
            ny=y+dy[i]
            if 0<=nx and nx<h and 0<=ny and ny<w:
                if field[nx][ny]!="#":
                    k.append([nx,ny])
                    field[nx][ny]="#"
    else:
        que.append(k)
        continue
    break
else:
    print(-1)
    sys.exit()
print(white-count)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import heapq
inf = 10**5
h, w = map(int, input().split())
wall = 0
grid = []
for _ in range(h):
    inp = input()
    wall += inp.count("#")
    grid.append([1 if i == "." else inf for i in inp])
grid = np.array(grid)
cost = np.ones(grid.shape, dtype=int)*inf

todo = [(0, 0)]     #cost, node
heapq.heapify(todo)
seen = np.zeros(grid.shape, dtype=int)

d = ((1, 0),
     (0, 1),
     (-1, 0),
     (0, -1))

while todo:
    c, n = heapq.heappop(todo)
    ny = n//w
    nx = n%w
    seen[ny][nx] = 1
    cost[ny][nx] = c

    for dx, dy in d:
        x, y =dx+nx, dy+ny
        if 0 <= x and x < w and 0 <= y and y < h and seen[y][x] == 0:
            cn = (min(cost[y][x], c+grid[y][x]), x+w*y)
            heapq.heappush(todo, cn)

if cost[-1][-1] >= inf:
    ans = -1
else:
    ans = h*w - (cost[-1][-1]+1) - wall
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, Counter
import sys
H, W = map(int, input().split())
count = 0
grid = ['s' for h in range(H)]
for h in range(H):
    grid[h] = list(input())
    tmp_count = Counter(grid[h])['#']
    if tmp_count == W:
        print(-1)
        sys.exit()
    count += tmp_count

deq = deque([(0, 0)])
visited = [[False for w in range(W)] for h in range(H)]
visited[0][0] = True
route = 0
while deq:
    route += 1
    for _ in range(len(deq)):
        coord = deq.popleft()
        h, w = coord
        visited[h][w] = True
        if coord == (H - 1, W - 1):
            print(H * W - route - count)
            sys.exit()
        if h < H - 1:
            if grid[h + 1][w] != '#' and not visited[h + 1][w]:
                deq.append((h + 1, w))
        if w < W - 1:
            if grid[h][w + 1] != '#' and not visited[h][w + 1]:
                deq.append((h, w + 1))
        if h > 0:
            if grid[h - 1][w] != '#' and not visited[h - 1][w]:
                deq.append((h - 1, w))
        if w > 0:
            if grid[h][w - 1] != '#' and not visited[h][w - 1]:
                deq.append((h, w - 1))

print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque, Counter
import sys
H, W = map(int, input().split())
count = 0
grid = ['s' for h in range(H)]
for h in range(H):
    grid[h] = list(input())
    count += Counter(grid[h])['#']

deq = deque([(0, 0)])
visited = [[False for w in range(W)] for h in range(H)]
visited[0][0] = True
route = 0
while deq:
    route += 1
    for _ in range(len(deq)):
        coord = deq.popleft()
        h, w = coord
        visited[h][w] = True
        if coord == (H - 1, W - 1):
            print(H * W - route - count)
            sys.exit()
        if h < H - 1:
            if grid[h + 1][w] != '#' and not visited[h + 1][w]:
                deq.append((h + 1, w))
        if w < W - 1:
            if grid[h][w + 1] != '#' and not visited[h][w + 1]:
                deq.append((h, w + 1))
        if h > 0:
            if grid[h - 1][w] != '#' and not visited[h - 1][w]:
                deq.append((h - 1, w))
        if w > 0:
            if grid[h][w - 1] != '#' and not visited[h][w - 1]:
                deq.append((h, w - 1))

print(-1)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
ls = [input().rstrip() for _ in range(h)]
ds = [[float('inf') for _ in range(w)] for _ in range(h)]
ds[0][0] = 1

dxdy = [(-1, 0), (1, 0), (0, -1), (0, 1)]


def bfs(x, y):
    for i in range(4):
        dx, dy = dxdy[i]
        nx = x + dx
        ny = y + dy
        if 0 <= nx < w and 0 <= ny < h and ls[ny][nx] == '.':
            if ds[ny][nx] > ds[y][x] + 1:
                ds[ny][nx] = ds[y][x] + 1
                q.append([nx, ny])


q = [[0, 0]]
while q:
    x, y = q.pop()
    bfs(x, y)
d = ds[h - 1][w - 1]
if d < float('inf'):
    s = sum([l.count('.') for l in ls])
    print(s - d)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10**6)

h, w = map(int, input().split())
ls = [input().rstrip() for _ in range(h)]
ds = [[float('inf') for _ in range(w)] for _ in range(h)]
ds[0][0] = 1

dxdy = [(-1, 0), (1, 0), (0, -1), (0, 1)]


def dfs(x, y):
    for i in range(4):
        dx, dy = dxdy[i]
        nx = x + dx
        ny = y + dy
        if 0 <= nx < w and 0 <= ny < h and ls[ny][nx] == '.':
            if ds[ny][nx] > ds[y][x] + 1:
                ds[ny][nx] = ds[y][x] + 1
                dfs(nx, ny)


dfs(0, 0)
d = ds[h - 1][w - 1]
if d < float('inf'):
    s = sum([l.count('.') for l in ls])
    print(s - d)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(200000)
input = sys.stdin.readline

N, M, = map(int, input().split())
L = [list(input().strip()) for _ in range(N)]

m = [[10 ** 18 for _ in range(M)] for _ in range(N)]

def bfs(x, y, c):
    if L[x][y] == "#":
        return

    if m[x][y] <= c:
        return

    m[x][y] = c

    if x + 1 < N:
        bfs(x + 1, y, c + 1)

    if y + 1 < M:
        bfs(x, y + 1, c + 1)

    if x - 1 >= 0:
        bfs(x - 1, y, c + 1)

    if y - 1 >= 0:
        bfs(x, y - 1, c + 1)

bfs(0, 0, 0)

if m[-1][-1] == 10 ** 18:
    print(-1)
    exit()

def dfs(x, y, c):
    if x == 0 and y == 0:
        L[x][y] = "o"
        return True
    for (_x, _y) in [(-1, 0), (0, -1), (1, 0), (0, 1)]:
        if x + _x < N and x + _x >= 0 and y + _y < M and y + _y >= 0:
            if c - 1 == m[x + _x][y + _y]:
                if dfs(x + _x, y + _y, c - 1):
                    L[x][y] = "o"
                    return True
    return False

dfs(N - 1, M - 1, m[-1][-1])

ans = 0
for i in range(N):
    for j in range(M):
        if L[i][j] == ".":
            ans += 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy

h, w = map(int, sys.stdin.readline().split())

maps = [list(sys.stdin.readline().rstrip()) for _ in range(h)]

def calcdist(maps, start, end, h, w):
    nextlist = []
    nextlist.append(start)
    count = 1
    while True:
        nexnex = []
        for i in nextlist:
            if i[0] == end[0] and i[1] == end[1]:
                return count
            if i[0] > 0 and maps[i[0] -1][i[1]] == '.':
                maps[i[0] -1][i[1]] = '#'
                nexnex.append([i[0] -1, i[1]])
            if i[0] < h-1 and maps[i[0] +1][i[1]] == '.':
                maps[i[0] +1][i[1]] = '#'
                nexnex.append([i[0] +1, i[1]])
            if i[1] > 0 and maps[i[0]][i[1]-1] == '.':
                maps[i[0]][i[1]-1] = '#'
                nexnex.append([i[0], i[1]-1])
            if i[1] < w-1 and maps[i[0]][i[1]+1] == '.':
                maps[i[0]][i[1]+1] = '#'
                nexnex.append([i[0], i[1]+1])
        nextlist = nexnex
        count += 1
    return count

kabe = 0

for i in range(h):
    for j in range(w):
        if maps[i][j] == '#':
            kabe += 1

total = 0
dist = calcdist(maps,[0, 0], [h-1, w-1], h, w)

print(h*w - dist - kabe)

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy

h, w = map(int, sys.stdin.readline().split())

maps = [list(sys.stdin.readline().rstrip()) for _ in range(h)]

tmaps = [[0] * w for _ in range(h)]

def calcdist(tmaps, start, end, h, w):
    nextlist = []
    nextlist.append(start)
    count = 1
    while True:
        nexnex = []
        for i in nextlist:
            tmaps[i[0]][i[1]] = count
            if i[0] == end[0] and i[1] == end[1]:
                return count
        for i in nextlist:
            if i[0] > 0 and tmaps[i[0] -1][i[1]] == 0:
                nexnex.append([i[0] -1, i[1]])
            if i[0] < h-1 and tmaps[i[0] +1][i[1]] == 0:
                nexnex.append([i[0] +1, i[1]])
            if i[1] > 0 and tmaps[i[0]][i[1]-1] == 0:
                nexnex.append([i[0], i[1]-1])
            if i[1] < w-1 and tmaps[i[0]][i[1]+1] == 0:
                nexnex.append([i[0], i[1]+1])
        nextlist = list(map(list, set(map(tuple, nexnex))))
        count += 1
    return count

kabe = 0

for i in range(h):
    for j in range(w):
        if maps[i][j] == '#':
            tmaps[i][j] = -1
            kabe += 1

total = 0
dist = calcdist(copy.deepcopy(tmaps),[0, 0], [h-1, w-1], h, w)

print(h*w - dist - kabe)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product

H, W = map(int, input().split())
S = [input() for _ in range(H)]
G = [[float("inf")]*W for _ in range(H)]
G[0][0] = 1

for _, i, j in product(range(H*W), range(H), range(W)) :
    if S[i][j] == "." :
        for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)] :
            if 0 <= i+x < H and 0<= j+y < W :
                G[i][j] = min(1+G[i+x][j+y], G[i][j])

d = sum(s.count(".") for s in S)
a = d-G[-1][-1]
print(-1 if a==-float("inf") else a)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

white = sum(s.count(".") for s in S)

Q = deque([(0, 0, 1)])
while Q:
    h, w, count = Q.popleft()
    if (h, w) == (H - 1, W - 1):
        print(white - count)
        quit()

    for nh, nw in [(h, w + 1), (h, w - 1), (h + 1, w), (h - 1, w)]:
        if not (0 <= nh < H and 0 <= nw < W):
            continue
        if S[nh][nw] == ".":
            S[h][w] = "" # visited
            Q.append((nh, nw, count + 1))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
H, W = [int(i) for i in input().split()]
S = [list(input()) for _ in range(H)]
 
white = sum(s.count(".") for s in S)
 
Q = deque([(0, 0, 1)])
while Q:
    h, w, count = Q.popleft()
    if (h, w) == (H - 1, W - 1):
        print(white - count)
        quit()
 
    S[h][w] = "_"
 
    for nh, nw in [(h, w + 1), (h, w - 1), (h + 1, w), (h - 1, w)]:
        if not (0 <= nh < H and 0 <= nw < W):
            continue
        if S[nh][nw] == ".":
            Q.append((nh, nw, count + 1))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

white = sum(s.count(".") for s in S)

Q = deque([(0, 0, 1)])
while Q:
    h, w, count = Q.popleft()
    if (h, w) == (H - 1, W - 1):
        print(white - count)
        quit()

    S[h][w] = "_"

    for nh, nw in [(h, w + 1), (h, w - 1), (h + 1, w), (h - 1, w)]:
        if not (0 <= nh < H and 0 <= nw < W):
            continue
        if S[nh][nw] == ".":
            Q.append((nh, nw, count + 1))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

white = sum(s.count(".") for s in S)

visited = [[False for _ in range(W)] for _ in range(H)]

Q = deque([(0, 0, 1)])
while Q:
    h, w, count = Q.popleft()
    if (h, w) == (H - 1, W - 1):
        print(white - count)
        quit()

    visited[h][w] = True

    for nh, nw in [(h, w + 1), (h, w - 1), (h + 1, w), (h - 1, w)]:
        if not (0 <= nh < H and 0 <= nw < W):
            continue
        if S[nh][nw] != "#" and not visited[nh][nw]:
            Q.append((nh, nw, count + 1))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
def bfs(S,H,W):
    stk = [(0,0)]
    cnt = 0
    seen = set()
    while True:
        nxt = []
        while stk:
            h,w = stk.pop()
            if(not (0<=h<H and 0<=w<W) or S[h][w]=='#' or (h,w) in seen):
                continue
            elif(h==H-1 and w==W-1):
                break
            seen.add((h,w))
            li=[(1,0),(-1,0),(0,-1),(0,1)]
            for x,y in li:
                nxt.append((h+y,w+x))
        else:
            stk = nxt
            cnt += 1
            continue
        break
    return cnt

H,W = [int(x) for x in input().split()]
S = [list(input()) for _ in range(H)]
wht = 0
for s in S:
    wht += s.count('.')
print(wht-(bfs(S,H,W)+1))

Submission status: Time Limit Exceeded

Solution code:
import queue
H, W = map(int, input().split())
numw = 0
S = []
for i in range(H):
  ss = input()
  numw += ss.count(".")
  S.append(ss)
#print(numw)
D = [[1000000]*W for i in range(H)]
q = queue.Queue()
q.put((0, 0, 0))
D[0][0] = 0
while not(q.empty()):
  i, j, d = q.get()
  if j > 0 and S[i][j-1] == "." and D[i][j-1] >= d:
    D[i][j-1] = d+1
    q.put((i, j-1, d+1))
  if i > 0 and S[i-1][j] == "." and D[i-1][j] >= d:
    D[i-1][j] = d+1
    q.put((i-1, j, d+1))
  if j+1 < W and S[i][j+1] == "." and D[i][j+1] >= d:
    D[i][j+1] = d+1
    q.put((i, j+1, d+1))
  if i+1 < H and S[i+1][j] == "." and D[i+1][j] >= d:
    D[i+1][j] = d+1
    q.put((i+1, j, d+1))
#print(D)
if D[H-1][W-1] == 1000000:
  print(-1)
  exit()
r = numw-D[H-1][W-1]-1
print(r)

Submission status: Time Limit Exceeded

Solution code:
import queue
H, W = map(int, input().split())
numw = 0
S = []
for i in range(H):
  ss = input()
  numw += ss.count(".")
  S.append(ss)
#print(numw)
D = [[1000000]*W for i in range(H)]
q = queue.Queue()
q.put((0, 0, 0))
D[0][0] = 0
while not(q.empty()):
  i, j, d = q.get()
  D[i][j] = d
  if j > 0 and S[i][j-1] == "." and D[i][j-1] > d:
    q.put((i, j-1, d+1))
  if i > 0 and S[i-1][j] == "." and D[i-1][j] > d:
    q.put((i-1, j, d+1))
  if j+1 < W and S[i][j+1] == "." and D[i][j+1] > d:
    q.put((i, j+1, d+1))
  if i+1 < H and S[i+1][j] == "." and D[i+1][j] > d:
    q.put((i+1, j, d+1))
#print(D)
if D[H-1][W-1] == 1000000:
  print(-1)
  exit()
r = numw-D[H-1][W-1]-1
print(r)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
b = 0
l = [0]*h
for k in range(h):
  a = str(input())
  b += a.count('#')
  l[k] = a
#l = [str(input()) for _ in range(h)]

from collections import deque

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

while queue:
  y, x = queue.popleft()
  if y == h-1 and x == w-1:
    print(h*w-visit[y][x]-b)
    exit()
  for i, j in ([-1, 0], [1, 0], [0, 1], [0, -1]):
    new_y, new_x = y+i, x+j
    if (new_x<0) or (new_x>=w) or (new_y<0) or (new_y>=h) or l[new_y][new_x]=='#':
      continue
    else:
      visit[new_y][new_x] = visit[y][x]+1
      queue.append([new_y,new_x])
else:
  print('-1')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(3000)
h,w=map(int,input().split())
s=['#'*(w+2)]+['#'+input()+'#' for _ in [0]*h]+['#'*(w+2)]
l=[[0]*(w+2) for _ in [0]*(h+2)]
for i in range(h+2):
    for j in range(w+2):
        if s[i][j]=='#':
            l[i][j]=-1
def sol(m,n):
    global l
    if l[m][n]>=0:
        for i,j in [(m-1,n),(m+1,n),(m,n-1),(m,n+1)]:
            if l[i][j]==0 and [i,j]!=[1,1]:
                l[i][j]=l[m][n]+1
                sol(i,j)
            elif l[i][j]>l[m][n]+1:
                l[i][j]=l[m][n]+1
                sol(i,j)
sol(1,1)
if l[h][w]==0:print(-1)
else:print(h*w-l[h][w]-(sum(x.count('#') for x in s)-2*h-2*w-4)-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(3000)
h,w=map(int,input().split())
s=['#'*(w+2)]+['#'+input()+'#' for _ in [0]*h]+['#'*(w+2)]
l=[[0]*(w+2) for _ in [0]*(h+2)]
for i in range(h+2):
    for j in range(w+2):
        if s[i][j]=='#':
            l[i][j]=-1
def sol(m,n):
    global l
    if l[m][n]>=0:
        for [i,j] in [[m-1,n],[m+1,n],[m,n-1],[m,n+1]]:
            if l[i][j]==0 and [i,j]!=[1,1]:
                l[i][j]=l[m][n]+1
                sol(i,j)
            elif l[i][j]>l[m][n]+1:
                l[i][j]=l[m][n]+1
                sol(i,j)
sol(1,1)
if l[h][w]==0:print(-1)
else:print(h*w-l[h][w]-(sum(x.count('#') for x in s)-2*h-2*w-4)-1)

Submission status: Time Limit Exceeded

Solution code:
import queue

H,W = map(int, input().split())
#world = [[c for c in input()] for _ in range(H)]
whiteCount = 0

world = []
for i in range(H):
    row = [c for c in input()]
    world.append(row) 
    whiteCount += len([c for c in row if c == '.'])

minRoot = whiteCount + 1

def bfs(x, y, depth, boforeX, beforeY):
    if x == W - 1 and y == H - 1:
        return min(minRoot, depth)

    depth = depth + 1
    appendPosition(x + 1, y, x, y, depth, boforeX, beforeY)
    appendPosition(x - 1, y, x, y, depth, boforeX, beforeY)
    appendPosition(x, y + 1, x, y, depth, boforeX, beforeY)
    appendPosition(x, y - 1, x, y, depth, boforeX, beforeY)

    return minRoot

def appendPosition(newX, newY, currentX, currentY, depth, boforeX, beforeY):
    if newX < 0 or newY < 0 or newX >= W or newY >= H or world[newY][newX] == '#' or (newX == boforeX and newY == beforeY):
        return

    q.put((newX, newY, depth, currentX, currentY))

    
q = queue.Queue()
q.put((0,0,1,-1,-1))

while q.empty() == False:
    position = q.get()
    minRoot = min(minRoot, bfs(*position))

if whiteCount < minRoot:
    print(-1)
else:
    print(whiteCount - minRoot)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

"""
H Wの後に
#.#.
###.
みたいな文字列を受け取る
"""
H,W = map(int,input().split(' '))
MAP = [['#']*(W+1)] + [None]*H

for i in range(1,H+1):
    MAP[i] = ['#'] + list(map(str,input()))
import queue
q = queue.Queue()


MAP[H][W] = 'G'
visited = [None]*(H+1)
for i in range(H+1):
    visited[i] = [False]*(W+1)

d_num = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if MAP[i][j]=='#':
            d_num += 1

def is_okay(x,y):
    if not (0<x<W+1) or not (0<y<H+1):
        return False
    if visited[y][x] or MAP[y][x]=='#':
        return False
    return True

n = 0
q.put([1,1,n])
ans = 10**7 + 7

while not q.empty():
    x,y,n = q.get()
    k = MAP[y][x]

    n += 1
    if k=='G':
        ans = min(ans,n)
        break

    if is_okay(x+1,y): q.put([x+1,y,n])
    if is_okay(x-1,y): q.put([x-1,y,n])
    if is_okay(x,y+1): q.put([x,y+1,n])
    if is_okay(x,y-1): q.put([x,y-1,n])
    visited[y][x] = True

if not ans==10**7 + 7:
    ANS = H*W - ans - d_num
else:
    ANS = -1

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

"""
H Wの後に
#.#.
###.
みたいな文字列を受け取る
"""
H,W = map(int,input().split(' '))
MAP = [['#']*(W+1)] + [None]*H

for i in range(1,H+1):
    MAP[i] = ['#'] + list(map(str,input()))
import queue
q = queue.Queue()


MAP[H][W] = 'G'
visited = [None]*(H+1)
for i in range(H+1):
    visited[i] = [False]*(W+1)

d_num = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if MAP[i][j]=='#':
            d_num += 1

def is_okay(x,y):
    if not (0<x<W+1) or not (0<y<H+1):
        return False
    if visited[y][x] or MAP[y][x]=='#':
        return False
    return True

n = 0
q.put([1,1,n])
ans = 10**7 + 7

while not q.empty():
    x,y,n = q.get()
    k = MAP[y][x]

    n += 1
    if k=='G':
        ans = min(ans,n)
        if ans == H + W - 1:
            break
        continue

    if is_okay(x+1,y): q.put([x+1,y,n])
    if is_okay(x-1,y): q.put([x-1,y,n])
    if is_okay(x,y+1): q.put([x,y+1,n])
    if is_okay(x,y-1): q.put([x,y-1,n])
    visited[y][x] = True

if not ans==10**7 + 7:
    ANS = H*W - ans - d_num
else:
    ANS = -1

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

"""
H Wの後に
#.#.
###.
みたいな文字列を受け取る
"""
H,W = map(int,input().split(' '))
MAP = [['#']*(W+1)] + [None]*H

for i in range(1,H+1):
    MAP[i] = ['#'] + list(map(str,input()))
import queue
q = queue.Queue()


MAP[H][W] = 'G'
visited = [None]*(H+1)
for i in range(H+1):
    visited[i] = [False]*(W+1)

d_num = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if MAP[i][j]=='#':
            d_num += 1

def is_okay(x,y):
    if not (0<x<W+1) or not (0<y<H+1):
        return False
    if visited[y][x] or MAP[y][x]=='#':
        return False
    return True

n = 0
q.put([1,1,n])
ans = 10**7 + 7

while not q.empty():
    x,y,n = q.get()
    k = MAP[y][x]

    n += 1
    if k=='G':
        ans = min(ans,n)
        continue

    if is_okay(x+1,y): q.put([x+1,y,n])
    if is_okay(x-1,y): q.put([x-1,y,n])
    if is_okay(x,y+1): q.put([x,y+1,n])
    if is_okay(x,y-1): q.put([x,y-1,n])
    visited[y][x] = True

if not ans==10**7 + 7:
    ANS = H*W - ans - d_num
else:
    ANS = -1

print(ANS)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

def bfs(point):
    global visit, s
    while point.qsize() > 0:
        hh, ww = point.get()
        h_w_list = [[hh + 1, ww], [hh - 1, ww], [hh, ww + 1], [hh, ww - 1]]
        min_num = inf
        for h_, w_ in h_w_list:
            if (h_ in range(h)) & (w_ in range(w)):
                min_num = min(min_num, visit[h_][w_])
                if s[h_][w_] == ".":
                    if visit[h_][w_] == inf:                    
                        point.put([h_, w_])
        if visit[hh][ww] == inf:
            visit[hh][ww] = min_num + 1

    
inf = 10 ** 9    
h, w = map(int, input().split())
s = []
point_num = 0
for _ in range(h):
    k = input()
    point_num += k.count(".")
    s.append(list(k))
visit = [[inf for _ in range(w)] for _ in range(h)]
point = Queue()
point.put([0, 0])
visit[0][0] = 0
bfs(point)
ans = point_num - visit[-1][-1] - 1
if ans < 0:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

def bfs(point):
    global visit, s
    while point.qsize() > 0:
        hh, ww = point.get()
        if visit[hh][ww] == inf:
            visit[hh][ww] = calc_min(hh, ww)
        h_w_list = [[hh + 1, ww], [hh - 1, ww], [hh, ww + 1], [hh, ww - 1]]
        for h_, w_ in h_w_list:
            if (h_ in range(h)) & (w_ in range(w)):
                if s[h_][w_] == ".":
                    if visit[h_][w_] == inf:                    
                        point.put([h_, w_])
        
        

def calc_min(hh, ww):
    h_w_list = [[hh + 1, ww], [hh - 1, ww], [hh, ww + 1], [hh, ww - 1]]
    min_num = inf
    for h_, w_ in h_w_list:
        if (h_ in range(h)) & (w_ in range(w)):
            min_num = min(min_num, visit[h_][w_])
    return min_num + 1
    
inf = 10 ** 9    
h, w = map(int, input().split())
s = []
point_num = 0
for _ in range(h):
    k = input()
    point_num += k.count(".")
    s.append(list(k))
visit = [[inf for _ in range(w)] for _ in range(h)]
point = Queue()
point.put([0, 0])
visit[0][0] = 0
bfs(point)
ans = point_num - visit[-1][-1] - 1
if ans < 0:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

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

# bfs 
C[0][0] = 0
pre_list = [(0,0)]
count = 0
 
while C[H-1][W-1] == '.':
    count += 1
    next_list = []
    for y,x in pre_list:
        for i,j in ((1,0),(0,-1),(0,1),(-1,0)):
            if y+i < 0 or x+j < 0 or y+i >= H or x+j >= W:
                continue
            if C[y+i][x+j] == '.':
                C[y+i][x+j] = count
                next_list.append((y+i,x+j))
    pre_list = next_list
black = 0
for h in C:
    for v in h:
        if v == "#":
            black += 1
print(H*W-black-count-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
way = [[False] * W for _ in range(H)]
dist = [(0,1),(1,0),(0,-1),(-1,0)]
q = deque([[0, 0, 1]])
cnt = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == ".":
            cnt += 1
while q:
    y,x,cost = q.popleft()
    way[y][x] = True
    if y == H-1 and x == W-1:
        print(cnt-cost)
        sys.exit(0)    
    for dy, dx in dist:
        ny,nx = y+dy,x+dx
        if ny >=0 and ny < H and nx >= 0 and nx < W and not way[ny][nx] and s[ny][nx] == ".":
            q.append([ny, nx, cost+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
way = [[False]*W for _ in range(H)]
dist = [(0,1),(1,0),(0,-1),(-1,0)]
q = deque([[0, 0, 1]])
cnt = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == ".":
            cnt += 1
while q:
    y,x,cost = q.popleft()
    way[y][x] = True
    if y == H-1 and x == W-1:
        print(cnt-cost)
        sys.exit(0)
    if s[y][x] == ".":
        for dy, dx in dist:
            ny,nx = y+dy,x+dx
            if ny >=0 and ny < H and nx >= 0 and nx < W and not way[ny][nx] and s[ny][nx] == ".":
                q.append([ny, nx, cost+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
way = [[False]*W for _ in range(H)]
dist = [[0,1],[1,0],[0,-1],[-1,0]]
q = deque([[0, 0, 1]])
cnt = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == ".":
            cnt += 1
while q:
    now = q.popleft()
    way[now[0]][now[1]] = True
    if now[0] == H-1 and now[1] == W-1:
        print(cnt-now[2])
        sys.exit(0)
    if s[now[0]][now[1]] == ".":
        for dy, dx in dist:
            if now[0]+dy >=0 and now[0]+dy < H and now[1]+dx >= 0 and now[1]+dx < W and not way[now[0]+dy][now[1]+dx] and s[now[0] + dy][now[1] + dx] == ".":
                q.append([now[0] + dy, now[1] + dx,now[2]+1])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
h,w=map(int,input().split())
field=[list(input()) for _ in range(h)]
count=0
queue=deque([[0,0,0]])
for i in range(h):
    for j in range(w):
        if field[i][j]=='.':
            count+=1
def bfs(x,y,k):
    if (not 0<=x<h) or (not 0<=y<w):
        return
    if field[x][y]=='#':
        return
    if visit[x][y]==1:
        return
    queue.append([x,y,k+1])
visit=[[0]*w for _ in range(h)]
while queue:
    x,y,k=queue.popleft()
#    print(queue)
#    print(field)
    if x==h-1 and y==w-1:
        print(count-k-1)
        sys.exit()
    
    visit[x][y]=1
    bfs(x+1,y,k)
    bfs(x-1,y,k)
    bfs(x,y-1,k)
    bfs(x,y+1,k)
if visit[h-1][w-1]==0:
    print(-1)
else:
    print(count-k-1)