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:
from collections import deque
 
h,w=[int(x) for x in input().rstrip().split()]
l=[[s for s in input()]for i in range(h)]

black=sum(s.count("#") for s in l)
dist=[[False for j in range(w)] for i in range(h)]
done=[[float('inf') for j in range(w)] for i in range(h)]
move=[[1,0],[-1,0],[0,1],[0,-1]]

def bfs():
  stack=deque([[0,0]])
  done[0][0]=0
  while(stack):
    x,y=stack.popleft()
    dist[y][x]=True
    
    for dx,dy in move:
      mx,my=x+dx,y+dy
      if (0<=my<=h-1) and (0<=mx<=w-1) and l[my][mx]=="." and dist[my][mx]==False:
        done[my][mx]=done[y][x]+1
        stack.append([mx,my])
  return done[h-1][w-1]
 
if bfs()!=float('inf'):print(h*w-done[h-1][w-1]-black-1)
else:print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
h,w=[int(x) for x in input().rstrip().split()]
l=[[s for s in input()]for i in range(h)]

black=sum(s.count("#") for s in l)
dist=[[False for j in range(w)] for i in range(h)]
done=[[float('inf') for j in range(w)] for i in range(h)]
move=[[1,0],[-1,0],[0,1],[0,-1]]

def bfs():
  stack=deque([[0,0]])
  done[0][0]=0
  while(stack):
    x,y=stack.popleft()
    dist[y][x]=True

    if y==h-1 and x==w-1:
        return done[h-1][w-1]

    for dx,dy in move:
      mx,my=x+dx,y+dy
      if (0<=my<=h-1) and (0<=mx<=w-1) and l[my][mx]=="." and dist[my][mx]==False:
        done[my][mx]=done[y][x]+1
        stack.append([mx,my])
  return done[h-1][w-1]
 
if bfs()!=float('inf'):print(h*w-done[h-1][w-1]-black-1)
else:print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
 
h,w=[int(x) for x in input().rstrip().split()]
l=[[s for s in input()]for i in range(h)]

black=sum(s.count("#") for s in l)
dist=[[False for j in range(w)] for i in range(h)]
done=[[float('inf') for j in range(w)] for i in range(h)]
move=[[1,0],[-1,0],[0,1],[0,-1]]

def bfs():
  stack=[[0,0]]
  done[0][0]=0
  while(stack):
    x,y=stack.pop(0)
    dist[y][x]=True

    if y==h-1 and x==w-1:
        return done[h-1][w-1]

    for dx,dy in move:
      mx,my=x+dx,y+dy
      if (0<=my<=h-1) and (0<=mx<=w-1) and l[my][mx]=="." and dist[my][mx]==False:
        done[my][mx]=done[y][x]+1
        stack.append([mx,my])
  return done[h-1][w-1]
 
if bfs()!=float('inf'):print(h*w-done[h-1][w-1]-black-1)
else:print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
 
h,w=[int(x) for x in input().rstrip().split()]
l=[]
black=0
for i in range(h):
  s=[x for x in input()]
  l.append(s)

black=sum(s.count("#") for s in l)
dist=[[False for j in range(w)] for i in range(h)]
done=[[float('inf') for j in range(w)] for i in range(h)]
move=[[1,0],[-1,0],[0,1],[0,-1]]

def bfs():
  stack=[[0,0]]
  done[0][0]=0
  while(stack):
    x,y=stack.pop(0)
    dist[y][x]=True
   
    for dx,dy in move:
      mx,my=x+dx,y+dy
      if not(0<=my<=h-1) or not(0<=mx<=w-1):
        continue
      if l[my][mx]=="#" or dist[my][mx]==True:
        continue
      done[my][mx]=done[y][x]+1
      stack.append([mx,my])
    
      if my==h-1 and mx==w-1:
        return True
  return False
 
if bfs()==1:
  print(h*w-done[h-1][w-1]-black-1)
else:
  print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
 
