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 numpy as np
h,w=map(int,input().split())
M=list(["*"]+list(input())+["*"] for i in range(h))
M.append(["*"]*(w+2))
M.insert(0,["*"]*(w+2))
add=[]
def go(a,b):
    root=[[1,0],[-1,0],[0,1],[0,-1]]
    for x,y in root:
        A,B=a+x,b+y
        if M[A][B]==".":
            M[A][B]="*"
            go(A,B)
            add.append((A,B))
    return add

cnt=0
if (h,w) in go(1,1):
    for i in range(1,h+1):
        for j in range(1,w+1):
            if M[i][j]=="#":cnt +=1
    print((h*w)-(h+w+cnt-1))
else:print(-1)

Submission status: Runtime Error

Solution code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <set>

using namespace std;

int dx[] = { -1, 1, 0, 0  };
int dy[] = {  0, 0, 1, -1 };
vector< vector<char> > maze;

int h, w;
int bfs() {
  vector<vector<int>> dist(h, vector<int>(w, -1));
  dist[0][0] = 0;
  queue<pair<int, int>> q;
  q.push(make_pair(0, 0));
  while (!q.empty()) {
    auto cur = q.front(); q.pop();
    int x = cur.first, y = cur.second;
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i];
      int ny = y + dy[i];
      if (nx < 0 || ny < 0 || nx >= w || ny >= h) { continue; }
      if (dist[ny][nx] != -1) { continue; }
      dist[ny][nx] = dist[y][x] + 1;
      q.push(make_pair(nx, ny));
    }
  }
  return dist[h-1][w-1];
}

int main() {
  cin >> h >> w;
  maze.assign(h, vector<char>(w, 0));

  int cnt_black = 0;
  for (int y = 0; y < h; y++) {
    string t; cin >> t;
    for (int x = 0; x < t.size(); x++) {
      maze[y][x] = t[x];
      if (t[x] == '#') { cnt_black++; }
    }
  }

  int dist = bfs();

  if (dist == -1) {
    cout << -1 << endl;
  } else {
    cout << h*w-(dist + 1)-cnt_black << endl;
  }
  return 0;
}

Submission status: Runtime Error

Solution code:
import sys

def input():
    return.sys.stdin.buffer.readline()[:-1]

h, w = map(int, input().split())
maze = [['#'] * (w+2)]
cou = 0
for i in range(h):
    a = ['#'] + list(input()) + ['#']
    maze.append(a)
x = ['#'] * (w+2)
maze.append(x)

for i in range(1, h+1):
    for j in range(1, w+1):
        if maze[i][j] == '#':
            cou += 1

ng = True
pos = [[1, 1, 0]]
while len(pos) > 0:
    x, y, depth = pos.pop(0)
    if ([x, y] == [h, w]) & (maze[x][y] != '#'):
        ans = h * w - cou - depth - 1
        #print(cou)
        #print(depth)
        print(ans)
        ng = False
        break
    maze[x][y] = 'f'

    if maze[x+1][y] == '.':
        pos.append([x+1, y, depth+1])
    if maze[x][y+1] == '.':
        pos.append([x, y+1, depth+1])
    if maze[x-1][y] == '.':
        pos.append([x-1, y, depth+1])
    if maze[x][y-1] == '.':
        pos.append([x, y-1, depth+1])
    #print(pos)
    #print(maze)


if (len(pos) == 0) & ng:
    print(-1)

Submission status: Runtime Error

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

def bfs(y,x,m):
  g = [[None if S[i][j] == '.' else -1 for j in range(W)] for i in range(H)]
  g[y][x] = 0
  q = deque()
  q.append((y,x))
  while q:
    i,j = q.popleft()
    for di,dj in ((0,1),(1,0),(-1,0),(0,-1)):
      ni = i+di; nj = j+dj
      if 0 <= ni < H and 0 <= nj < W and g[ni][nj] is None:
        g[ni][nj] = g[i][j] + 1
        q.append((ni,nj))
  return max(max(r) for r in g)

for i in range(H):
  for j in range(W):
    if S[i][j] == '.':
      deq = bfs(i,j,S)
      if ans < deq:
        ans = deq
print(ans)

Submission status: Runtime Error

