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:
import sys
import numpy as np
from heapq import heappop, heappush


def main():
    H, W = map(int, sys.stdin.readline().split())

    grid = np.array([list(sys.stdin.readline().rstrip()) for _ in range(H)])
    grid = np.pad(grid, 1, constant_values=('#'))

    can_go = False
    i = j = 1 # start
    c = 0     # real cost
    h = max(H - 1, W - 1) # goalまでの推定cost 
    s = c + h # score
    q = [] # open list
    heappush(q, (s, c, i, j))
    visited = set() # closed list
    # parent = [[None * (W + 1)] for _ in range(H+1)]

    while q:
        s, c, i, j = heappop(q)
        visited.add((i, j))
        if c == s:
            can_go = True
            break
        for dy, dx in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            y = i + dy
            x = j + dx
            if grid[y][x] == '.' and not (y, x) in visited:
                visited.add((y, x))
                h = max(H - y, W - x)
                s = h + c + 1
                heappush(q, (s, c+1, y, x))
 
    if can_go:
        ans = np.sum(grid == '.') - (c + 1)
    else:
        ans = -1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import deque

h, w = map(int, input().split())
p = (input() for i in range(h))

# メモ配列
INF = 10**7
memo = [[INF]*w for i in range(h)]

# 白マスをカウント
wcnt = 0
for i in p:
    for j in i:
        if j == '.':
            wcnt+=1

# 幅探索用キュー初期化
q = deque()
q.append((0, 0))
memo[0][0]  = 0

# 探索用ベクトル
vx = (0, -1, 0, 1)
vy = (-1, 0, 1, 0)

ans = -1
for i in range(INF):
    # キューが空なら終了
    if len(q) == 0:
        break
        
    # キューから一つ取り出す
    x, y = map(int, q.pop())
    
    # ゴールなら終了
    if x == w-1 and y == h-1:
        ans = memo[y][x]
        break
        
    # 4方向の距離を確定して、エンキューする
    for j in range(4):
        nx, ny = x+vx[j], y+vy[j]
        
        # エリア外 or 探索済み or 黒色なら探索しない
        if nx < 0 or w <= nx or ny < 0 or h <= ny or memo[ny][nx] != INF or p[ny][nx] == '#':
            continue
            
        memo[ny][nx] = memo[y][x]+1
        q.appendleft((nx, ny))

if ans == -1:
    print(ans)
else:
    print(wcnt-ans-1)

Submission status: Runtime Error

Solution code:
from collections import deque
def bfs():
    d=[[float("inf")]*w for i in range(h)]
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    que=deque([])
    que.append((0,0))
    d[0][0]=0
    while que:
        p=que.popleft()
        if p[0]==h-1 and p[1]==w-1:
            break
        for i in range(4):
            nx=p[0]+dx[i]
            ny=p[1]+dy[i]
            if 0<=nx and nx<h and 0<=ny and ny<w and maze[nx][ny]!="#" and d[nx][ny]==float("inf"):
                que.append((nx,ny))
                d[nx][ny]=d[p[0]][p[1]]+1
    return d[h][w]

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

if d[h][w]!=inf:
    ans=h*w-d[h][w]-1-maze.count("#")
else:
    ans=-1

print(ans)

Submission status: Runtime Error

Solution code:
H, W=map(int, input().split())
m=[[-1 for i in range(W+2)]]
mm=[[-1]+[0 for j in range(W)]+[-1] for i in range(H)]
m=m+mm+m
m[1][1]=1

counter0=0
for i in range(1, H+1):
  c=input()
  for j in range(1, W+1):
    if c[j-1]=='#':
      mm[i][j]=-1
    else:
      counter0+=1
      
def f(math, kazu, h, w):
  cha=0
  for i in range(1, h+1):
    for j in range(1, w+1):
      if math[i][j]==kazu:
        if math[i-1][j]==0:
          math[i-1][j]=kazu+1
          cha=1
        if math[i+1][j]==0:
          math[i+1][j]=kazu+1
          cha=1
        if math[i][j-1]==0:
          math[i][j-1]=kazu+1
          cha=1
        if math[i][j+1]==0:
          math[i][j+1]=kazu+1
          cha=1
  return math, cha

cha=1
i=1
while cha==1:
  m, cha=f(m, i, H, W)
  i+=1
  
if m[H][W]==0:
  out=-1
else:
  out=counter0-m[H][W]
  
print(out)