h,w=[int(x) for x in input().rstrip().split()]
l=[]
black=0
for i in range(h):
  s=[x for x in input()]
  l.append(s)
 
black+=sum(map(lambda x:x.count('#'),l))
 
dist=[[False]*w for i in range(h)]
done=[[float('inf')]*w for i in range(h)]
 

move=[[1,0],[-1,0],[0,1],[0,-1]]
def bfs():
  stack=[[0,0]]
  done[0][0]=0
  while(stack):
    x,y=stack.pop(0)
    dist[y][x]=True
   
    for dx,dy in move:
      mx=x+dx
      my=y+dy

      if not(0<=my<=h-1) or not(0<=mx<=w-1) or l[my][mx]=="#" or dist[my][mx]==True:
        continue
 
      done[my][mx]=done[y][x]+1
      stack.append([mx,my])
    
      if my==h-1 and mx==w-1:
        return True

  return False
 
if __name__=="__main__":
  if bfs()==1:
    print(h*w-done[h-1][w-1]-black-1)
  else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int, input().split())
field = []
countd = 0
for _ in range(H):
    ls = []
    st = str(input())
    for ss in st:
        ls.append(ss)
        if ss =='.':
            countd += 1
    field.append(ls)

from collections import deque

dis = [[float('inf')]*51 for i in range(51)]
que = deque([])
que.append([0,0,0])
dis[0][0] = 0
while len(que) > 0:
    pre = que.popleft()
    d = pre[0]
    x = pre[1]
    y = pre[2]
    for dx in [-1,1]:
        for dy in [-1,1]:
            if 0<=x+dx<=H-1:
                if field[x+dx][y]=='.':
                    dis[x+dx][y] = d+1
                    que.append([d+1,x+dx,y])
            if 0<=y+dy<=W-1:
                if field[x][y+dy]=='.':
                    dis[x][y+dy] = d+1
                    que.append([d+1,x,y+dy])

an = dis[H-1][W-1]
if an ==float('inf'):
    print(-1)
else:
    print(countd-an-1)

Submission status: Time Limit Exceeded

Solution code:
import sys

h,w=[int(x) for x in input().rstrip().split()]
l=[]
black=0
for i in range(h):
  s=[x for x in input()]
  l.append(s)

black+=sum(map(lambda x:x.count('#'),l))

dist=[[False]*w for i in range(h)]


def bfs():
  cnt=1
  stack=[[0,0,cnt]]

  while(stack):
    x,y,cnt=stack.pop(0)
    dist[y][x]=True
    
    move=[[x+1,y],[x-1,y],[x,y+1],[x,y-1]]

    for mx,my in move:
      if not(0<=my<=h-1) or not(0<=mx<=w-1) or l[my][mx]=="#" or dist[my][mx]==True:
        continue

      
      stack.append([mx,my,cnt+1])
    
      if my==h-1 and mx==w-1:
        print(h*w-cnt-black-1)
        sys.exit()
  print(-1)

if __name__=="__main__":
  bfs()

Submission status: Time Limit Exceeded

Solution code:
import sys

h,w=[int(x) for x in input().rstrip().split()]
l=[]
black=0
for i in range(h):
  s=[x for x in input()]
  l.append(s)

black+=sum(map(lambda x:x.count('#'),l))

dist=[[False]*w for i in range(h)]
done=[[float('inf')]*w for i in range(h)]

cnt=0
def bfs():
  stack=[[0,0]]
  done[0][0]=0
  while(stack):
    x,y=stack.pop(0)
    dist[y][x]=True
    
    move=[[x+1,y],[x-1,y],[x,y+1],[x,y-1]]

    for mx,my in move:
      if not(0<=my<=h-1) or not(0<=mx<=w-1) or l[my][mx]=="#" or dist[my][mx]==True:
        continue

      done[my][mx]=done[y][x]+1
      stack.append([mx,my])
    
      if my==h-1 and mx==w-1:
        print(h*w-done[my][mx]-black-1)
        sys.exit()
  print(-1)

