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: Runtime Error

Solution code:
from collections import deque

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

q = deque()
q.append((0, 0, 0))
S[0][0] = "#"
while q:
    y, x, cnt = q.popleft()
    for dy, dx in [[1, 1], [-1, 1], [1, -1], [-1, -1]]:
        if 0 <= y + dy < H and 0 <= x + dx < W and S[y + dy][x + dx] == ".":
            q.append(y + dy, x + dx, cnt + 1)
            S[y + dy][x + dx] = "#"
if S[H-1][W-1] == ".":
    print(-1)
else:
    score = H * W - (cnt + 1)
    print(score)

Submission status: Runtime Error

Solution code:
import queue

H, W = list(map(int, input().split()))
s = [list(input()) + ['#'] for i in range(H)] + [['#' for i in range(W+1)]]
white = sum([s[i].count('.') for i in range(H)])

q = queue.PriorityQueue()
s[0][0] = 1
q.put((0,0))

while not q.empty():
    i, j = q.get()
    for x, y in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]:
        if s[x][y] == '.':
            s[x][y] = s[i][j]+1
            q.put((x, y))

print(white-s[H-1][W-1])

Submission status: Runtime Error

Solution code:
#coding utf-8
from collections import deque
H,W=map(int,input().split())

s = [list(input().strip()) for _ in range(H)]
d = [[ 0 for i in range(W)] for j in range(H)]
q = deque([])
q.append([0,0,0])
y,x,z=q.popleft()

H = H-1
W = W-1

while y!=H or x!=W:
  if s[y][x]=="." and d[y][x]==0:
    if y<H:
      q.append([y+1,x,z+1])
    if x<W:
      q.append([y,x+1,z+1])
    if y>0:
      q.append([y-1,x,z+1])
    if x>0:
      q.append([y,x-1,z+1])
    d[y][x]=1  
  y,x,z=q.popleft()

ans1=0
for i in range(H+1):
  for j in range(W+1):
    if s[i][j]=="#":
      ans1 +=1
      
ans = (H+1)*(W+1)-ans1-z-1
print(ans)

Submission status: Runtime Error

Solution code:
H, W = map(int,input().split())
# C = [list(input()) for _ in range(H)]
C = []
pre = 0
for i in range(H):
    c = list(input())
    pre += c.count("#")
    C.append(c)

list = [(0, 0)]
count = 1
 
while C[H-1][W-1] == '.':
    count += 1
    next_list = []
    for y,x in list:
        for i,j in ((1,0),(0,1),):
            if x+j < W and y+i < H:
                if C[y+i][x+j] == '.':
                    C[y+i][x+j] = count
                    next_list.append((y+i,x+j))
    list = list(set(next_list))
print(H*W-pre-count)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
field = [input() for x in range(H)]
vx = [0,0,1,-1]
vy = [1,-1,0,0]
reached = [[-1 for x in range(W)]for x in range(H)]
from collections import deque
def bfs(y,x):
    q = deque([[y,x]])
    reached[y][x] = 1
    try:
        while q:
            y,x = q.popleft()
            if [y,x] == [H-1,W-1]:
                return reached[y][x]
            for dy,dx in zip(vy,vx):
                ny,nx = y+dy,x+dx
                if not (0<=ny<H and 0<=nx<W):
                    continue
                if field[ny][nx] == '.' and reached[ny][nx] == -1:
                    q.append([ny,nx])
                    reached[ny][nx] = reached[y][x] + 1
    except:
        return -1
bk = 0
for x in field:
    for y in x:
        if y == '#':
            bk += 1
print(H*W-bfs(0,0)-bk)

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
field = [input() for x in range(H)]
vx = [0,0,1,-1]
vy = [1,-1,0,0]
reached = [[-1 for x in range(W)]for x in range(H)]
from collections import deque
def bfs(y,x):
    q = deque([[y,x]])
    reached[y][x] = 1

    while q:
        y,x = q.popleft()
        if [y,x] == [H-1,W-1]:
            return reached[y][x]
        for dy,dx in zip(vy,vx):
            ny,nx = y+dy,x+dx
            if not (0<=ny<H and 0<=nx<W):
                continue
            if field[ny][nx] == '.' and reached[ny][nx] == -1:
                q.append([ny,nx])
                reached[ny][nx] = reached[y][x] + 1