Submission status: Runtime Error

Solution code:
import queue
h,w = map(int,input().split())
mas = []
black_num = 0
for i in range(h):
    row = list(input())
    mas.append(row)
for i in range(h):
    for j in range(w):
        if mas[i][j] == "#":
            black_num += 1
dx = [0,0,1,-1]
dy = [1,-1,0,0]
def bfs():
    q = queue.Queue()
    q.put([0,0])
    step = mas.copy()
    for i in range(h):
        for j in range(w):
            step[i][j] = -1
    step[0][0] = 0
    while not q.empty():
        s = q.get()
        if s[0] == h-1 and s[1] == w-1:
            break
        for i in range(4):
            nx = s[0] + dx[i]
            ny = s[1] + dy[i]
            if(0 <= nx < h and 0 <= ny < w and mas[nx][ny] !="#" and step[nx][ny] == -1):
                q.put([nx,ny])
                step[nx][ny] = step[s[0]][s[1]] + 1
    return ste[h-1][w-1]

least = bfs()
if(least == -1):
    print(-1)
else:
    print(h * w - black_num - least - 1)

Submission status: Runtime Error

Solution code:
from collections import deque
 
qx = deque([])
qy = deque([])
 
nowx = 0
nowy = 0
tmpx = 0
tmpy = 0
 
ans = -1
cnt = 1
m = []
 
sx=[0,1,0,-1]
sy=[1,0,-1,0]
H,W = map(int, input().split())
for i in range(H):
    m.append(list(input()))
f = 0
p=[[999 for i in range(W)] for j in range(H)]
 
qx.append(nowx)
qy.append(nowy)
p[nowx][nowy]=0
 
while(len(qx) > 0 and f == 0):
    nowx = qx.popleft()
    nowy = qy.popleft()
    for i in range(4):
        tmpx = nowx + sx[i]
        tmpy = nowy + sy[i]
        if (tmpx < 0 or tmpx > W-1 or tmpy < 0 or tmpy > H-1):
            continue
        if (m[tmpy][tmpx] == '#'):
            continue
        if (tmpx == W-1 and tmpy == H-1):
            p[tmpy][tmpx] = p[nowy][nowx]+1
            ans = p[nowy][nowx]+1
            f = 1
            break
        if (p[tmpy][tmpx] > p[nowy][nowx]+1):
            p[tmpy][tmpx] = p[nowy][nowx]+1
            qx.append(tmpx)
            qy.append(tmpy)
 
ans2 = sum(x.count('.') for x in m) - ans -1 
print(ans2)
 
from collections import deque

qx = deque([])
qy = deque([])

nowx = 0
nowy = 0
tmpx = 0
tmpy = 0

ans = 0
cnt = 1
m = []

sx=[0,1,0,-1]
sy=[1,0,-1,0]
H,W = map(int, input().split())
for i in range(H):
    m.append(list(input()))
f = 0
p=[[999 for i in range(W)] for j in range(H)]

qx.append(nowx)
qy.append(nowy)
p[nowx][nowy]=0

while(len(qx) > 0 and f == 0):
    nowx = qx.popleft()
    nowy = qy.popleft()
    for i in range(4):
        tmpx = nowx + sx[i]
        tmpy = nowy + sy[i]
        if (tmpx < 0 or tmpx > W-1 or tmpy < 0 or tmpy > H-1):
            continue
        if (m[tmpy][tmpx] == '#'):
            continue
        if (tmpx == W-1 and tmpy == H-1):
            p[tmpy][tmpx] = p[nowy][nowx]+1
            ans = p[nowy][nowx]+1
            f = 1
            break
        if (p[tmpy][tmpx] > p[nowy][nowx]+1):
            p[tmpy][tmpx] = p[nowy][nowx]+1
            qx.append(tmpx)
            qy.append(tmpy)

if(ans == -1):
    ans2 = -1
else:
    ans2 = sum(x.count('.') for x in m) - ans -1 
print(ans2)

Submission status: Runtime Error