if __name__=="__main__":
  bfs()

Submission status: Time Limit Exceeded

Solution code:
import sys

h,w=[int(x) for x in input().rstrip().split()]
l=[]
black=0
for i in range(h):
  s=[x for x in input()]
  l.append(s)
  black+=s.count("#")

dist=[[False]*w for i in range(h)]
done=[[float('inf')]*w for i in range(h)]

cnt=0
def bfs():
  stack=[[0,0]]
  done[0][0]=0
  while(stack):
    x,y=stack.pop(0)
    dist[y][x]=True
    
    move=[[x+1,y],[x-1,y],[x,y+1],[x,y-1]]

    for mx,my in move:
      if not(0<=my<=h-1) or not(0<=mx<=w-1) or l[my][mx]=="#" or dist[my][mx]==True:
        continue

      done[my][mx]=done[y][x]+1
      stack.append([mx,my])
    
      if my==h-1 and mx==w-1:
        print(h*w-done[my][mx]-black-1)
        sys.exit()
  print(-1)

if __name__=="__main__":
  bfs()

Submission status: Time Limit Exceeded

Solution code:
import sys

h,w=[int(x) for x in input().rstrip().split()]
l=[]
black=0
for i in range(h):
  s=[x for x in input()]
  l.append(s)
  for j in s:
    if j=="#":
      black+=1

dist=[[False]*w for i in range(h)]
done=[[float('inf')]*w for i in range(h)]

cnt=0
def bfs():
  stack=[[0,0]]
  done[0][0]=0
  while(stack):
    x,y=stack.pop(0)
    dist[y][x]=True
    
    move=[[x+1,y],[x-1,y],[x,y+1],[x,y-1]]

    for mx,my in move:
      if not(0<=my<=h-1) or not(0<=mx<=w-1) or l[my][mx]=="#" or dist[my][mx]==True:
        continue

      done[my][mx]=done[y][x]+1
      stack.append([mx,my])
    
      if my==h-1 and mx==w-1:
        print(h*w-done[my][mx]-black-1)
        sys.exit()
  print(-1)


if __name__=="__main__":
  bfs()

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
w += 2
L=['#']*w
for _ in range(h):
    l=list(input())
    L += ['#']+l+['#']
L += ['#']*w
num=L.count('.')
x=w+1
y=(h+1)*w-2
k=1     
L[x]=k
while L[y]=='.':
    k += 1
    for i in range(w,(h+1)*w):
        if L[i]=='.':
            if L[i-1]==k-1 or L[i+1]==k-1 or L[i-w]==k-1 or L[i+w]==k-1: 
                L[i]=k

ans=L[y]
print(num-ans)

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
w += 2
L=['#']*w
for _ in range(h):
    l=list(input())
    L += ['#']+l+['#']
L += ['#']*w

def route(x,y):
    k=1     
    L[x]=k
    while L[y]=='.':
        k += 1
        for i in range(w,(h+1)*w):
            if L[i]=='.':
                if L[i-1]==k-1 or L[i+1]==k-1 or L[i-w]==k-1 or L[i+w]==k-1:
                        L[i]=k
    return L[y]
num=L.count('.')
ans=route(w+1,(h+1)*w-2)
print(num-ans)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue

R, C = map(int, input().split())
sy, sx = 1, 1
gy, gx = R, C

field = [["#"] * (C + 2)] + \
        [list("#" + input() + "#") for i in range(R)] + \
        [["#"] * (C + 2)]
dxy = [(0,1), (0,-1), (1,0), (-1,0)]
flg = False
cnt = 0

dot_num = sum(r.count('.') for r in field)

q = Queue()
q.put([sy, sx])
field[sy][sx] = 0

while flg == False:
    yx = q.get()
    cnt = field[yx[0]][yx[1]]
    for dy, dx in dxy:
        y_n, x_n = yx[0] + dy, yx[1] + dx
        if y_n == gy and x_n == gx:
            field[y_n][x_n] = cnt + 1
            flg = True
            print(dot_num - (cnt+2))
            break
        if field[y_n][x_n] == '#':
            continue
        if field[y_n][x_n] == '.':
            q.put([y_n, x_n])
            field[y_n][x_n] = cnt + 1
    if flg:
        break