bk = 0
for x in field:
    for y in x:
        if y == '#':
            bk += 1
print(H*W-bfs(0,0)-bk)

Submission status: Runtime Error

Solution code:
import collections

#入力
H, W = map(int, input().split())

#lst = [['a']*W for _ in range(H)]
count = 0 #白色のマスの総数
lst = []
row = []
for i in range(H):
    row = list(input())
    count += row.count('.')
    lst += [row]
 
#for i in range(H):
#    for j in range(W):
#        if lst[i][j] == '.':
#            count += 1

sx, sy = 1, 1 #スタート位置
gx, gy = H, W #ゴール位置

move = [[-1, 0], [1,0], [0, -1], [0, 1]]

def bfs():
    q = collections.deque()
    INF = 10 ** 9
    d = [[INF]* W for _ in range(H)]
    q.append(0)
    q.append(0)
    d[0][0] = 0

    while True:
        if q.empty():
            break
        px = q.popleft()
        py = q.popleft()
        if px == gx-1 and py == gy-1:
            break
        else:
            for dx, dy in move:
                nx = px + dx
                ny = py + dy

                if 0 <= nx and nx < H and 0 <= ny and ny < W and lst[nx][ny] == '.' and d[nx][ny] == INF:
                    q.append(nx)
                    q.append(ny)
                    d[nx][ny] = d[px][py] + 1
    return d[gx-1][gy-1]

a = bfs()

if a == 10 **9:
    print (-1)
else:
    print (count - a - 1)

Submission status: Runtime Error

Solution code:
import collections

#入力
H, W = map(int, input().split())

#lst = [['a']*W for _ in range(H)]
count = 0 #白色のマスの総数
lst = []
row = []
for i in range(H):
    row = list(input())
    count += row.count('.')
    lst += [row]
 
#for i in range(H):
#    for j in range(W):
#        if lst[i][j] == '.':
#            count += 1

sx, sy = 1, 1 #スタート位置
gx, gy = H, W #ゴール位置

move = [[-1, 0], [1,0], [0, -1], [0, 1]]

def bfs():
    q = collections.deque()
    INF = 10 ** 3
    d = [[INF]* W for _ in range(H)]
    q.append(0)
    q.append(0)
    d[0][0] = 0

    while True:
        if q.empty():
            break
        px = q.popleft()
        py = q.popleft()
        if px == gx-1 and py == gy-1:
            break
        else:
            for dx, dy in move:
                nx = px + dx
                ny = py + dy

                if 0 <= nx and nx < H and 0 <= ny and ny < W and lst[nx][ny] == '.' and d[nx][ny] == INF:
                    q.append(nx)
                    q.append(ny)
                    d[nx][ny] = d[px][py] + 1
    return d[gx-1][gy-1]

a = bfs()

if a == 10 **9:
    print (-1)
else:
    print (count - a - 1)

Submission status: Runtime Error

Solution code:
import collections

#入力
H, W = map(int, input().split())

#lst = [['a']*W for _ in range(H)]
count = 0 #白色のマスの総数
lst = []
row = []
for i in range(H):
    row = list(input())
    count += row.count('.')
    lst += [row]
 
#for i in range(H):
#    for j in range(W):
#        if lst[i][j] == '.':
#            count += 1

sx, sy = 1, 1 #スタート位置
gx, gy = H, W #ゴール位置

move = [[-1, 0], [1,0], [0, -1], [0, 1]]

def bfs():
    q = collections.deque()
    INF = 10 ** 3
    d = [[INF]* W for _ in range(H)]
    q.append(0)
    q.append(0)
    d[0][0] = 0

    while True:
        px = q.popleft()
        py = q.popleft()
        if px == gx-1 and py == gy-1:
            break
        else:
            for dx, dy in move:
                nx = px + dx
                ny = py + dy

                if 0 <= nx and nx < H and 0 <= ny and ny < W and lst[nx][ny] == '.' and d[nx][ny] == INF:
                    q.append(nx)
                    q.append(ny)
                    d[nx][ny] = d[px][py] + 1
    return d[gx-1][gy-1]