Solution code:
#ABC088D - Grid Repainting
from collections import deque
import sys
def bfs():
    d = [[float("inf")]*W for i in range(H)]
    
    que=deque([])
    que.append((0,0))
    d[0][0] = 0
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0<= nx < W and 0<= ny < H and d[nx][ny] == float("inf") and maze[nx][ny] != "#":
                que.append((nx,ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
            if nx == W-1 and ny == H-1:
                return d[nx][ny]
                break
    if d[W-1][H-1] == float("inf"):
        print(-1)
        sys.exit()
    
H, W = list(map(int,input().split()))
maze = []
count = 0
for i in range(H):
    l = list(input())
    maze.append(l)
    count += l.count(".")

print(count-1-bfs())

Submission status: Runtime Error

Solution code:
#ABC088D - Grid Repainting
from collections import deque
import sys
def bfs():
    d = [[float("inf")]*W for i in range(H)]
    
    que=deque([])
    que.append((0,0))
    d[0][0] = 0
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0<= nx < W and 0<= ny < H and d[nx][ny] == float("inf") and maze[nx][ny] != "#":
                que.append((nx,ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
            if nx == W-1 and ny == H-1:
                return d[nx][ny]
                break
    if d[W-1][H-1] == float("inf"):
        print("-1")
        sys.exit()
    
H, W = list(map(int,input().split()))
maze = []
count = 0
for i in range(H):
    l = list(input())
    maze.append(l)
    count += l.count(".")

print(count-1-bfs())

Submission status: Runtime Error

Solution code:
#ABC088D - Grid Repainting
from collections import deque
import sys
def bfs():
    d = [[float("inf")]*W for i in range(H)]
    
    que=deque([])
    que.append((0,0))
    d[0][0] = 0
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if nx == W-1 and ny == H-1:
                return d[nx][ny]
                break
            if 0<= nx < W and 0<= ny < H and d[nx][ny] == float("inf") and maze[nx][ny] != "#":
                que.append((nx,ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
            
    if d[W-1][H-1] == float("inf"):
        print("-1")
        sys.exit()
    
H, W = list(map(int,input().split()))
maze = []
count = 0
for i in range(H):
    l = list(input())
    maze.append(l)
    count += l.count(".")

print(count-1-bfs())

Submission status: Runtime Error

Solution code:
#ABC088D - Grid Repainting
from collections import deque
import sys
def bfs():
    d = [[float("inf")]*W for i in range(H)]
    
    que=deque([])
    que.append((0,0))
    d[0][0] = 0
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if nx == W-1 and ny == H-1:
                return d[nx][ny]
                break
            if 0<= nx < W and 0<= ny < H and d[nx][ny] == float("inf") and maze[nx][ny] != "#":
                que.append((nx,ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
            
    if d[W-1][H-1] == float("inf"):
        print("-1")
        sys.exit()
    
H, W = list(map(int,input().split()))
maze = []
count = 0
for i in range(H):
    l = list(input())
    maze.append(l)
    count += l.count(".")

print(count-2-bfs())

Submission status: Runtime Error

Solution code:
#ABC088D - Grid Repainting
from collections import deque
import sys
def bfs():
    d = [[float("inf")]*W for i in range(H)]
    
    que=deque([])
    que.append((0,0))
    d[0][0] = 0
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0<= nx < W and 0<= ny <= H and d[nx][ny] == float("inf") and maze[nx][ny] != "#":
                que.append((nx,ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
            if nx == W-1 and ny == H-1:
                return d[nx][ny]
                break
    if d[W-1][H-1] == float("inf"):
        print("-1")
        sys.exit()
    
H, W = list(map(int,input().split()))
maze = []
count = 0
for i in range(H):
    l = list(input())
    maze.append(l)
    count += l.count(".")

print(count-2-bfs())

Submission status: Runtime Error

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

white = 0

for i in range(H):
    white += s[i].count(".")


q = deque()
q.append((0, 0))

g = [[10**9]*W for i in range(H)]
g[0][0] = 0
for i in range(H*W):
    x, y = q.popleft()
    if (x, y) == (H-1, W-1):
        break
    else:
        if x < H-1 and s[x+1][y] == ".":
            if g[x+1][y] == 10**9:
                q.append((x+1, y))
            g[x+1][y] = min(g[x+1][y], g[x][y]+1)
        if y < W-1 and s[x][y+1] == ".":
            if g[x][y+1] == 10**9:
                q.append((x, y+1))
            g[x][y+1] = min(g[x][y+1], g[x][y]+1)
        if x > 0 and s[x-1][y] == ".":
            if g[x-1][y] == 10**9:
                q.append((x-1, y))
            g[x-1][y] = min(g[x-1][y], g[x][y]+1)
        if y > 0 and s[x][y-1] == ".":
            if g[x][y-1] == 10**9:
                q.append((x, y-1))
            g[x][y-1] = min(g[x][y-1], g[x][y]+1)
if g[H-1][W-1] == 10**9:
    print(-1)
else:
    print(white - (g[H-1][W-1]+1))

Submission status: Runtime Error

Solution code:
count = 0

# for i in range(H):
#     for j in range(W):
#         if field[i][j] == start:
#             sy, sx = i, j
#         elif field[i][j] == goal:
#             gy, gx = i, j
sy,sx = 0,0
gy,gx = H-1,W-1
seen = [[0 for i in range(W)] for j in range(H)]
queue = [[sy,sx]]
flag = False
while queue != []:
    h,w = queue.pop(0)
    before = seen[h][w]
    for i in range(4):
        nh = h + dy[i]
        nw = w + dx[i]
        if (nh == gy) and (nw == gx):
            count = before+1
            flag = True
        if (0<=nh<H) and (0<=nw<W):
            if field[nh][nw] != 'X':
                if seen[nh][nw] == 0:
                    seen[nh][nw] = before+1
                    queue.append([nh,nw])
    if flag:
        break
whites = 0
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            whites += 1
if count != 0 :
    print(whites - count-1)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
c1 = list(map(int, input().split()))
c2 = list(map(int, input().split()))
c3 = list(map(int, input().split()))

c = c1 + c2 + c3

if sum(c) % 3 == 0 and c[0] + c[4] + c[8] == c[1] + c[3] + c[8]:
    print("Yes")
else:
    print("No")

Submission status: Runtime Error

Solution code:
import sys
import collections


def solve():
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    h, w = list(map(int, input().rstrip('\n').split()))
    s = [list(str(input().rstrip('\n'))) for _ in range(h)]
    ql = [[0, 0, 0]]
    ql = collections.deque(ql)
    fq = collections.defaultdict(list)
    fq[0, 0]
    mt = 10 ** 10
    while True:
        if len(ql) != 0:
            cost, xv, yv = ql.popleft()
            if xv == h - 1 and yv == w - 1:
                mt = min(mt, cost)
            for xv, yv in [[xv + 1, yv], [xv - 1, yv], [xv, yv + 1], [xv, yv - 1]]:
                if 0 <= xv < h and 0 <= yv < w:
                    if (xv, yv) not in fq and s[xv, yv] != "#":
                        ql.append([cost + 1, xv, yv])
                        fq[xv, yv]
        else:
            break
    if mt == 10 ** 10:
        print(-1)
    else:
        cnt = 0
        for i in range(h):
            cnt += s[i].count("#")
        print(h * w - cnt - (mt + 1))


if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!
H,W=map(int,input().split())
S=[]
        
for _ in range(H):
    S.append(list(input()))

def bfs(h,w,num):
    if h==H-1 and w==W-1:
        print(num)
        exit()
    if h!=0:
        if S[h-1][w]!="#":
            temp.append([h-1,w])
    if w!=0:
        if S[h][w-1]!="#":
            temp.append([h,w-1])
    if h!=H:
        if S[h+1][w]!="#":
            temp.append([h+1,w])
    if w!=W:
        if S[h][w+1]!="#":
            temp.append([h,w+1])
    
q=[[0,0]]
temp=[]

while True:
    while q:
        bfs(q.pop(0))
    q=temp[:]

Submission status: Runtime Error

Solution code:
def main():
    h, w = map(int, input().split())
    G = [list(input()) for i in range(h)]
    dy, dx = [-1, 1, 0, 0], [0, 0, -1, 1]
    
    dist = [[-1 for j in range(w)] for i in range(h)]
    que = deque()
    px = [[-1 for j in range(w)] for i in range(h)]
    py = [[-1 for j in range(w)] for i in range(h)]
    dist[0][0] = 0
    que.append((0, 0))
    while (len(que) != 0):
        y, x = que[0][0], que[0][1]
        que.popleft()

        for i in range(4):
            ny, nx = y+dy[i], x+dx[i]
            if (ny < 0) or (h <= ny) or (nx < 0) or (w <= nx):
                continue
            if G[ny][nx] == "#":
                continue
            if dist[ny][nx] == -1:
                dist[ny][nx] = dist[y][x] + 1
                py[ny][nx], px[ny][nx] = y, x
                que.append((ny, nx))

    if dist[h-1][w-1] == -1:
        print(dist[h-1][w-1])
    else:
        y, x = h - 1, w - 1
        while y != -1 and x != -1:
            G[y][x] = "o"
            y, x = py[y][x], px[y][x]
        ans = 0
        for i in G:
            for j in i:
                if j == ".":
                    ans += 1
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import deque

def bfs(maze,visited,sy,sx,gy,gx):
    Step = ([1,0],[0,1],[-1,0],[0,-1])
    
    que = deque([[sx,sy]])
    visited[sx][sy] = 1
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in Step:
            ny,nx = y+j , x+k
            if 0 <= ny <= gy and 0 <= nx <= gx:
                if maze[ny][nx] == '.' and visited[ny][nx] == INF:
                    visited[ny][nx] = visited[y][x] + 1
                    que.append([ny,nx])


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

cntSharp = 0
for i in range(h):
    cntSharp += maze[i].count('.')

INF = 10**5
visited = [[INF]*w for _ in range(h)]

sx,sy = 0,0
gy,gx = h-1,w-1

minStep = bfs(maze,visited,sy,sx,gy,gx)
print(cntSharp - minStep)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)
from collections import deque
from itertools import chain

def bfs(maze,visited,gy,gx):
    que = deque([[0,0]])
    visited[0][0] = 0
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if 0 <= ny < w and 0 <= nx < h:
                if maze[ny][nx] == "." and visited[ny][nx] == -1:
                    visited[ny][nx] = visited[y][x] + 1
                    que.append([ny,nx])

h,w = map(int,input().split())
maze = [input() for _ in range(h)]
visited = [[-1]*(w) for _ in range(h)]
sr = bfs(maze,visited,h-1,w-1)

num_dot = list(chain.from_iterable(maze))
num_dot = num_dot.count('.')

if sr == -1 or num_dot < sr:
    print(-1)
else:
    print(num_dot - sr - 1)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)
from collections import deque
from itertools import chain

def bfs(maze,visited,gy,gx):
    que = deque([[0,0]])
    visited[0][0] = 0
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if 0 <= ny < w and 0 <= nx < h:
                if maze[ny][nx] == "." and visited[ny][nx] == -1:
                    visited[ny][nx] = visited[y][x] + 1
                    que.append([ny,nx])

h,w = map(int,input().split())
maze = [input() for _ in range(h)]
visited = [[-1]*(w) for _ in range(h)]
sr = bfs(maze,visited,h-1,w-1)

num_dot = list(chain.from_iterable(maze))
num_dot = num_dot.count('.')
print(num_dot - sr - 1)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)

from collections import deque
from itertools import chain

def bfs(maze,visited,gy,gx):
    que = deque([[1,1]])
    visited[1][1] = 0
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if maze[ny][nx] == "." and visited[ny][nx] == -1:
                visited[ny][nx] = visited[y][x] + 1
                que.append([ny,nx])

h,w = map(int,input().split())
maze = ["#"*(w+2)] + ["#"+input()+"#" for _ in range(h)] + ["#"*(w+2)]
visited = [[-1]*(w+2) for _ in range(h+2)]
sr = bfs(maze,visited,h,w)

num_dot = list(chain.from_iterable(maze))
num_dot = num_dot.count('.')
print(num_dot - sr - 1)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**8)

from collections import deque
from itertools import chain

def bfs(maze,visited,gy,gx):
    que = deque([[1,1]])
    visited[1][1] = 0
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if maze[ny][nx] == "." and visited[ny][nx] == -1:
                visited[ny][nx] = visited[y][x] + 1
                que.append([ny,nx])

h,w = map(int,input().split())
maze = ["#"*(w+2)] + ["#"+input()+"#" for _ in range(h)] + ["#"*(w+2)]
visited = [[-1]*(w+2) for _ in range(h+2)]
sr = bfs(maze,visited,h,w)

num_dot = list(chain.from_iterable(maze))
num_dot = num_dot.count('.')
num_sharp = h*w - num_dot
print(h*w - num_sharp - sr - 1)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)

from collections import deque
from itertools import chain

def bfs(maze,visited,gy,gx):
    que = deque([[1,1]])
    visited[1][1] = 0
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if maze[ny][nx] == "." and visited[ny][nx] == -1:
                visited[ny][nx] = visited[y][x] + 1
                que.append([ny,nx])

h,w = map(int,input().split())
maze = ["#"*(w+2)] + ["#"+input()+"#" for _ in range(h)] + ["#"*(w+2)]
visited = [[-1]*(w+2) for _ in range(h+2)]
sr = bfs(maze,visited,h,w)

num_dot = list(chain.from_iterable(maze))
num_dot = num_dot.count('.')
num_sharp = h*w - num_dot
print(h*w - num_sharp - sr - 1)

Submission status: Runtime Error

Solution code:
from collections import deque
from itertools import chain

def bfs(maze,visited,gy,gx):
    que = deque([[1,1]])
    visited[1][1] = 0
    
    while que:
        y,x = que.popleft()
        if [y,x] == [gy,gx]:
            return visited[y][x]
        for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx = y+j,x+k
            if maze[ny][nx] == "." and visited[ny][nx] == -1:
                visited[ny][nx] = visited[y][x] + 1
                que.append([ny,nx])

h,w = map(int,input().split())
maze = ["#"*(w+2)] + ["#"+input()+"#" for _ in range(h)] + ["#"*(w+2)]
visited = [[-1]*(w+2) for _ in range(h+2)]
sr = bfs(maze,visited,h,w)

num_dot = list(chain.from_iterable(maze))
num_dot = num_dot.count('.')
num_sharp = h*w - num_dot
print(h*w - num_sharp - sr - 1)

Submission status: Runtime Error

Solution code:
from collections import deque
h,w = map(int,input().split())
list1 = [list(input()) for i in range(h) ]
visited = [[-1]*w for i in range(h)]
black_count = 0
for i in range(h):
	black_count += list1[i].count("#")
def bfs(maze, visited, sy, sx, gy, gx):
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        if [y, x] == [gy, gx]:
            return visited[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_y < h and \
				0 <= new_x < w and\
				maze[new_y][new_x] == "." and \
                visited[new_y][new_x] == -1:
				
                visited[new_y][new_x] = visited[y][x] + 1
                queue.append([new_y, new_x])

shortest = bfs(list1,visited,0,0,h-1,w-1)

print(h*w - black_count - shortest-1) #-1はスタート地点

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
maze = []
start = (0,0)
wall = 1
goal = 2
block = 0
for i in range(h):
	row = input()
	row_int = []
	for i in list(row):
		if i == "#":
			row_int.append(1)
			block += 1
		elif i == ".":
			row_int.append(0)
	maze.append(row_int)

maze[h-1][w-1] = 2

def in_map(x,y):
	return 0 <= x <= w-1 and 0 <= y <= h-1

def bfs(maze,y,x):
	if maze[y][x] == goal:
		return [(y,x)]
	maze[y][x] = wall
	for (next_y,next_x) in [(y+1, x), (y, x+1), (y, x-1), (y-1, x)]:
		if not in_map(next_x,next_y):
			continue
		if maze[next_y][next_x] == wall :
			continue
		route = bfs(maze,next_y,next_x)
		if route:
			return [(y,x)] + route

print(h*w - len(bfs(maze,0,0)) - block)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
sy = 0
sx = 0
gy = H-1
gx = W-1
c = []
d = [[-1 for i in range(W)] for j in range(H)]
d[sy][sx] = 0
cnt=0
for i in range(H):
	c.append(input())
for j in range(H):
  cnt=cnt+c[j].count(".")

dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
q = deque()
q.append([sy, sx, 0])
while len(q) != 0:
	y, x, w = q[0]
	if y == gy and x == gx:
		break

	for i in range(4):
		ny, nx = y + dirr[i][0], x + dirr[i][1]
		if ny>=0 and nx>=0 and ny<H and nx<W and d[ny][nx] == -1 and c[ny][nx] != "#":
			q.append([ny, nx, w + 1])
			d[ny][nx] = w + 1

	q.popleft()

if d[gy][gx]==-1:
  print(-1)
else:
  print(cnt-w-1)

Submission status: Runtime Error

Solution code:
import copy

h, w = list(map(int, input().split()))
sharp = 0
D = []
for i in range(h):
    D.append(list(input()))
    # #の数を数えておく
    sharp += D[i].count('#')
ans = []
def dfs(row, column, count,data,ans):
    #もし配列の外を参照しているようであれば終了させる
    if(row > w - 1) or (column > h - 1) or ( row < 0 ) or ( column < 0 ):
        return

    if data[column][row] == '#':
        return
    #探索済みなので＃を入れたが、もっと良い方法があるかもしれない
    data[column][row] = '#'
    #その場所がゴールならば終了。ansにそこまでのコストを追加
    if column == h - 1 and row == w - 1:
        count += 1
        ans.append(count)
        return

    else:
        count += 1
        s = copy.deepcopy(data)
        ##dataの写しを引数として渡したい。参照渡しか値渡しかを確認
        #+-1ずつ四方向に全探索
        dfs(row + 1, column,     count, s,ans)
        dfs(row,     column + 1, count, s,ans)
        dfs(row - 1, column,     count, s,ans)
        dfs(row,     column - 1, count, s,ans)
        return

dfs(0, 0, 0,D,ans)
if len(ans) == 0:
    print(-1)
else:
    k = min(ans)
print(h * w - sharp - k)

Submission status: Runtime Error

Solution code:
h, w = list(map(int, input().split()))
sharp = 0
data = []
for i in range(h):
    data.append(list(input()))
    sharp += data[i].count('#')
ans = []
def dfs(row, column, count,data):
    if(row > w - 1) or (column > h - 1) or ( row < 0 ) or ( column < 0 ):
        return

    if data[column][row] == '#':
        return

    data[column][row] = '#'

    if column == h - 1 and row == w - 1:
        count += 1
        ans.append(count)
        return

    else:

        dfs(row + 1, column,     count + 1,data)
        dfs(row,     column + 1, count + 1,data)
        dfs(row - 1, column,     count + 1,data)
        dfs(row,     column - 1, count + 1,data)
        return
dfs(0, 0, 0,data)
if len(ans) == 0:
    print(-1)
else:
    k = min(ans)
print(h * w - sharp - k)

Submission status: Runtime Error

Solution code:
h, w = list(map(int, input().split()))
sharp = 0
data = []
for i in range(h):
    data.append(list(input()))
    sharp += data[i].count('#')
ans = []
def dfs(row, column, count,data):
    if(row > w - 1) or (column > h - 1) or ( row < 0 ) or ( column < 0 ):
        return

    if data[column][row] == '#':
        return

    data[column][row] = '#'

    if column == h- 1 and row == w - 1:
        count += 1
        ans.append(count)
        return

    else:

        dfs(row + 1, column,     count + 1,data)
        dfs(row,     column + 1, count + 1,data)
        dfs(row - 1, column,     count + 1,data)
        dfs(row,     column - 1, count + 1,data)
        return
dfs(0, 0, 0,data)
if len(ans) == 0:
    k = -1
else:
    k = min(ans)
print(h * w - sharp - k)

Submission status: Runtime Error

Solution code:
h, w = list(map(int, input().split()))
sharp = 0
data = []
for i in range(h):
    data.append(list(input()))
    sharp += data[i].count('#')
ans = []
def dfs(row, column, count,data):
    if(row > w - 1) or (column > h - 1) or row < 0 or column < 0:
        return

    if data[column][row] == '#':
        return
    data[column][row] = '#'
    if column == h- 1 and row == w - 1:
        count += 1
        ans.append(count)
        return
    else:

        dfs(row + 1, column,     count + 1,data)
        dfs(row,     column + 1, count + 1,data)
        dfs(row - 1, column,     count + 1,data)
        dfs(row,     column - 1, count + 1,data)
        return
dfs(0, 0, 0,data)
print(h * w - sharp - min(ans))

Submission status: Runtime Error

Solution code:
from collections import deque
h,w=map(int,input().split())
field=["#" for i in range(w+2)]+[["#"]+list(input())+["#"] for i in range(h)]+["#" for i in range(w+2)]
queue=deque([[1,1]])
cost=[[50000 for i in range(w)]for j in range(h)]
cost[0][0]=0
while queue:
  now=queue.popleft()
  for i in [(-1,-1),(-1,1),(1,1),(1,-1)]:
    if field[now[0]+i[0]][now[1]+i[1]]=="#":continue
    if cost[now[0]+i[0]-1][now[1]+i[1]-1]!=50000
    if cost[now[0]+i[0]-1][now[1]+i[1]-1]>cost[now[0]-1][now[1]-1]+1:
      cost[now[0]+i[0]-1][now[1]+i[1]-1]=cost[now[0]-1][now[1]-1]+1
cnt=0
for i in range(h+2):
  for j in range(w+2):
    if field[i][j]=="#":cnt+=1
cnt-=(h+w)*2+4
blackable=h*w-cnt
if cost[-1][-1]==50000:print(-1)
else:
  print(blackable-cost[-1][-1])