if flg == False:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
import itertools
import numpy as np

R, C = map(int, input().split())
sy, sx = 1, 1
gy, gx = R, C

field = [["#"] * (C + 2)] + \
        [list("#" + input() + "#") for i in range(R)] + \
        [["#"] * (C + 2)]
dxy = [(0,1), (0,-1), (1,0), (-1,0)]
flg = False
cnt = 0

field_1d = list(itertools.chain.from_iterable(field))
field01 = [1 if i == '.' else 0 for i in field_1d]
dot_num = np.array(field01).sum()

q = Queue()
q.put([sy, sx])
field[sy][sx] = 0

while flg == False:
    yx = q.get()
    cnt = field[yx[0]][yx[1]]
    for dy, dx in dxy:
        y_n, x_n = yx[0] + dy, yx[1] + dx
        if y_n == gy and x_n == gx:
            field[y_n][x_n] = cnt + 1
            flg = True
            print(dot_num - (cnt+2))
            break
        if field[y_n][x_n] == '#':
            continue
        if field[y_n][x_n] == '.':
            q.put([y_n, x_n])
            field[y_n][x_n] = cnt + 1
    if flg:
        break
if flg == False:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
import itertools
import numpy as np

R, C = map(int, input().split())
sy, sx = 1, 1
gy, gx = R, C

field = [["#"] * (C + 2)] + \
        [list("#" + input() + "#") for i in range(R)] + \
        [["#"] * (C + 2)]
dxy = [(0,1), (1,0), (0,-1), (-1,0)]
flg = False
cnt = 0

field_1d = list(itertools.chain.from_iterable(field))
field01 = [1 if i == '.' else 0 for i in field_1d]
dot_num = np.array(field01).sum()

q = Queue()
q.put([sy, sx])
field[sy][sx] = 0

while flg == False:
    yx = q.get()
    cnt = field[yx[0]][yx[1]]
    for dy, dx in dxy:
        y_n, x_n = yx[0] + dy, yx[1] + dx
        if y_n == gy and x_n == gx:
            field[y_n][x_n] = cnt + 1
            flg = True
            print(dot_num - (cnt+2))
        if field[y_n][x_n] == '#':
            continue
        if field[y_n][x_n] == '.':
            q.put([y_n, x_n])
            field[y_n][x_n] = cnt + 1
if flg == False:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
import itertools
import numpy as np

R, C = map(int, input().split())
sy, sx = 1, 1
gy, gx = R, C

field = [["#"] * (C + 2)] + \
        [list("#" + input() + "#") for i in range(R)] + \
        [["#"] * (C + 2)]
dxy = [(0,1), (0,-1), (1,0), (-1,0)]
flg = False
cnt = 0

field_1d = list(itertools.chain.from_iterable(field))
field01 = [1 if i == '.' else 0 for i in field_1d]
dot_num = np.array(field01).sum()

q = Queue()
q.put([sy, sx])
field[sy][sx] = 0

while flg == False:
    yx = q.get()
    cnt = field[yx[0]][yx[1]]
    for dy, dx in dxy:
        y_n, x_n = yx[0] + dy, yx[1] + dx
        if y_n == gy and x_n == gx:
            field[y_n][x_n] = cnt + 1
            flg = True
            print(dot_num - (cnt+2))
        if field[y_n][x_n] == '#':
            continue
        if field[y_n][x_n] == '.':
            q.put([y_n, x_n])
            field[y_n][x_n] = cnt + 1
if flg == False:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

s = []
cnt = 0
for _ in range(h):
    tmp = list(input())
    cnt += tmp.count("#")
    s.append(tmp)