a = bfs()

if a == 10 **9:
    print (-1)
else:
    print (count - a - 1)

Submission status: Runtime Error

Solution code:
from collections import deque

h, w = map(int, input().split())
cnt = 0
maze = [[0]*w]*h
for y in range(h):
    maze[y] = list(input())
    for x in range(w):
        if maze[y][x] == ".":
            cnt +=1

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

def isWalk(x, y):
    if x<0 or x>=w or y<0 or y>=h or maze[y][x]=="#":
        return False
    else:
        return True

while 1:
    x, y = queue.popleft()
    if x==w-1 and y==h-1:
        print(cnt - cost[y][x] - 1)
        exit()
    else:
        for i, j in step:
            if isWalk(x+i, y+j) and cost[y+j][x+i]==-1:
                queue.append((x+i, y+j))
                cost[y+j][x+i] = cost[y][x] + 1

Submission status: Runtime Error

Solution code:
#D問題
H,W=map(int,input().split())
white=0
grids=[]
for i in range(H):
    grid=list(str(input()))
    white+=grid.count(".")
    grids.append(grid)
visited=[[-1 for i in range(W)] for j in range(H)]
visited[0][0]=0
def bfs(x,y):
    global visited
    global grids
    
    now=visited[y][x]
    if x == W-1 and y == H-1:
        return
    else:
        if x > 0:
            if visited[y][x-1] > now or visited[y][x-1] == -1:
                if grids[y][x-1] == ".":
                    visited[y][x-1]=now+1
                    bfs(x-1,y)
        if x < W-1:
            if visited[y][x+1] > now or visited[y][x+1] == -1:
                if grids[y][x+1] == ".":
                    visited[y][x+1]=now+1
                    bfs(x+1,y)
        if y > 0:
            if visited[y-1][x] > now or visited[y-1][x] == -1:
                if grids[y-1][x] == ".":
                    visited[y-1][x]=now+1
                    bfs(x,y-1)
        if y < H-1:
            if visited[y+1][x] > now or visited[y+1][x] == -1:
                if grids[y+1][x] == ".":
                    visited[y+1][x]=now+1
                    bfs(x,y+1)
bfs(0,0)
path=visited[H-1][W-1]+1
if path == 0:
    print(-1)
else:
    print(white-path)

Submission status: Runtime Error

Solution code:
#D問題
H,W=map(int,input().split())
white=0
grids=[]
for i in range(H):
    grid=list(str(input()))
    white+=grid.count(".")
    grids.append(grid)
visited=[[-1 for i in range(W)] for j in range(H)]
visited[0][0]=0
def bfs(x,y):
    global visited
    global grids
    
    now=visited[y][x]
    if x == W-1 and y == H-1:
        return
    else:
        if x > 0:
            if visited[y][x-1] > now or visited[y][x-1] == -1:
                if grids[y][x-1] == ".":
                    visited[y][x-1]=now+1
                    bfs(x-1,y)
        if x < W-1:
            if visited[y][x+1] > now or visited[y][x+1] == -1:
                if grids[y][x+1] == ".":
                    visited[y][x+1]=now+1
                    bfs(x+1,y)
        if y > 0:
            if visited[y-1][x] > now or visited[y-1][x] == -1:
                if grids[y-1][x] == ".":
                    visited[y-1][x]=now+1
                    bfs(x,y-1)
        if y < H-1:
            if visited[y+1][x] > now or visited[y+1][x] == -1:
                if grids[y+1][x] == ".":
                    visited[y+1][x]=now+1
                    bfs(x,y+1)
bfs(0,0)
path=visited[H-1][W-1]+1
print(white-path)

Submission status: Runtime Error

Solution code:
from collections import deque
#input sequences
H, W = map(int, input().split())
mtrx = [input() for i in range(H)]
dst = [[-1]*W for j in range(H)]


def bfs(dst,mtrx,sy, sx, gy, gx):
    queue = deque([[sy, sx]])
    dst[sy][sx] = 0
    #print(dst)
    while queue:
        y, x = queue.popleft()
        #print([y,x])
        if [y, x] == [gy, gx]:
            return int(dst[y][x])
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y+j, x+k
            if (0 <= new_x and new_x < W and 0 <= new_y and new_y < H):
                if mtrx[new_y][new_x] == "." and dst[new_y][new_x] == -1:
                    dst[new_y][new_x] = dst[y][x] + 1
                    queue.append([new_y, new_x])