Solution code:
#088_D
import queue
h, w = map(int, input().split())
inf = 10 ** 5
s = [input() for _ in range(h)]
d = [[inf]*w for _ in range(h)]

que = queue.Queue()
que.put((0, 0))
d[0][0] = 0
while not que.empty():
    qx, qy = que.get()
    if qx == h-1 and qy == w-1:
        break
        
    for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        px, py = qx+dx, qy+dy
        if 0 <= px < h and 0<= py < w:
            if s[px][py] == '#':
                continue
            elif d[px][py] != inf:
                continue
            d[px][py] = d[qx][qy] + 1
            que.put((px, py))
            
if dp[h-1][w-1] == inf:
    print(-1)
else:
    print(h * w - (d[h-1][w-1]+1) - sum(s[i].count('#') for i in range(h)))

Submission status: Runtime Error

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

H, W = map(int, input().split())

initial = 0
grid = []
for _ in range(H):
    row = input()
    initial += row.count("#")
    grid.append(row)

def bfs():
    dire = [(1,0),(0,1),(-1,0),(0,-1)]
    q = deque()
    q.append((0, 0, 1))
    explored = set()
    explored.add((0, 0))
    while q:
        y, x, count = q.popleft()
        for h, w in dire:
            yh = y + h
            xw = x + w
            if yh < 0 or yh >= H or xw < 0 or xw >= W or grid[yh][xw] == "#" or (yh, xw) in explored:
                continue
            
            if (yh, xw) == (H-1, W-1):
                return count+1

            explored.add((yh, xw))
            q.append((yh, xw, count+1))

path_count = bfs()

print(H*W - path_count - initial)

Submission status: Runtime Error

Solution code:
import queue
import numpy as np

num = list(map(int,input().split()))
field = [list(input()) for i in range(num[0])]
seen = np.zeros((num[0],num[1]))

step_r = [1,0,-1,0]
step_c = [0,1,0,-1]
q_r = queue.Queue()
q_c = queue.Queue()
sign = 0
white = 0
q_r.put(0)
q_c.put(0)

for i in range(num[0]):
  for j in range(num[1]):
    if field[i][j] == ".":
      white = white + 1

while not q_r.empty():
  r = q_r.get()
  c = q_c.get()
  for i in range(4):
    next_r = r + step_r[i]
    next_c = c + step_c[i]
    
    if (next_r<0) or (num[0]<=next_r) or (next_c<0) or (num[1]<=next_c) or (field[next_r][next_c] == "#"):
      continue
      
    if seen[next_r][next_c] == 0:
      q_r.put(next_r)
      q_c.put(next_c)
      seen[next_r][next_c] = seen[r][c] + 1
      if (next_r == num[0]-1) and (next_c == num[1]-1):
        g_r = next_r
        g_c = next_c
        sign = 1
        break
 
  if sign == 1:
    break
    
ans = white - (seen[g_r][g_c] + 1)
print(int(ans))

Submission status: Runtime Error

Solution code:
import colections
H, W = map(int, input().split())
l = [input() for _ in range(H)]
check = [([0] * (W)) for _ in range(H)]
white = 0
for i in range(H):
    white += l[i].count(".")
q = collections.deque()
check[0][0] = 1
q.append([0, 0])
g = False
while q:
    h, w = q.popleft()
    for i, j in ([0, 1], [0, -1], [1, 0], [-1, 0]):
        new_h = h + i
        new_w = w + j
        if new_w < 0 or new_h < 0 or new_w > W-1 or new_h > H-1 or l[new_h][new_w] == "#":
            continue
        elif check[new_h][new_w] == 0:
            check[new_h][new_w] = check[h][w] + 1
            q.append([new_h, new_w])
print(white - check[H-1][W-1] if check[H-1][W-1] != 0 else -1)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
l = [input() for _ in range(H)]
check = [([0] * (W)) for _ in range(H)]
white = 0
for i in range(H):
    white += l[i].count(".")
q = collections.deque()
check[0][0] = 1
q.append([0, 0])
g = False
while q:
    h, w = q.popleft()
    for i, j in ([0, 1], [0, -1], [1, 0], [-1, 0]):
        new_h = h + i
        new_w = w + j
        if new_w < 0 or new_h < 0 or new_w > W-1 or new_h > H-1 or l[new_h][new_w] == "#":
            continue
        elif check[new_h][new_w] == 0:
            check[new_h][new_w] = check[h][w] + 1
            q.append([new_h, new_w])