pos = [0, 0]
ans = 1
direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
queue = deque()
queue.append(pos)
queue.append(ans)
check = [[False for _ in range(w)] for _ in range(h)]
while queue:
    pos = queue.popleft()
    ans = queue.popleft()
    check[pos[0]][pos[1]] = True
    ans += 1
    for dy, dx in direction:
        y = pos[0] + dy
        x = pos[1] + dx
        if x == -1 or x == w or y == -1 or y == h:
            continue
        if check[y][x]:
            continue
        if s[y][x] == "#":
            continue
        if y == h - 1 and x == w - 1:
            print(h * w - cnt - ans)
            exit()
        queue.append([y, x])
        queue.append(ans)
    
else:
    print(-1)
    exit()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import numpy as np

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

s = []
cnt = 0
for _ in range(h):
    tmp = list(input())
    cnt += tmp.count("#")
    s.append(tmp)

pos = [0, 0]
ans = 1
direction = [[0, 1], [0, -1], [1, 0], [-1, 0]]
queue = deque()
queue.append(pos)
queue.append(ans)
check = np.zeros([h, w], dtype = bool)
while queue:
    pos = queue.popleft()
    ans = queue.popleft()
    check[pos[0]][pos[1]] = True
    ans += 1
    for dy, dx in direction:
        y = pos[0] + dy
        x = pos[1] + dx
        if x == -1 or x == w or y == -1 or y == h:
            continue
        if check[y][x]:
            continue
        if s[y][x] == "#":
            continue
        if y == h - 1 and x == w - 1:
            print(h * w - cnt - ans)
            exit()
        queue.append([y, x])
        queue.append(ans)
    
else:
    print(-1)
    exit()

Submission status: Time Limit Exceeded

Solution code:
import collections
def bfs(G,l):
    l.append([1,1])
    visited = [[0] * len(G[0]) for i in range(len(G))]
    chk = 0
    G[1][1] = 0
    while(len(l)):
        now = l.popleft()
        visited[now[0]][now[1]] = 1
        if now == [len(G)-2,len(G[0])-2]:
            chk = 1
            break

        if G[now[0]][now[1]+1] != "#" and visited[now[0]][now[1]+1] == 0:
            l.append([now[0],now[1]+1])
            G[now[0]][now[1]+1] = min(G[now[0]][now[1]] + 1,G[now[0]][now[1]+1])

        if G[now[0]][now[1]-1] != "#" and visited[now[0]][now[1]-1] == 0:
            l.append([now[0],now[1]-1])
            G[now[0]][now[1]-1] = min(G[now[0]][now[1]] + 1,G[now[0]][now[1]-1])

        if G[now[0]+1][now[1]] != "#" and visited[now[0]+1][now[1]] == 0:
            l.append([now[0]+1,now[1]])
            G[now[0]+1][now[1]] = min(G[now[0]][now[1]] + 1,G[now[0]+1][now[1]])

        if G[now[0]-1][now[1]] != "#" and visited[now[0]-1][now[1]] == 0:
            l.append([now[0]-1,now[1]])
            G[now[0]-1][now[1]] = min(G[now[0]][now[1]]+1,G[now[0]-1][now[1]])
    return chk

[h,w] = [int(i) for i in input().split()]
s = [["#"] * (w+2)]
whites = 0
for i in range(h):
    ls = ["#"]
    tmp = input()
    for j in range(len(tmp)):
        if tmp[j] == ".":
            ls.append(200)
        else:
            ls.append(tmp[j])
    ls.append("#")
    whites += tmp.count(".")
    s.append(ls)
s.append(["#"] * (w+2))
l = collections.deque()

if bfs(s,l):
    print(whites - s[h][w]-1)
    
else:
    print(-1)
#print(s)

Submission status: Time Limit Exceeded