cnt = 0

for c in mtrx:
	cnt += c.count('#')
#print(cnt)
#print(H*W)
#print(dst)
print(H*W - cnt - 1 -bfs(dst,mtrx,0, 0, H-1, W-1))

Submission status: Runtime Error

Solution code:
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(100000)

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1 or cost[y+1][x] != float('inf'):
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1 or cost[y-1][x] != float('inf'):
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1 or cost[y][x+1] != float('inf'):
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1 or cost[y][x-1] != float('inf'):
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Runtime Error

Solution code:
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(100000)

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

move_que = [[1,1]]

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(place):
  y,x = place
  if cost[y+1][x] != -1　or cost[y+1][x] != float('inf'):
      cost[y+1][x] = cost[y][x]+1
      move_que.append([y+1,x])       
      
  if cost[y-1][x] != -1 or cost[y-1][x] != float('inf'):
      cost[y-1][x] = cost[y][x]+1
      move_que.append([y-1,x])
  
  if cost[y][x+1] != -1 or cost[y][x+1] != float('inf'):
      cost[y][x+1] = cost[y][x]+1
      move_que.append([y,x+1])
  
  if cost[y][x-1] != -1 or cost[y][x-1] != float('inf'):
      cost[y][x-1] = cost[y][x]+1
      move_que.append([y,x-1])
  
while len(move_que) != 0:
  move(move_que[0])
  move_que = move_que[1:]

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Runtime Error

Solution code:
import sys

h,w = [int(i) for i in input().split()]

sys.setrecursionlimit(h*w)

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(y,x):
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move(y+1,x)
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move(y-1,x)
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move(y,x+1)
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move(y,x-1)
  

move(1,1)

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Runtime Error

Solution code:
h,w = [int(i) for i in input().split()]

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(y,x):
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move(y+1,x)
  
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move(y,x+1)
      
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move(y-1,x)
  
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move(y,x-1)
  

move(1,1)

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Runtime Error

Solution code:
h,w = [int(i) for i in input().split()]

s = [['#']*(w+2)] + [['#']+list(input())+['#'] for _ in range(h)] + [['#']*(w+2)]
#print(s)

cost = [[-1 if s[y][x] == '#' else float('inf') for x in range(w+2)] for y in range(h+2)]
cost[1][1] = 0
#print(cost)

def list_flatten(nested_list):
  flat_list = []
  fringe = [nested_list]
  
  while len(fringe) > 0:
    node = fringe.pop(0)
    if isinstance(node, list):
      fringe = node + fringe
    else:
      flat_list.append(node)

  return(flat_list)
      
def move(y,x):
  if cost[y-1][x] != -1:
    if cost[y-1][x] > cost[y][x]+1:
      cost[y-1][x] = cost[y][x]+1
      move(y-1,x)
  if cost[y+1][x] != -1:
    if cost[y+1][x] > cost[y][x]+1:
      cost[y+1][x] = cost[y][x]+1
      move(y+1,x)
  if cost[y][x-1] != -1:
    if cost[y][x-1] > cost[y][x]+1:
      cost[y][x-1] = cost[y][x]+1
      move(y,x-1)
  if cost[y][x+1] != -1:
    if cost[y][x+1] > cost[y][x]+1:
      cost[y][x+1] = cost[y][x]+1
      move(y,x+1)

move(1,1)

#print(cost)

if cost[h][w] == float('inf'):
  print(-1)
else:
  while_num = list_flatten(s).count('.')
  print(while_num - (cost[h][w]+1))

Submission status: Runtime Error

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import deque