print(white - check[H-1][W-1] if check[H-1][W-1] != -1 else -1)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
s = []
nb = 0
for _ in range(H):
    s.append(list(input()))
    nb += s[-1].count("#")

nw = H * W - nb

sy, sx = 0, 0
gy, gx = H - 1, W - 1

q = [[sy, sx]]
visited = [[int(1e10)]*W for _ in range(H)]
visited[sy][sx] = 0
while q:
    ty, tx = q.pop(0)
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        ny, nx = ty + dy, tx + dx
        if 0 <= ny < H and 0 <= nx < W and s[ny][nx] != "#":
            if visited[ny][nx] > visited[ty][tx] + 1:
                visited[ny][nx] = visited[ty][tx] + 1
                q.append([ny, nx])
    if [gy, gx] in q:
        temp = visited[gy][gx]
        break
if s[gy][gx] == int(1e10):
    print(-1)
else: print(nw - temp - 1)

Submission status: Runtime Error

Solution code:
import sys

H, W = map(int, input().split())
s = []
nb = 0
for _ in range(H):
    s.append(list(input()))
    nb += s[-1].count("#")

nw = H * W - nb

sy, sx = 0, 0
gy, gx = H - 1, W - 1

# たどりつけない場合
if s[gy - 1][gx] == "#" and s[gy][gx - 1] == "#":
    print(-1)
    sys.exit()

q = [[sy, sx]]
visited = [[int(1e10)]*W for _ in range(H)]
visited[sy][sx] = 0
while q:
    ty, tx = q.pop(0)
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        ny, nx = ty + dy, tx + dx
        if 0 <= ny < H and 0 <= nx < W and s[ny][nx] != "#":
            if visited[ny][nx] > visited[ty][tx] + 1:
                visited[ny][nx] = visited[ty][tx] + 1
                q.append([ny, nx])
    if [gy, gx] in q:
        temp = visited[gy][gx]
        break

print(nw - temp - 1)

Submission status: Runtime Error

Solution code:
import sys

H, W = map(int, input().split())
s = []
nb = 0
for _ in range(H):
    s.append(list(input()))
    nb += s[-1].count("#")

nw = H * W - nb

sy, sx = 0, 0
gy, gx = H - 1, W - 1

# たどりつけない場合
if s[gy - 1][gx] == "#" and s[gy][gx - 1] == "#":
    print(-1)
    sys.exit()

q = [[sy, sx]]
visited = [[int(1e10)]*W for _ in range(H)]
visited[sy][sx] = 0
while q:
    ty, tx = q.pop(0)
    for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
        ny, nx = ty + dy, tx + dx
        if 0 <= ny < H and 0 <= nx < W and s[ny][nx] != "#" and visited[ny][nx] > visited[ty][tx] + 1:
            visited[ny][nx] = visited[ty][tx] + 1
            q.append([ny, nx])
    if [gy, gx] in q:
        temp = visited[gy][gx]
        break

print(nw - temp - 1)

Submission status: Runtime Error

Solution code:
import sys

H, W = map(int, input().split())
s = []
nb = 0
for _ in range(H):
    s.append(list(input()))
    nb += s[-1].count("#")

nw = H * W - nb

sy, sx = 0, 0
gy, gx = H - 1, W - 1

# たどりつけない場合
if s[gy - 1][gx] == "#" and s[gy][gx - 1] == "#":
    print(-1)
    sys.quit()

q = [[sy, sx]]
visited = [[int(1e10)]*W for _ in range(H)]
visited[sy][sx] = 0
while True:
    nq = []
    for ty, tx in q:
        for dy, dx in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            ny, nx = ty + dy, tx + dx
            if 0 <= ny < H and 0 <= nx < W and s[ny][nx] == "." and visited[ny][nx] > visited[ty][tx] + 1:
                visited[ny][nx] = visited[ty][tx] + 1
                nq.append([ny, nx])
    q = nq
    if [gy, gx] in q:
        temp = visited[gy][gx]
        break

print(nw - temp - 1)

Submission status: Runtime Error