Solution code:
import collections
def bfs(G,l):
    l.append([1,1])
    visited = [[0] * len(G[0]) for i in range(len(G))]
    chk = 0
    G[1][1] = 0
    while(len(l)):
        now = l.popleft()
        visited[now[0]][now[1]] = 1
        if now == [len(G)-2,len(G[0])-2]:
            chk = 1

        if G[now[0]][now[1]+1] != "#" and visited[now[0]][now[1]+1] == 0:
            l.append([now[0],now[1]+1])
            G[now[0]][now[1]+1] = min(G[now[0]][now[1]] + 1,G[now[0]][now[1]+1])

        if G[now[0]][now[1]-1] != "#" and visited[now[0]][now[1]-1] == 0:
            l.append([now[0],now[1]-1])
            G[now[0]][now[1]-1] = min(G[now[0]][now[1]] + 1,G[now[0]][now[1]-1])

        if G[now[0]+1][now[1]] != "#" and visited[now[0]+1][now[1]] == 0:
            l.append([now[0]+1,now[1]])
            G[now[0]+1][now[1]] = min(G[now[0]][now[1]] + 1,G[now[0]+1][now[1]])

        if G[now[0]-1][now[1]] != "#" and visited[now[0]-1][now[1]] == 0:
            l.append([now[0]-1,now[1]])
            G[now[0]-1][now[1]] = min(G[now[0]][now[1]]+1,G[now[0]-1][now[1]])
    return chk

[h,w] = [int(i) for i in input().split()]
s = [["#"] * (w+2)]
whites = 0
for i in range(h):
    ls = ["#"]
    tmp = input()
    for j in range(len(tmp)):
        if tmp[j] == ".":
            ls.append(200)
        else:
            ls.append(tmp[j])
    ls.append("#")
    whites += tmp.count(".")
    s.append(ls)
s.append(["#"] * (w+2))
l = collections.deque()

if bfs(s,l):
    print(whites - s[h][w]-1)
    """
    for i in range(h+2):
        for j in range(w+2):
            print(s[i][j],end = ",")
        print()
    """
else:
    print(-1)
#print(s)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs(S,W,H):
    dx=(-1,0,1,0)
    dy=(0,1,0,-1)
    queue=deque([[0,0]])
    visited=[]
    goal=False
    cnt=deque([0])
    while queue and goal==False:
        exe=queue.popleft()
        C=cnt.popleft()
        visited.append(exe)
        for i in range(len(dx)):
            x=exe[0]+dx[i]
            y=exe[1]+dy[i]
            if [x,y]==[W-1,H-1]:
                goal=True
            elif 0<=x<=W-1 and 0<=y<=H-1 and S[y][x]==".":
                if [x,y] not in visited:
                    queue.append([x,y])
                    cnt.append(C+1)
    return goal,C+1

def main():
    H,W=map(int,input().strip().split())
    S=[list(input()) for _ in range(H)]
    # number of dot
    num_sharp=0
    for i in range(H):
        for j in range(W):
            if S[i][j]=="#":
                num_sharp+=1
    goal,num=bfs(S,W,H)
    if goal:
        return W*H-num_sharp-(num+1)
    else:
        return -1

if __name__=="__main__":
    print(main())

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

def main(*args, **kwargs):
    # Initialize data
    H, W = map(int, sys.stdin.readline().split())
    total_cells = H * W
    existing_black_cells = 0

    grid = []
    for i in range(H):
        line = sys.stdin.readline()
        existing_black_cells += line.count('#')
        grid.append(line)

    # Initialize Search
    queue = deque()
    queue.append((0, 0))  # start point
    visited = set()
    movement = 0

    while len(queue) > 0:
        movement += 1
        for i in range(len(queue)):  # Process same level
            coodinate = queue.popleft()
            visited.add(coodinate)
            y = coodinate[0]
            x = coodinate[1]

            # Terminate condition
            if y == H - 1 and x == W - 1:
                print(total_cells - movement - existing_black_cells)
                return

            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                X = x + dx
                Y = y + dy
                adjacent = (Y, X)
                if 0 <= X < W and 0 <= Y < H and grid[Y][X] == '.' and adjacent not in visited:
                    queue.append(adjacent)
    print(-1)
    return
main()