def bfs(grid):
    h = len(grid)
    w = len(grid[0])
    
    dist = [[float('inf')]*w for _ in range(h)]
    
    que = deque([])
    que.append(((0,0), 1))
    dist[0][0] = 0
    
    drs = [-1,0,1,0]
    dcs = [0,-1,0,1]
    
    while que:
        (rcur, ccur), cost = que.popleft()
        if rcur == h-1 and ccur == w-1:
            return dist[h-1][w-1]
    
        for dr, dc in zip(drs, dcs):
            if not (0 <= rcur+dr < h and 0 <= ccur+dc < w):
                continue
            
            elif grid[rcur+dr][ccur+dc] == '#':
                continue
            
            elif dist[rcur+dr][ccur+dc] != float('inf'):
                continue
            
            dist[rcur+dr][ccur+dc] = cost + 1
            que.append(((rcur+dr, ccur+dc), cost+1))
            

h,w = li()
grid = [lc() for _ in range(h)]

white = 0
for row in grid:
    for col in row:
        if col == '.':
            white += 1

print(white - bfs(grid))

Submission status: Runtime Error

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

white = 0
for d in map:
    white += d.count('.')

memory = [(0,0)]
data = [[0] * W for _ in range(H)]
data[0][0] = 1
direction = [(0,1), (0,-1), (1,0), (-1,0)]
while True:
    x, y = memory.pop(0)
    for dx, dy in direction:

        if x + dx == H - 1 and y + dy == W-1:
            print(white - (data[x][y] + 1))
            exit()
        if 0 <= x + dx < H and 0 <= y + dy < W:
            if map[x+dx][y+dy] == '.' and data[x+dx][y+dy] == 0:
                data[x+dx][y+dy] = data[x][y] + 1
                memory.append((x+dx, y+dy))

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
MA = [list(input().strip()) for _ in range(H)]
VI = [[-1] * W for _ in range(H)]

kabe = 0
for i in range(H):
    kabe += MA[i].count("#")

from collections import deque


def bfs(ma, vi):
    Q = deque([(0,0)])
    sy, sx = (0,0)
    vi[sy][sx] = 0
    while True:
        q = Q.popleft()
        y, x = q
        if q == (H-1,W-1):
            return vi[y][x]
        for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
            nq = y + dy, x + dx
            ny, nx = nq
            if 0 <= ny < H and 0 <= nx < W and vi[ny][nx] == -1:
                if ma[ny][nx] == '.':
                    Q.append(nq)
                    vi[ny][nx] = vi[y][x] + 1



print(H * W - kabe - bfs(MA, VI) - 1)

Submission status: Runtime Error

Solution code:
H,W=map(int, input().split())
s=[list(input()) for _ in range(H)]
d=[[9999999999999 for _ in range(W)] for _ in range(H)]
def bfs(h, w, c):
	if d[h][w] <= c:
		return
	d[h][w] = c
	for dh,dw in [(0, -1), (-1, 0), (0, 1), (1, 0)]:
		if h+dh >= 0 and w+dw >= 0 and h+dh < H and w+dw < W and s[h+dh][w+dw] == ".":
			bfs(h+dh, w+dw, c+1)
bfs(0, 0, 1)
print(H*W-d[H-1][W-1]-sum(map(lambda x: x.count("#"), s)))

Submission status: Runtime Error

Solution code:
H,W=map(int, input().split())
s=[list(input()) for _ in range(H)]
d=[[H*W for _ in range(W)] for _ in range(H)]
def dfs(h, w, c):
	if d[h][w] <= c:
		return
	d[h][w] = c
	for dh,dw in [(0, -1), (-1, 0), (0, 1), (1, 0)]:
		if h+dh >= 0 and w+dw >= 0 and h+dh < H and w+dw < W and s[h+dh][w+dw] == ".":
			dfs(h+dh, w+dw, c+1)
dfs(-1, 0, 0)
print(H*W-d[H-1][W-1]-sum(map(lambda x: x.count("#"), s)))

Submission status: Runtime Error

Solution code:
h, w = map(int, input().split())
grid = [[c == "." for c in input()] for i in range(h)]
if not (grid[0][0] and grid[-1][-1]):
    print(-1)
else:
    print(grid[1000000])

Submission status: Runtime Error

Solution code:
from collections import deque
R,C = map(int,input().split())
sy,sx = 1,1  #スタートの座標
gy,gx = R,C  #ゴールの座標
L = []
for i in range(R):
  L.append(list(input()))   #迷路の情報を受け取る