Solution code:
from collections import deque
def bfs(maze, sy, sx, gy, gx):
    d = [[-1] * w for _ in range(h)]
    que = deque([[sy, sx]])
    #print(que)
    d[sy][sx] = 0
    while que:
        y, x = que.popleft()
        if y == gy and x == gx:
            break
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            ny, nx = y + j, x + k
            if 0 <= nx < w  and 0 <= ny < h  and d[ny][nx] == -1 and maze[ny][nx] != "#":
                d[ny][nx] = d[y][x] + 1
                que.append([ny, nx])
                
    return d
gx, gy = w - 1, h - 1
def counting(maze, h, w, aim):
    cnt = 0
    for i in range(h):
        for j in range(w):
            if maze[i][j] == aim:
                cnt += 1
    return cnt
a = bfs(maze, 0, 0, gy, gx)
if a[gy][gx] == -1:
    print(-1)
else:
    print(h * w - (counting(maze, h, w, '#') + (a[gy][gx] + 1)))

Submission status: Runtime Error

Solution code:
from collections import deque

H, W = map(int, input().split())
edges = ['#']*(W+2)
field = [edges]
dyx = [(0, 1), (0, -1), (1, 0), (-1, 0)]
bk = 0
for _ in range(H):
    line = list(input())
    bk += line.count('#')
    field.append(['#'] + line + ['#'])
field.append(edges)

steps = 1
q = deque()
field[1][1] = 1
q.append((1, 1, 1))

while q:
    cy, cx, lv = q.popleft()

    for dy, dx in dyx:
        ny, nx = dy+cy, dx+cx

        if field[ny][nx] == '.':
            field[ny][nx] = lv+1
            q.append((ny, nx, lv+1))
steps = field[H][W]
if steps.isnumeric():
    print(W*H-bk-steps)
else:
    print(-1)

Submission status: Runtime Error

Solution code:
from collections import deque

H, W = map(int, input().split())
edges = ['#']*(W+2)
field = [edges]
dyx = [(0, 1), (0, -1), (1, 0), (-1, 0)]
bk = 0
for _ in range(H):
    line = list(input())
    bk += line.count('#')
    field.append(['#'] + line + ['#'])
field.append(edges)

steps = 1
q = deque()
field[1][1] = 1
q.append((1, 1, 1))

while q:
    cy, cx, lv = q.popleft()

    for dy, dx in dyx:
        ny, nx = dy+cy, dx+cx

        if field[ny][nx] == '.':
            field[ny][nx] = lv+1
            q.append((ny, nx, lv+1))
steps = field[H][W]

print(W*H-bk-steps)

Submission status: Runtime Error

Solution code:
# 最短でゴールして残った黒をぜんぶ白に変えれば最大のポイントをもらえそう
# ってなふうに雑に考えてたけど、探索・最短経路復元・解答それぞれで1度ずつBFSをしなきゃならんのか？？？？

h, w = map(int, input().split())
table = [[] for _ in range(h)]
for y in range(h):
    table[y] = list(input())
# ステップ更新用
my_table = [[-1 for _ in range(w)] for _ in range(h)]
my_table[0][0] = 0
yo = [(0, 0)]
steps = [0, -1, 0, 1, 0]
while len(yo) > 0:
    p = yo[0]
    yo = yo[1:]
    for i in range(4):
        next_x, next_y = steps[i + 1] + p[1], steps[i] + p[0]
        if next_x < 0 or w <= next_x or next_y < 0 or h <= next_y:
            continue
        if table[next_y][next_x] == "#":
            continue
        if my_table[next_y][next_x] >= 0:
            continue
        my_table[next_y][next_x] = my_table[p[0]][p[1]] + 1
        yo.append((next_y, next_x))

# 経路を逆からたどって最短経路復元
restore_table = [["o" for _ in range(w)] for _ in range(h)]
restore_table[h - 1][w - 1] = "x"
now = my_table[h - 1][w - 1]
cur = (h - 1, w - 1)
while now != 0:
    for i in range(4):
        next_y, next_x = steps[i] + cur[0], steps[i + 1] + cur[1]
        if next_x < 0 or w <= next_x or next_y < 0 or h < next_y:
            continue
        if my_table[next_y][next_x] == now - 1:
            restore_table[next_y][next_x] = "x"
            cur = (next_y, next_x)
            now -= 1
            break