Submission status: Time Limit Exceeded

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

def main(*args, **kwargs):
    # Initialize data
    H, W = map(int, input().split())
    total_cells = H * W
    existing_black_cells = 0

    grid = []
    for i in range(H):
        line = input()
        existing_black_cells += line.count('#')
        grid.append(line)

    # Initialize Search
    queue = deque()
    queue.append((0, 0))  # start point
    visited = set()
    movement = 0

    while len(queue) > 0:
        movement += 1
        for i in range(len(queue)):  # Process same level
            coodinate = queue.popleft()
            visited.add(coodinate)
            y = coodinate[0]
            x = coodinate[1]

            # Terminate condition
            if y == H - 1 and x == W - 1:
                print(total_cells - movement - existing_black_cells)
                return

            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                X = x + dx
                Y = y + dy
                adjacent = (Y, X)
                if 0 <= X < W and 0 <= Y < H and grid[Y][X] == '.' and adjacent not in visited:
                    queue.append(adjacent)
    print(-1)
    return
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
 
def main(*args, **kwargs):
    # Initialize data
    H, W = map(int, input().split())
    total_cells = H * W
    existing_black_cells = 0
 
    grid = []
    for i in range(H):
        line = input()
        existing_black_cells += line.count('#')
        grid.append(line)
 
    # Initialize Search
    queue = deque()
    queue.append((0, 0))  # start point
    visited = set()
    movement = 0

    while len(queue) > 0:
        movement += 1
        for i in range(len(queue)):  # Process same level
            coodinate = queue.popleft()
            visited.add(coodinate)
            y = coodinate[0]
            x = coodinate[1]
 
            # Terminate condition
            if y == H - 1 and x == W - 1:
                print(total_cells - movement - existing_black_cells)
                return
 
            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                X = x + dx
                Y = y + dy
                adjacent = (Y, X)
                if 0 <= X < W and 0 <= Y < H and grid[Y][X] == '.' and adjacent not in visited:
                    queue.append(adjacent)
    print(-1)
    return
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main(*args, **kwargs):
    # Initialize data
    H, W = map(int, input().split())
    total_cells = H * W
    existing_black_cells = 0

    grid = []
    for i in range(H):
        line = input()
        existing_black_cells += line.count('#')
        grid.append(line)

    # Initialize Search
    queue = deque()
    queue.append((0, 0))  # start point
    visited = set()
    movement = 0

    while len(queue) > 0:
        movement += 1
        for i in range(len(queue)):  # Process same level
            coodinate = queue.popleft()
            visited.add(coodinate)
            y = coodinate[0]
            x = coodinate[1]

            # Terminate condition
            if y == H - 1 and x == W - 1:
                print(total_cells - movement - existing_black_cells)
                return

            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                X = x + dx
                Y = y + dy
                adjacent = (Y, X)
                if 0 <= X < W and 0 <= Y < H and grid[Y][X] == '.' and adjacent not in visited:
                    queue.append(adjacent)
    print(-1)
    return
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def main(*args, **kwargs):
    # Initialize data
    H, W = map(int, input().split())
    total_cells = H * W
    existing_black_cells = 0

    grid = [['' for _ in range(W)] for _ in range(H)]
    for i in range(H):
        line = input()
        for j in range(W):
            grid[i][j] = line[j]
            if line[j] == '#':
                existing_black_cells += 1

    # Initialize Search
    queue = deque()
    queue.append((0, 0))  # start point
    visited = set()
    movement = 0

    while len(queue) > 0:
        movement += 1
        for i in range(len(queue)): # Process same level
            coodinate = queue.popleft()
            visited.add(coodinate)
            y = coodinate[0]
            x = coodinate[1]

            # Terminate condition
            if y == H - 1 and x == W - 1:
                print(total_cells - movement - existing_black_cells)
                return

            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                X = x+dx
                Y = y+dy
                adjacent = (Y, X)
                if 0 <= X < W and 0 <= Y < H and adjacent not in visited and grid[Y][X] == '.':
                    queue.append(adjacent)
    print(-1)
    return