dy_dx = [[1,0],[-1,0],[0,1],[0,-1]]   #移動
que = deque([[sy-1,sx-1]])   #queには次に見るべき座標が入る。括弧が二重になっていることに留意
L[sy-1][sx-1] = 0  #スタートの座標（迷路上）の情報を0に
while len(que) > 0:  #queが空でないときは
  cur = que.popleft()   #queの一番左を見る
  for i in range(4):  #現在見ているマスの上下左右をチェック
    if 0 <= cur[0]+dy_dx[i][0] <= R-1 and 0 <= cur[1]+dy_dx[i][1] <= C-1:  #移動した後も迷路内にあるかの確認
      if L[cur[0]+dy_dx[i][0]][cur[1]+dy_dx[i][1]] == '.':  #まだ見ていない通路であれば
        L[cur[0]+dy_dx[i][0]][cur[1]+dy_dx[i][1]] = L[cur[0]][cur[1]]+1  #現在見ているマスの手数+1を入れる
        que.append([cur[0]+dy_dx[i][0],cur[1]+dy_dx[i][1]])   #queの末尾に今チェックした座標を入れる
black = 0
for i in range(R):
  for j in range(C):
    if L[i][j] == '#':
      black += 1
print(R*C-L[gy-1][gx-1]-1-black)

Submission status: Runtime Error

Solution code:
#方針 最短経路以外を黒に塗れば良い
#最短経路が複数あってもその時通る白マスの数は不変なので、黒く塗れる白マスの数も不変である。
#したがって最短経路を求め(この時+1が実際に通る白マスの数になる)元々の白マスの数から
#最短経路+1を減算すれば答えは求まることになる。

from collections import deque

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

white_panel_cnt = 0
for y in range(H):
    for x in range(W):
        if maze[y][x] == '.':
            white_panel_cnt += 1
que = deque()

#スタート位置は(1,1)※list的には(0,0)になっている
sx,sy,gx,gy = (0,0,W-1,H-1)
que.append((sx,sy))
distance_from_start = [[-1]*W for _ in range(H)]
distance_from_start[sy][sx] = 0
move = [[1,0],[-1,0],[0,1],[0,-1]]

def minimum_distance():
    while len(que) != 0:
        x,y = que.popleft()
        #for i in range(len(distance_from_start)):
            #print(distance_from_start[i])
        if x == gx and y == gy:
            return distance_from_start[y][x]
        for i in range(4):
            next_x = x + move[i][0]
            next_y = y + move[i][1]
            #print(next_x,next_y)
            if next_x < 0 or next_x >= W or next_y < 0 or next_y >= H or distance_from_start[next_y][next_x] != -1 or maze[next_y][next_x] == '#':
                continue
            #print(distance_from_start[y][x])
            distance_from_start[next_y][next_x] = distance_from_start[y][x] + 1
            que.append((next_x,next_y))
        #for i in range(len(distance_from_start)):
            #print(distance_from_start[i])

distance = minimum_distance()
#print('distance={}'.format(distance))
if distance == -1:
    score = -1
else :
    score = white_panel_cnt-(distance+1)

print(score)

Submission status: Runtime Error

Solution code:
import Queue
def main():
H,W=map(int,raw_input().split())
    s=[raw_input() for i in range(H)]
    print(s)
    q=Queue.Queue()
    visited=[[False]*W for _ in range(H)]
    dist=[[1145141919810]*W for _ in range(H)]
    visited[0][0]=True
    dist[0][0]=0
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    q.put((0,0))

    while not q.empty():
        x,y=q.get()
        for i in range(4):  
            xx=x+dx[i]
            yy=y+dy[i]
            if (not 0<=xx<H) or (not 0<=yy<W): continue
            if s[xx][yy] == "#" :continue
            if visited[xx][yy]:continue
            visited[xx][yy]=True
            dist[xx][yy]=dist[x][y]+1
            q.put((xx,yy))
    if dist[H-1][W-1]:
        print(-1)
        return
    use=[[False]*W for _ in range(H)]
    use[H-1][W-1]=True
    use[0][0]=True
    (x,y)=(H-1, W-1)
    while (x,y) != (0,0):
        use[x][y]=True
        mpos=(-1,-1)
        mval=1145141919
        for i in range(4):
            xx=x+dx[i]
            yy=y+dy[i]
            if (not 0<=xx<H) or (not 0<=yy<W): continue     
            if dist[xx][yy] < mval:
                mpos=(xx,yy)
                mval=dist[xx][yy]
        x,y=mpos
    cnt=0
    for x in range(H):
        for y in range(W):
            if s[x][y] == "." and not use[x][y]: cnt+=1
    print(cnt)