# やっと答え
ans = 0
for y in range(h):
    for x in range(w):
        if restore_table[y][x] == "o" and table[y][x] == ".":
            ans += 1
print(ans)

Submission status: Runtime Error

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


def bfs(field, d, sx, sy, gx, gy):
    queue = deque([(sx, sy)])
    d[sx][sy] += 1
    
    while queue:
        x, y = queue.popleft()
        if (x, y) == (gx, gy):
            return d[x][y]

        dx = [1, 0, -1, 0]
        dy = [0, 1, 0, -1]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            
            # field内かつ障害物じゃないかつ未訪問なら追加
            if (0 <= nx <= gx and 0 <= ny <= gy
                and field[nx][ny] != "#" 
                and d[nx][ny] == -1):
                d[nx][ny] = d[x][y] + 1
                queue.append((nx, ny))

def main():
    H,W = map(int, readline().split())
    s = [readline() for i in range(H)]

    #スタートからの距離(-1は未訪問)
    d = [[-1]*W for i in range(H)]

    min_path = bfs(s, d, 0, 0, H-1, W-1) + 1

    black = 0
    for line in s:
        black += line.count("#")

    ans = H * W - min_path - black
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
import heapq
import copy
import numpy as np
from collections import deque

h,w=list(map(int,input().split()))
s=np.array([[x for x in input()] for i in range(h)])
d=[[0]*w for i in range(h)]

q=deque([[1,0,0]])

while True:
    cnt,hh,ww=deque.popleft(q)

    if hh==h-1 and ww==w-1:
        nblack=np.sum(s=="#",dtype=np.int)
        print(h*w-nblack-cnt)
        exit(0)
    for nh,nw in [[hh+dh,ww+dw] for dh,dw in [[1,0],[-1,0],[0,1],[0,-1]]]:
        if 0>nh or nh>=h or 0>nw or nw>=w or d[nh][nw]==1 or s[nh][nw]=='#':
            continue
        d[nh][nw]=1
        deque.append(q,[cnt+1,nh,nw])

Submission status: Runtime Error

Solution code:
h,w = map(int,input().split())
s = []
for i in range(h):
  s += [list(map(int,input().split()))]
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 < n-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 < n-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: Runtime Error

Solution code:
h,w = map(int,input().split())
s = []
for i in range(h):
  s += [list(map(int,input().split()))]
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 < n 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 < n 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: Runtime Error

Solution code:
dy = [0, 0, 1, -1]
dx = [1, -1, 0, 0]


def bfs(start, goal):
    q = [[start]]
    while len(q) > 0:
        path = q.pop(0)
        n = path[len(path) - 1]
        if n == goal:
            return path
        else:
            for sy, sx in zip(dy, dx):
                py = n[0] + sy
                px = n[1] + sx
                if py < 0 or H <= py:
                    continue
                if px < 0 or W <= px:
                    continue
                if S[py][px] == "#":
                    continue
                if visited[py][px]:
                    continue
                visited[py][px] = True
                x = (py, px)
                if x not in path:
                    new_path = path[:]
                    new_path.append(x)
                    q.append(new_path)

H, W = map(int, input().split())
S = []
for i in range(H):
    S.append([c for c in input()])
# print(S)
visited = [[False for _ in range(W)] for _ in range(H)]
start = (0, 0)
goal = (H-1, W-1)
ans = bfs(start, goal)
# print(ans)
counter = 0
for i in range(H):
    for j in range(W):
        if (i, j) in ans:
            continue
        if S[i][j] == ".":
            counter += 1
print(counter)

Submission status: Runtime Error

Solution code:
10 37
.....................................
...#...####...####..###...###...###..
..#.#..#...#.##....#...#.#...#.#...#.
..#.#..#...#.#.....#...#.#...#.#...#.
.#...#.#..##.#.....#...#.#.###.#.###.
.#####.####..#.....#...#..##....##...
.#...#.#...#.#.....#...#.#...#.#...#.
.#...#.#...#.##....#...#.#...#.#...#.
.#...#.####...####..###...###...###..
.....................................

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
s = []
black = 0
for i in range(H):
    l = list(input())
    for j in range(W):
        if l[j] == "#":
            black += 1
    s.append(l)