main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def main(*args, **kwargs):
    # Initialize data
    H, W = map(int, input().split())
    total_cells = H * W
    existing_black_cells = 0

    grid = [['' for _ in range(W)] for _ in range(H)]
    for i in range(H):
        line = input()
        for j in range(W):
            grid[i][j] = line[j]
            if line[j] == '#':
                existing_black_cells += 1

    # Initialize Search
    queue = deque()
    queue.append((0, 0))  # start point
    visited = set()
    movement = 0

    while len(queue) > 0:
        movement += 1
        for i in range(len(queue)): # Process same level
            coodinate = queue.popleft()
            visited.add(coodinate)
            y = coodinate[0]
            x = coodinate[1]

            # Terminate condition
            if y == H - 1 and x == W - 1:
                print(total_cells - movement - existing_black_cells)
                return

            for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                X = x+dx
                Y = y+dy
                adjacent = (Y, X)
                if 0 <= X < W and 0 <= Y < H and adjacent not in visited and grid[Y][X] == '.':
                    queue.append(adjacent)
    print(-1)
    return
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline
from collections import deque
H,W = list(map(int, input().split()))
matrix = []
blocks = 0
for _ in range(H):
  # row = list(input())
  row = readline().rstrip()
  blocks += row.count("#")
  matrix.append(row)

q = deque([(0,0,0)])
min_step = -1
# visited = []
visited = [ [False]*W for _ in range(H) ]
visited[0][0] = True

while q:
  r,c,step = q.popleft()
  # visited.append((r,c))
  # visited[r][c] = True

  for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
    nr,nc = r+i,c+j
    if nr==H-1 and nc==W-1: 
      min_step = step+1
      q = []
      break

    if nr<0 or nc<0 or nr>=H or nc>=W: continue
    if visited[nr][nc]: continue
    # if (nr,nc) in visited: continue
    if matrix[nr][nc] == "#": continue
    visited[r][c] = True
    q.append((nr,nc,step+1))

if min_step == -1:
  print(-1)
else:
  print( H*W - blocks - min_step -1 )

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W = list(map(int, input().split()))
matrix = []
blocks = 0
for _ in range(H):
  row = list(input())
  blocks += row.count("#")
  matrix.append(row)

q = deque([(0,0,0)])
min_step = -1
# visited = []
visited = [ [False]*W for _ in range(H) ]
visited[0][0] = True

while q:
  r,c,step = q.popleft()
  # visited.append((r,c))
  # visited[r][c] = True

  for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
    nr,nc = r+i,c+j
    if nr==H-1 and nc==W-1: 
      min_step = step+1
      q = []
      break

    if nr<0 or nc<0 or nr>=H or nc>=W: continue
    if visited[nr][nc]: continue
    # if (nr,nc) in visited: continue
    if matrix[nr][nc] == "#": continue
    visited[r][c] = True
    q.append((nr,nc,step+1))

if min_step == -1:
  print(-1)
else:
  print( H*W - blocks - min_step -1 )

Submission status: Time Limit Exceeded

Solution code:
H,W = list(map(int, input().split()))
matrix = []
blocks = 0
for _ in range(H):
  row = list(input())
  blocks += row.count("#")
  matrix.append(row)

q = [(0,0,0)]
min_step = -1
# visited = []
visited = [ [False]*W for _ in range(H) ]

while q:
  r,c,step = q.pop(0)
  # visited.append((r,c))
  visited[r][c] = True

  for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
    nr,nc = r+i,c+j
    if nr==H-1 and nc==W-1: 
      min_step = step+1
      q = []
      break

    if nr<0 or nc<0 or nr>=H or nc>=W: continue
    if visited[nr][nc]: continue
    # if (nr,nc) in visited: continue
    if matrix[nr][nc] == "#": continue
    q.append((nr,nc,step+1))

if min_step == -1:
  print(-1)
else:
  print( H*W - blocks - min_step -1 )