Submission status: Runtime Error

Solution code:
ans=chk=0
h,w=map(int,input().split())
d=[[0]*w for i in range(h)]
l=[]
for i in range(h):
    a=input()
    chk+=a.count("#")
    l.append(a)
p=set([(0,0)])
while len(p):
    a,b=p.pop()
    for y,x in xy:
        y+=a
        x+=b
        if 0<=y<h and 0<=x<w and l[y][x]!="#":
            if d[y][x]==0 or d[y][x]>d[a][b]+1:
                d[y][x]=d[a][b]+1
                p.add((y,x))

print(-1 if d[h-1][w-1]==0 else h*w-1-chk-d[h-1][w-1])

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
##計算の都合、 通路(.)を正の整数、壁(#)を-1に変換する
Mij = [[0] * W for _ in range(H)]
space_count = 0
for i in range(H):
    s = input()
    for j in range(W):
        if s[j] == ".":
            space_count += 1
            Mij[i][j] = 100000
        else:
            Mij[i][j] = -1

dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]

def search(i, j, step):
    if i == H - 1 and j == W - 1:
        return step

    best = None
    for d in dirs:
        i2 = i + d[0]
        j2 = j + d[1]
        if 0 <= i2 < H and 0 <= j2 < W:
            if step + 1 < Mij[i2][j2]:
                Mij[i2][j2] = step
                r = search(i2, j2, step + 1)
                if not r:
                    continue
                if not best or best > r:
                    best = r
    return best

total_steps = search(0, 0, 1)
if total_steps is None:
    print(-1)
else:
    print(space_count - total_steps)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
M = [[float('inf') for _ in range(W)] for _ in range(H)]


def dfs(x, y, c):
    cc = float('inf')
    for xx, yy in [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)]:
        if (H, W) == (yy + 1, xx + 1):
            return c + 1
        if 0 <= yy < H and 0 <= xx < W and S[yy][xx] == '.' and \
                (M[yy][xx] > c + 1):
            M[yy][xx] = c + 1
            cc = min(cc, dfs(xx, yy, c + 1))
    return cc


def main():
    ans = 0
    for i in range(H):
        ans += S[i].count('.')
    c = dfs(0, 0, 1)
    if c == float('inf'):
        print(-1)
    else:
        print(ans - c)


main()

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
M = {(0, 0): 1}


def dfs(x, y, c):
    cc = float('inf')
    for xx, yy in [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)]:
        if (H, W) == (yy + 1, xx + 1):
            return c + 1
        if 0 <= yy < H and 0 <= xx < W and S[yy][xx] == '.' and \
                ((xx, yy) not in M or M[(xx, yy)] > c + 1):
            M[(xx, yy)] = c + 1
            cc = min(cc, dfs(xx, yy, c + 1))
    return cc


def main():
    dfs(0, 0, 1)
    # ans = 0
    # for i in range(H):
    #     ans += S[i].count('.')
    # c = dfs(0, 0, 1)
    # if c == float('inf'):
    #     print(-1)
    # else:
    #     print(ans - c)


main()

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
M = {(0, 0): 1}


def dfs(x, y, c):
    cc = float('inf')
    for xx, yy in [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)]:
        if (H, W) == (yy + 1, xx + 1):
            return c + 1
        if 0 <= yy < H and 0 <= xx < W and S[yy][xx] == '.' and \
                ((xx, yy) not in M or M[(xx, yy)] > c + 1):
            M[(xx, yy)] = c + 1
            cc = min(cc, dfs(xx, yy, c + 1))
    return cc


def main():
    ans = 0
    for i in range(H):
        ans += S[i].count('.')
    c = dfs(0, 0, 1)
    if c == float('inf'):
        print(-1)
    else:
        print(ans - c)


main()