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 sys
input = sys.stdin.readline
 
H, W = [int(x) for x in input().split()]
s = []
W_count = 0
for _ in range(H):
    tmp = list(input().rstrip())
    s.append(tmp)
    W_count += tmp.count('.')

from collections import deque
D = [[-1] * W for _ in range(H)]

def bfs():
    queue = deque([(0, 0, 0, 0)])
    D[0][0] = 0
    while queue:
        u = queue.popleft()
        x = u[0]
        y = u[1]
        D[x][y] = D[u[2]][u[3]] + 1
        for i in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if 0 <= i[0] < H and 0 <= i[1] < W and D[i[0]][i[1]] < 0 and s[i[0]][i[1]] == ".":
                queue.append((i[0], i[1], x, y))
    return D

D = bfs()
if D[-1][-1] == -1:
    print(-1)
    sys.exit()
print(W_count - D[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = []
ans = 0
for _ in range(h):
    s = input()
    mass.append(s)
    ans += s.count(".")

dx = (0, 0, 1, -1)
dy = (1, -1, 0, 0)

q = deque([(0, 0)])
d = [[0]*w for _ in range(h)]
visited = [[0]*w for _ in range(h)]
while q:
    i, j = q.popleft()
    visited[i][j] = 1
    for k in range(4):
        ni = i + dx[k]
        nj = j + dy[k]
        if ni < 0 or h <= ni:
            continue
        if nj < 0 or w <= nj:
            continue
        if mass[ni][nj] == "#":
            continue
        if not visited[ni][nj]:
            q.append((ni, nj))
            d[ni][nj] = d[i][j] + 1
        if ni == h-1 and nj == w-1:
            break
    else:
        continue
    break

if d[h-1][w-1] == 0:
    print(-1)
else:
    print(ans - d[h-1][w-1] - 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = []
ans = 0
for _ in range(h):
    s = input()
    mass.append(s)
    ans += s.count(".")

dx = (0, 0, 1, -1)
dy = (1, -1, 0, 0)

q1 = deque([0])
q2 = deque([0])
d = [[0]*w for _ in range(h)]
visited = [[0]*w for _ in range(h)]
while q1:
    i = q1.popleft()
    j = q2.popleft()
    visited[i][j] = 1
    for k in range(4):
        ni = i + dx[k]
        nj = j + dy[k]
        if ni < 0 or h <= ni:
            continue
        if nj < 0 or w <= nj:
            continue
        if mass[ni][nj] == "#":
            continue
        if not visited[ni][nj]:
            q1.append(ni)
            q2.append(nj)
            d[ni][nj] = d[i][j] + 1
        if ni == h-1 and nj == w-1:
            break
    else:
        continue
    break

if d[h-1][w-1] == 0:
    print(-1)
else:
    print(ans - d[h-1][w-1] - 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = []
ans = 0
for _ in range(h):
    s = input()
    mass.append(s)
    ans += s.count(".")

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

q1 = deque([0])
q2 = deque([0])
d = [[0]*w for _ in range(h)]
visited = [[0]*w for _ in range(h)]
while q1:
    i = q1.popleft()
    j = q2.popleft()
    visited[i][j] = 1
    for k in range(4):
        ni = i + dx[k]
        nj = j + dy[k]
        if ni < 0 or h <= ni:
            continue
        if nj < 0 or w <= nj:
            continue
        if mass[ni][nj] == "#":
            continue
        if not visited[ni][nj]:
            q1.append(ni)
            q2.append(nj)
            d[ni][nj] = d[i][j] + 1

if d[h-1][w-1] == 0:
    print(-1)
else:
    print(ans - d[h-1][w-1] - 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = [input() for _ in range(h)]

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

q1 = deque([0])
q2 = deque([0])
d = [[0]*w for _ in range(h)]
visited = [[0]*w for _ in range(h)]
while q1:
    i = q1.popleft()
    j = q2.popleft()
    visited[i][j] = 1
    for k in range(4):
        ni = i + dx[k]
        nj = j + dy[k]
        if ni < 0 or h <= ni:
            continue
        if nj < 0 or w <= nj:
            continue

        if mass[ni][nj] == "#":
            continue
        if not visited[ni][nj]:
            q1.append(ni)
            q2.append(nj)
            d[ni][nj] = d[i][j] + 1

if d[h-1][w-1] == 0:
    print(-1)
else:
    ans = 0
    for i in mass:
        ans += i.count(".")
    print(ans - d[h-1][w-1] - 1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = [list(input()) for _ in range(h)]

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

q1 = deque([0])
q2 = deque([0])
d = [[0]*w for _ in range(h)]
visited = [[0]*w for _ in range(h)]
while q1:
    i = q1.popleft()
    j = q2.popleft()
    visited[i][j] = 1
    for k in range(4):
        ni = i + dx[k]
        nj = j + dy[k]
        if ni < 0 or h <= ni:
            continue
        if nj < 0 or w <= nj:
            continue

        if mass[ni][nj] == "#":
            continue
        if not visited[ni][nj]:
            q1.append(ni)
            q2.append(nj)
            d[ni][nj] = d[i][j] + 1

if d[h-1][w-1] == 0:
    print(-1)
else:
    ans = 0
    for i in mass:
        ans += i.count("#")
    print(h * w - ans - d[h-1][w-1] - 1)

Submission status: Time Limit Exceeded

Solution code:
import queue

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

ans, que = count + 1, queue.Queue()
que.put([1, 1, 1])
while not que.empty():
    q = que.get()
    if q[0] == W and q[1] == H:
        ans = q[2]
        break
    else:
        s[q[1]][q[0]] = q[2]

    for a in around:
        nextx, nexty = q[0] + a[0], q[1] + a[1]
        if s[nexty][nextx] == '.':
            que.put([nextx, nexty, q[2] + 1])

print(count - ans)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
s = [input() for i in range(h)]
cost = [[2500] * w for i in range(h)]
cost[0][0] = 1
wall = 0
for i in range(h):
  for j in range(w):
    if s[i][j] == '#':
      wall += 1
for k in range(h*w):
  for i in range(h):
    for j in range(w):
      if s[i][j] != '#':
        u = cost[i-1][j] + 1 if i > 0 and s[i-1][j] != '#' else 2500
        d = cost[i+1][j] + 1 if i < h-1 and s[i+1][j] != '#' else 2500
        l = cost[i][j-1] + 1 if j > 0 and s[i][j-1] != '#' else 2500
        r = cost[i][j+1] + 1 if j < w-1 and s[i][j+1] != '#' else 2500
        cost[i][j] = min(cost[i][j], u, d, l, r)

if cost[h-1][w-1] == 2500:
  print(-1)
else:
  print(h*w - cost[h-1][w-1] - wall)

Submission status: Time Limit Exceeded

Solution code:
from pprint import pprint
INF = 1000000
dx = [1, -1, 0,  0]
dy = [0,  0, 1, -1]
# 入力
h, w = map(int, input().split())
maze = []
wallcount = 0
for i in range(h):
    l = list(input())
    maze.append(l)
    wallcount += l.count("#")

# ワーシャルフロイド用に枠を作る。
# 2次元マップしてもいいが面倒なので、１次元にする。[0 - x][0 - y]を[0- x * y]にflattenする
wsmap = lambda a, b: (a * w + b)
dp = []
# 辺がない時はINFを入れのでデフォルト値とする
for i in range(h * w):
    dp.append([INF] * (h * w))

# 迷路ををグラフにする。
for y in range(h):
    for x in range(w):
        if maze[y][x] == "#": # そのマスが壁なら何もしない(他のマストの連結はないので)
            continue
        # ワーシャルフロイドでは自分自身へのコストは0にしておく。
        dp[wsmap(y, x)][wsmap(y, x)] = 0
        # ４方向に移動できるかの判定
        for dir in range(len(dx)):
            nx, ny = x + dx[dir], y + dy[dir]
            if -1 < nx and nx < w and -1 < ny and ny < h: # 枠をはみ出ないかチェック
                if maze[ny][nx] != "#": # そのマスが壁でないなら
                    dp[wsmap(y, x)][wsmap(ny, nx)] = 1 # コストを1にする

# ワーシャルフロイドする
for kk in range(h * w):
    for ii in range(h * w):
        for jj in range(h * w):
            dp[ii][jj] = min(dp[ii][jj], dp[ii][kk] + dp[kk][jj])

# これで結果が出たので
import itertools
res = list(itertools.chain(*dp))# 二次元配列を一次元にして
needstep = dp[0][-1]
res = h * w
res -= wallcount
res -= needstep + 1
print(res if res >= 0 else "-1")

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = [list(input()) for _ in range(h)]


def check(a, b, w):
    return mass[a][b] == "." and not w[a][b]


stack = deque([(0, 0)])
visited = [[0] * w for _ in range(h)]
depth = [[1] * w for _ in range(h)]

while stack:
    i, j = stack.popleft()
    visited[i][j] = 1
    d_now = depth[i][j]
    if j < w-1:
        if check(i, j+1, visited):
            stack.append((i, j+1))
            depth[i][j+1] = d_now + 1
            if i == h-1 and j == w-2:
                break
    if i < h-1:
        if check(i+1, j, visited):
            stack.append((i+1, j))
            depth[i+1][j] = d_now + 1
            if i == h-2 and j == w-1:
                break
    if 0 < j:
        if check(i, j-1, visited):
            stack.append((i, j-1))
            depth[i][j-1] = d_now + 1
    if 0 < i:
        if check(i-1, j, visited):
            stack.append((i-1, j))
            depth[i-1][j] = d_now + 1

black = 0
for i in range(h):
    black += mass[i].count("#")
x = depth[h-1][w-1]
ans = h * w - x - black
if x == 1:
    ans = -1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = [list(input()) for _ in range(h)]


def check(a, b, w):
    return mass[a][b] == "." and not w[a][b]


q = deque([(0, 0)])
visited = [[0] * w for _ in range(h)]
depth = [[1] * w for _ in range(h)]

while q:
    i, j = q.popleft()
    visited[i][j] = 1
    d_now = depth[i][j]
    if j < w-1:
        if check(i, j+1, visited):
            q.append((i, j+1))
            depth[i][j+1] = d_now + 1
    if 0 < j:
        if check(i, j-1, visited):
            q.append((i, j-1))
            depth[i][j-1] = d_now + 1
    if i < h-1:
        if check(i+1, j, visited):
            q.append((i+1, j))
            depth[i+1][j] = d_now + 1
    if 0 < i:
        if check(i-1, j, visited):
            q.append((i-1, j))
            depth[i-1][j] = d_now + 1

black = 0
for i in range(h):
    black += mass[i].count("#")
x = depth[h-1][w-1]
ans = h * w - x - black
if x == 1:
    ans = -1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = [list(input()) for _ in range(h)]


def check(a, b, w):
    return mass[a][b] == "." and not (a, b) in w


q = deque([(0, 0)])
visited = {(0, 0)}
depth = [[1] * w for _ in range(h)]

while q:

    i, j = q.popleft()
    visited.add((i, j))
    d_now = depth[i][j]
    if j < w-1:
        if check(i, j+1, visited):
            q.append((i, j+1))
            depth[i][j+1] = d_now + 1
    if 0 < j:
        if check(i, j-1, visited):
            q.append((i, j-1))
            depth[i][j-1] = d_now + 1
    if i < h-1:
        if check(i+1, j, visited):
            q.append((i+1, j))
            depth[i+1][j] = d_now + 1
    if 0 < i:
        if check(i-1, j, visited):
            q.append((i-1, j))
            depth[i-1][j] = d_now + 1

x = depth[h-1][w-1]
black = 0
for i in range(h):
    black += mass[i].count("#")
ans = h * w - x - black
if x == 1:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h, w = map(int, input().split())
mass = [list(input()) for _ in range(h)]


def check(a, b, w):
    return mass[a][b] == "." and not (a, b) in w


q = deque([(0, 0)])
visited = {(0, 0)}
depth = [[1] * w for _ in range(h)]

while q:

    i, j = q.popleft()
    visited.add((i, j))
    d_now = depth[i][j]
    if j < w-1:
        if check(i, j+1, visited):
            q.append((i, j+1))
            depth[i][j+1] = d_now + 1
    if 0 < j:
        if check(i, j-1, visited):
            q.append((i, j-1))
            depth[i][j-1] = d_now + 1
    if i < h-1:
        if check(i+1, j, visited):
            q.append((i+1, j))
            depth[i+1][j] = d_now + 1
    if 0 < i:
        if check(i-1, j, visited):
            q.append((i-1, j))
            depth[i-1][j] = d_now + 1

x = depth[h-1][w-1]
black = 0
for i in range(h):
    for j in range(w):
        if mass[i][j] == "#":
            black += 1
ans = h * w - x - black
if x == 1:
    ans = -1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  h,w=LI()
  q=queue.Queue()

  field=[S() for _ in range(h)]
  counter=[[inf]*w for _ in range(h)]

  sharp_cnt=0
  for x in field:
    sharp_cnt+=x.count('#')

  q.put((0,0,1))

  while not q.empty()>0:
    y,x,cnt=q.get()
    
    if counter[y][x]<cnt:
      continue
    counter[y][x]=cnt

    for dy,dx in dd:
      ny=y+dy
      nx=x+dx

      if 0<=ny and 0<=nx and ny<h and nx<w:
        if field[ny][nx]!='#':

          if counter[ny][nx]==inf:
            q.put((ny,nx,cnt+1))

  step_cnt=counter[h-1][w-1]

  if step_cnt==inf:
    return -1

  return h*w-sharp_cnt-step_cnt

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  h,w=LI()
  q=queue.Queue()

  field=[S() for _ in range(h)]
  counter=[[inf]*w for _ in range(h)]

  sharp_cnt=0
  for x in field:
    sharp_cnt+=x.count('#')

  q.put((0,0,1))

  while not q.empty()>0:
    y,x,cnt=q.get()
    counter[y][x]=cnt

    for dy,dx in dd:
      ny=y+dy
      nx=x+dx

      if 0<=ny and 0<=nx and ny<h and nx<w:
        if field[ny][nx]!='#':

          if counter[ny][nx]==inf:
            q.put((ny,nx,cnt+1))

  step_cnt=counter[h-1][w-1]

  if step_cnt==inf:
    return -1

  return h*w-sharp_cnt-step_cnt

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  h,w=LI()
  q=[]

  field=[S() for _ in range(h)]
  counter=[[inf]*w for _ in range(h)]

  sharp_cnt=0
  for x in field:
    sharp_cnt+=x.count('#')

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

  while len(q)>0:
    y,x,cnt=q.pop()
    if counter[y][x]<cnt:
      continue
    counter[y][x]=cnt

    for dy,dx in dd:
      ny=y+dy
      nx=x+dx

      if 0<=ny and 0<=nx and ny<h and nx<w:
        if field[ny][nx]!='#':

          if counter[ny][nx]>cnt+1:
            q.append((ny,nx,cnt+1))

  step_cnt=counter[h-1][w-1]

  if step_cnt==inf:
    return -1

  return h*w-sharp_cnt-step_cnt

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  h,w=LI()
  q=[]

  field=[S() for _ in range(h)]
  counter=[[inf]*w for _ in range(h)]

  sharp_cnt=0
  for x in field:
    sharp_cnt+=x.count('#')

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

  ind=0
  while len(q)>0:
    ind+=1
    if ind>10**8:
      break

    y,x,cnt=q.pop()
    counter[y][x]=cnt

    for dy,dx in dd:
      ny=y+dy
      nx=x+dx

      if 0<=ny and 0<=nx and ny<h and nx<w:
        if field[ny][nx]!='#':

          if counter[ny][nx]>cnt:
            q.append((ny,nx,cnt+1))

  step_cnt=counter[h-1][w-1]+1

  if step_cnt==inf+1:
    return -1

  return h*w-sharp_cnt-step_cnt

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  h,w=LI()
  q=[]

  field=[S() for _ in range(h)]
  counter=[[inf]*w for _ in range(h)]

  sharp_cnt=0
  for x in field:
    sharp_cnt+=x.count('#')

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

  while len(q)>0:
    y,x,cnt=q.pop()
    counter[y][x]=cnt

    for dy,dx in dd:
      ny=y+dy
      nx=x+dx

      if 0<=ny and 0<=nx and ny<h and nx<w:
        if field[ny][nx]!='#':
          if counter[ny][nx]>3000 and counter[ny][nx]<4000:
            continue
          if counter[ny][nx]>cnt:
            q.append((ny,nx,cnt+1))

  step_cnt=counter[h-1][w-1]+1

  if step_cnt==inf+1:
    return -1

  return h*w-sharp_cnt-step_cnt

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
import math,itertools,fractions,heapq,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  h,w=LI()
  q=[]

  field=[S() for _ in range(h)]
  counter=[[inf]*w for _ in range(h)]

  sharp_cnt=0
  for x in field:
    sharp_cnt+=x.count('#')

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

  while len(q)>0:
    y,x,cnt=q.pop()
    counter[y][x]=cnt

    for dy,dx in dd:
      ny=y+dy
      nx=x+dx

      if 0<=ny and 0<=nx and ny<h and nx<w:
        if field[ny][nx]!='#':
          if counter[ny][nx]>cnt:
            q.append((ny,nx,cnt+1))

  step_cnt=counter[h-1][w-1]+1

  if step_cnt==inf+1:
    return -1

  return h*w-sharp_cnt-step_cnt

# main()
print(main())

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
#0が進めるところ、1は無理
#lis = [[1 if l == '#' else 0 for l in list(input())] for _ in range(h)]

road_count = 0
lis = [list('#'*(w+2))]
for _ in range(h):
    li = input()
    for i in li:
        if i == '.':
            road_count += 1
    li = '#' + li + '#'
    lis.append(list(li))
lis.append(list('#'*(w+2)))

#print(lis)
dp = [[0]*(w+2) for _ in range(h+2)]

#(開始x,開始y,移動回数)
step = [[1,1]]
while len(step)>0:
    x,y = step.pop(0)

    if x == h and y == w:
        print(road_count-dp[x][y]-1)
        exit()

    #探索済みのところは、#にする
    lis[x][y] = '#'


    if lis[x-1][y] != '#':
        step.append([x-1,y])
        dp[x-1][y] = dp[x][y]+1
    if lis[x+1][y] != '#':
        step.append([x+1,y])
        dp[x+1][y] = dp[x][y]+1
    if lis[x][y-1] != '#':
        step.append([x,y-1])
        dp[x][y-1] = dp[x][y]+1
    if lis[x][y+1] != '#':
        step.append([x,y+1])
        dp[x][y+1] = dp[x][y]+1
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = map(int,input().split())
#0が進めるところ、1は無理
lis = [[1 if l == '#' else 0 for l in list(input())] for _ in range(h)]
#ゴールは9
lis[h-1][w-1] = 9
#print(lis)
#[[0, 0, 1], [1, 0, 0], [0, 0, 9]]

#この問題ではbfsを始める前に、もともと移動可能だったところの数を記録しておく
road = 0
for row in lis:
    for column in row:
        if column != 1:
            road +=1

count = 0
#(開始x,開始y,移動回数)
que = deque([])
que.append([0,0,0])
while len(que)>0:
    x,y,depth = que.popleft()

    if lis[x][y] == 9:
        count = depth
        break

    #探索済みのところは、1にする
    lis[x][y] = 1

    #遷移先は0or9なので、1以外なら行ける
    if x-1>=0 and lis[x-1][y] != 1:
        que.append([x-1,y,depth+1])
    if x+1<h and lis[x+1][y] != 1:
        que.append([x+1,y,depth+1])
    if y-1>=0 and lis[x][y-1] != 1:
        que.append([x,y-1,depth+1])
    if y+1<w and lis[x][y+1] != 1:
        que.append([x,y+1,depth+1])

#そもそも行けない
if count == 0:
    print(-1)
#(移動可能マス数) - (移動する道順上のマスの数 ＝ 最短の移動回数＋１）
else:
    print(road-(count+1))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = map(int,input().split())
#0が進めるところ、1は無理
lis = [[1 if l == '#' else 0 for l in list(input())] for _ in range(h)]
#ゴールは9
lis[h-1][w-1] = 9
#print(lis)
#[[0, 0, 1], [1, 0, 0], [0, 0, 9]]

#この問題ではbfsを始める前に、もともと移動可能だったところの数を記録しておく
road = 0
for row in lis:
    for column in row:
        if column != 1:
            road +=1

count = 0
#(開始x,開始y,移動回数)
pos = [[0,0,0]]
que = deque(pos)
while len(pos)>0:
    x,y,depth = pos.pop(0)

    if lis[x][y] == 9:
        count = depth
        break

    #探索済みのところは、1にする
    lis[x][y] = 1

    #遷移先は0or9なので、1以外なら行ける
    if x-1>=0 and lis[x-1][y] != 1:
        pos.append([x-1,y,depth+1])
    if x+1<h and lis[x+1][y] != 1:
        pos.append([x+1,y,depth+1])
    if y-1>=0 and lis[x][y-1] != 1:
        pos.append([x,y-1,depth+1])
    if y+1<w and lis[x][y+1] != 1:
        pos.append([x,y+1,depth+1])

#そもそも行けない
if count == 0:
    print(-1)
#(移動可能マス数) - (移動する道順上のマスの数 ＝ 最短の移動回数＋１）
else:
    print(road-(count+1))

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
#0が進めるところ、1は無理
lis = [[1 if l == '#' else 0 for l in list(input())] for _ in range(h)]
#ゴールは9
lis[h-1][w-1] = 9
#print(lis)
#[[0, 0, 1], [1, 0, 0], [0, 0, 9]]

#この問題ではbfsを始める前に、もともと壁だったところの数を記録しておく
road = 0
for row in lis:
    for column in row:
        if column != 1:
            road +=1

count = 0
#(開始x,開始y,移動回数)
pos = [[0,0,0]]
while len(pos)>0:
    x,y,depth = pos.pop(0)

    if lis[x][y] == 9:
        count = depth
        break

    #探索済みのところは、1にする
    lis[x][y] = 1

    #遷移先は0or9なので、1以外なら行ける
    if x-1>=0 and lis[x-1][y] != 1:
        pos.append([x-1,y,depth+1])
    if x+1<h and lis[x+1][y] != 1:
        pos.append([x+1,y,depth+1])
    if y-1>=0 and lis[x][y-1] != 1:
        pos.append([x,y-1,depth+1])
    if y+1<w and lis[x][y+1] != 1:
        pos.append([x,y+1,depth+1])

#(全マス) - (壁) - (移動する道順上のマスの数 ＝ 最短の移動回数＋１）
if count == 0:
    print(-1)
else:
    print(road-(count+1))

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue

h, w = list(map(int, input().split()))
l = [input() for _ in range(h)]
checked = [[False for _ in range(w)] for __ in range(h)]

q = queue.Queue()
q.put((0, 0, 1))
checked[0][0] = True
while not q.empty():
    x, y, count = q.get()
    #if checked[y][x]:
    #    continue
    checked[y][x] = True
    if x == w-1 and y == h-1:
        ans = 0
        for i in range(h):
            for j in range(w):
                if l[i][j] == ".":
                    ans += 1
        print(ans-count)
        sys.exit(0)
    if x > 0 and l[y][x-1] == "." and not checked[y][x-1]:
        q.put((x-1, y, count+1))
    if y > 0 and l[y-1][x] == "." and not checked[y-1][x]:
        q.put((x, y-1, count+1))
    if x < w-1 and l[y][x+1] == "." and not checked[y][x+1]:
        q.put((x+1, y, count+1))
    if y < h-1 and l[y+1][x] == "." and not checked[y+1][x]:
        q.put((x, y+1, count+1))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
import queue

h, w = list(map(int, input().split()))
l = [input() for _ in range(h)]
checked = [[False for _ in range(w)] for __ in range(h)]

q = queue.Queue()
q.put((0, 0, 1))
checked[0][0] = True
while not q.empty():
    x, y, count = q.get()
    checked[y][x] = True
    if x == w-1 and y == h-1:
        ans = 0
        for i in range(h):
            for j in range(w):
                if l[i][j] == ".":
                    ans += 1
        print(ans-count)
        sys.exit(0)
    if x > 0 and l[y][x-1] == "." and not checked[y][x-1]:
        q.put((x-1, y, count+1))
    if y > 0 and l[y-1][x] == "." and not checked[y-1][x]:
        q.put((x, y-1, count+1))
    if x < w-1 and l[y][x+1] == "." and not checked[y][x+1]:
        q.put((x+1, y, count+1))
    if y < h-1 and l[y+1][x] == "." and not checked[y+1][x]:
        q.put((x, y+1, count+1))
print(-1)

Submission status: Time Limit Exceeded

Solution code:
INF = 1e10

H, W = list(map(int, input().split()))
c = []
cnt = 0
for y in range(H):
    c.append(input())
    for s in c[-1]:
        if s=='.':
            cnt+=1
    
def search(syx, gyx):
    sy,sx = syx
    gy,gx = gyx
    visited = [[INF]*W for _ in range(H)]
    q = [[sy,sx]]
    visited[sy][sx]=0
    while visited[gy][gx]==INF:
        tmp_q = []
        for one in q:
            cy,cx = one
            for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                ny, nx = cy+dy, cx+dx
                if 0 <= nx < W and 0 <= ny < H and c[ny][nx] == '.' and visited[ny][nx]> visited[cy][cx]+1:
                    visited[ny][nx] = visited[cy][cx]+1
                    tmp_q.append([ny,nx])
        q = tmp_q
    return visited[gy][gx]

print(cnt-search([0,0],[H-1,W-1])-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque,defaultdict
H,W = map(int,input().split())
s = [["#"]*(W+2)] + [list("#"+input()+"#") for _ in range(H)] + [["#"]*(W+2)]
Q = deque([(1,1,1)])
cnt = 0
for S in s[1:-1]:
    cnt += S.count(".")

while Q:
    x,y,d = Q.popleft()
    s[x][y] = "#"
    if x == H and y == W:
        route = d
        break
    for dx,dy in [(1,0),(-1,0),(0,1),(0,-1)]:
        if s[x+dx][y+dy] == ".":
            Q.append((x+dx,y+dy,d+1))
else:
    print(-1)
    exit()

print(cnt-route)

Submission status: Time Limit Exceeded

Solution code:
from scipy.sparse.csgraph import dijkstra

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

graph = [[0 for _ in range(H*W)] for _ in range(H*W)]

for i in range(H):
    for j in range(W-1):
        if s[i][j] == s[i][j+1] == ".":
            graph[j+(W*i)][j+(W*i)+1] = 1
            graph[j+(W*i)+1][j+(W*i)] = 1

for i in range(H-1):        
    for j in range(W):
        if s[i][j] == s[i+1][j] == ".":
            graph[j+(W*i)][j+(W*(i+1))] = 1
            graph[j+(W*(i+1))][j+(W*i)] = 1
            
d = dijkstra(graph)

cnt = 0
for i in s:
    for j in range(W):
        if i[j] == ".":
            cnt += 1
      
if d[0][H*W-1] == float("inf"):
    print(-1)
else:
    print(int(cnt-d[0][H*W-1]-1))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if s[y][x]!='.':
        continue
    if x==W-1 and y==H-1:
        print(white-l)
        break
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H:
            q_append((nx,ny,l+1))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
H,W=map(int,input().split())
s=[]
s.append("".join("#" for _ in range(W+2)))
cnt=0
for i in range(H):
    ss=input().strip()
    s.append("#"+ss+"#")
    for w in range(W):
        if ss[w]==".":
            cnt+=1

s.append("".join("#" for _ in range(W+2)))
#print(s)
import sys
sys.setrecursionlimit(300000)
def solv(h,w,cnt):
    #print(h,w)
    #print(a)
    #print(s)
    if a[h][w]>cnt+1 and s[h][w]==".":
        a[h][w]=cnt+1
        solv(h-1,w,cnt+1)
        solv(h,w-1,cnt+1)
        solv(h+1,w,cnt+1)
        solv(h,w+1,cnt+1)
    return

a=[[1000000]*(W+2) for _ in range(H+2)]
solv(1,1,0)
print(cnt-a[-2][-2] if a[-2][-2]!= 1000000 else -1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
q_append=q.append
q_popleft=q.popleft
while q:
    x,y,l=q_popleft()
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H and s[ny][nx]=='.':
            q_append((nx,ny,l+1))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W=map(int,input().split())
white=0
s=[]
for y in range(H):
    line=input()
    white+=line.count('.')
    s.append(list(line))

q = deque([(0,0,1)])
while q:
    x,y,l=q.popleft()
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H and s[ny][nx]=='.':
            q.append((nx,ny,l+1))
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W=map(int,input().split())
s=[list(input()) for _ in range(H)]

white=sum([1 if s[y][x]=='.' else 0 for x in range(W) for y in range(H)])
q = deque([(0,0,1)])
while q:
    x,y,l=q.popleft()
    if x==W-1 and y==H-1:
        print(white-l)
        break
    s[y][x]='*'
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx, ny=(x+d[0],y+d[1])
        if 0<=nx<W and 0<=ny<H and s[ny][nx]=='.':
            q.append((nx,ny,l+1))
else:
    print(-1)