white = H*W-black
from collections import deque
q = deque([(0,0,0)])
s[0][0] = "#"
while q:
    x,y,cnt = q.popleft()
    for dx,dy in [(0,1),(0,-1),(1,0),(-1,0)]:
        nx,ny = x+dx,y+dy
        if 0<=nx<H and 0<=ny<W and s[nx][ny] != "#":
            if nx == H-1 and ny == W-1:
                print(white-cnt-2)
                exit(114514)
            s[nx][ny] = "#"
            q.append((nx,ny,cnt+1))
print(-1)

Submission status: Runtime Error

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
    visit_counter[y][x]+=1

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

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+1))]
for _ in range(h):
    li = input()
    for i in li:
        if i == '.':
            road_count += 1
    li += '#'
    lis.append(list(li))
lis.append(list('#'*(w+1)))

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

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

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

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


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

Submission status: Runtime Error

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

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

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 coun == 0:
    print(-1)
else:
    print(road-(count+1))

Submission status: Runtime Error

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を始める前に、もともと壁だったところの数を記録しておく
wall = 0
for row in lis:
    for column in row:
        if column == 1:
            wall +=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<w 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<h and lis[x][y+1] != 1:
        pos.append([x,y+1,depth+1])

#(全マス) - (壁) - (移動する道順上のマスの数 ＝ 最短の移動回数＋１）
print(h*w-wall-(count+1))

Submission status: Runtime Error

Solution code:
H,W = map(int,input().split())
move_x = [1,-1,0,0]
move_y = [0,0,1,-1]
Field = [[c for c in input()] for _ in range(H)]
seen = [[False for _ in range(W)] for _ in range(H)]
queue = []
black = 0
for i in range(H):
    for j in range(W):
        if Field[i][j] == '#':
            black += 1
dist = [[0 for _ in range(W)] for _ in range(H)]
res = -1 
def bfs(start_x,start_y,Field,seen,queue,dist):
    global res
    seen[start_x][start_y] = True
    for i in range(0,4):
        x = start_x + move_x[i]
        y = start_y + move_y[i]
        if x < 0 or y < 0 or x >= H or y >= W:
            continue #out of range
        if Field[x][y] == '#':
            continue #we don't visit black square.
        if seen[x][y]:
            continue #already visited
        if Field[x][y] in queue:
            continue #already in queue.
        if x == (H-1) and y == (W-1):
            dist[x][y] = dist[start_x][start_y] + 1
            res = H*W - dist[x][y] - black #H*W - counting(seen) - black 
        queue.append((x,y))
        dist[x][y] = dist[start_x][start_y] + 1
    for element in queue:
        x,y = element
        if seen[x][y]:
            continue
        seen[x][y] = True
        queue.remove(element)
        bfs(x,y,Field,seen,queue,dist)    
bfs(0,0,Field,seen,queue,dist)
print(res-1)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
ans = 0
S = []
for _ in range(H):
    s = list(input())
    ans += s.count('.')
    S.append(s)

inf = float('inf')
G = [[inf] * H * W for _ in range(H * W)]

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

for h in range(H):
    for w in range(W):
        for x, y in zip(dx, dy):
            nx = w + x
            ny = h + y
            if 0 <= nx < W and 0 <= ny < H and S[ny][nx] != '#':
                G[W * h + w][W * ny + nx] = 1

from scipy.sparse.csgraph import dijkstra

d = dijkstra(G, indices=0)

print(int(ans - d[-1] - 1))

Submission status: Runtime Error

Solution code:
import numpy as np
H, W = map(int, input().split())
grid = np.array([list(map(str, input())) for _ in range(H)])

X = np.where(grid == '#')
A = np.zeros([H,W])
A[X] = 1
orig_black = np.count_nonzero(grid=='#')

q = [[0,0,0]]
while q:
	cx,cy,cd = q.pop(0)
	if cx == H-1 and cy == W-1:
		shortest = cd
		break
	elif A[cx,cy] == -1:
		continue

	A[cx,cy] = -1

	for nx,ny in [[cx+1,cy],[cx-1,cy],[cx,cy+1],[cx,cy-1]]:
		if 0 <= nx < H and 0 <= ny < W:
			if A[nx][ny] == 0:
				q.append([nx,ny,cd+1])

print((H*W)-shortest-orig_black-1)