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: Accepted

Solution code:
import re
import sys
from collections import *
from functools import lru_cache
from heapq import *
from itertools import *

INF=float('inf')

sys.setrecursionlimit(2**31-1)

rfs=lambda:rl().split()
ri=lambda:int(rl())
ris=lambda:list(map(int,rfs()))
rl=lambda:next(sys.stdin)
rls=lambda:list(map(str.strip,sys.stdin))
rs=lambda:rl().strip()
rt=lambda:sys.stdin.read()
rg=lambda:list(list(ln) for ln in rls())

def n4(i,j):
    return [
                (i-1,j),
        (i,j+1),        (i,j-1),
                (i+1,j),
    ]

def n8(i,j):
    return [
        (i-1,j-1),(i-1,j),(i-1,j+1),
        (  i,j-1),        (  i,j+1),
        (i+1,j-1),(i+1,j),(i+1,j+1),
    ]

inb=lambda i,j,m,n:0<=i<m and 0<=j<n

###########################################

H,W=ris()
s=rg()

nbl=sum(row.count('#') for row in s)
s[0][0]='#'
que=deque([(0,0,1)])
ok=False
while que:
    i,j,k=que.popleft()
    if i+1==H and j+1==W:
        ok=True
        break
    for ni,nj in n4(i,j):
        if inb(ni,nj,H,W) and s[ni][nj]!='#':
            s[ni][nj]='#'
            que.append((ni,nj,k+1))

if ok:
    print(H*W-nbl-k)
else:
    print(-1)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
A=[]
for i in range(h):
    A.append(list(input()))
kabe=0
for i in range(h):
    for j in range(w):
        if A[i][j]=="#":
            kabe+=1
def bfs():
    while queue:
        x,y,d=queue.pop()
        #print("xyd",x,y,d)
        for i in range(4):
            xx=x+dx[i] ; yy=y+dy[i]
            if xx==h-1 and yy==w-1:
                print(h*w-d-2-kabe);exit()
            if 0<=xx<h and 0<=yy<w and A[xx][yy]==".":
                A[xx][yy]="#"
                queue.appendleft([xx,yy,d+1])


from collections import deque
dx=[-1,0,1,0] ;dy=[0,1,0,-1]
queue=deque([[0,0,0]])
bfs()
print(-1)

Submission status: Accepted

Solution code:
from collections import deque
INF=10**18
h,w=map(int,input().split())
e=[input() for _ in range(h)]
cnt=0
for i in range(h):
  for j in range(w):
    if e[i][j]=='.':cnt+=1
dx=[-1,0,1,0]
dy=[0,-1,0,1]
sx,sy=0,0
gx,gy=h-1,w-1
q=deque([(sx,sy)])
d=[[INF]*w for _ in range(h)]
d[sx][sy]=1
while q:
  x,y=q.popleft()
  for i in range(4):
    nx=x+dx[i]
    ny=y+dy[i]
    if 0<=nx<h and 0<=ny<w and e[nx][ny]=='.' and d[nx][ny]==INF:
      q.append((nx,ny))
      d[nx][ny]=d[x][y]+1
if d[gx][gy]==INF:print(-1)
else:print(cnt-d[gx][gy])

Submission status: Accepted

Solution code:
from collections import deque
H,W = map(int,input().split())
grid = [0] * H
num_black = 0
for i in range(H):
    s = input()
    for j in range(len(s)):
        if s[j] == '#':
            num_black += 1
    grid[i] = list(s)
time_grid = [[-1] * W for _ in range(H)]
time_grid[0][0] = 0
queue = deque()
queue.append([0,0,0])
while queue:
    y,x,t = queue.popleft()
    for next_y, next_x in [[y+1,x],[y,x+1],[y-1,x],[y,x-1]]:
        if 0 <= next_x < W and 0 <= next_y < H and grid[next_y][next_x] == '.':
            queue.append([next_y,next_x,t+1])
            time_grid[next_y][next_x] = t+1
            grid[next_y][next_x] = '#'
if time_grid[H-1][W-1] != -1:
    print(H*W-time_grid[-1][-1]-1-num_black)
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque


def bfs(sy, sx, gy, gx):
    q = deque([[sy, sx]])
    visited[sy][sx] = 0
    while q:
        y, x = q.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 ny < 0 or ny > h-1 or nx < 0 or nx > w-1 or path[ny][nx] == "#":
                continue
            if path[ny][nx] == "." and visited[ny][nx] == -1:
                visited[ny][nx] = visited[y][x]+1
                q.append([ny, nx])


h, w = map(int, input().split())
path = [input() for _ in range(h)]
visited = [[-1]*w for _ in range(h)]
sy, sx = 0, 0
gy, gx = h-1, w-1
bfs(sy, sx, gy, gx)

count = 0
for i in range(h):
    for j in range(w):
        if path[i][j] == '#':
            count += 1
if visited[gy][gx] != -1:
    print(h*w-count-(visited[gy][gx]+1))
else:
    print(-1)

Submission status: Accepted

Solution code:
import collections

h, w = map(int, input().split())
s = []
count = 0
s.append("#" * (w + 2))
for i in range(h):
    temp = input()
    count += temp.count(".")
    s.append("#" + temp + "#")
s.append("#" * (w + 2))
dis = [[float("inf") for i in range(w + 2)] for i in range(h + 2)]
dis[1][1] = 0
p = collections.deque([[1, 1]])
d = [[-1, 0], [1, 0], [0, -1], [0, 1]]
while p:
    temp = p.popleft()
    x, y = temp[0], temp[1]
    for i in d:
        dx, dy = i[0], i[1]
        if s[y + dy][x + dx] == "#":
            continue
        else:
            if dis[y][x] + 1 < dis[y + dy][x + dx]:
                dis[y + dy][x + dx] = dis[y][x] + 1
                p.append([x + dx, y + dy])
if dis[h][w] == float("inf"):
    print(-1)
else:
    print(count - dis[h][w] - 1)

Submission status: Accepted

Solution code:
from collections import deque
from collections import Counter

H,W=map(int,input().split())
S=[]
c = []
for i in range(H):
  s = input()
  S.append(s)
  c.extend(list(s))
c = Counter(c)

def bfs(s):
  seen = [[0 for i in range(W)] for j in range(H)]
  total = [[0 for i in range(W)] for j in range(H)]
  todo = deque([])
  now = s
  if S[now[0]][now[1]]=='#':return 0
  seen[now[0]][now[1]],total[now[0]][now[1]] = 1,0
  todo.append(now)
  while 1:
    if len(todo)==0:break
    now = todo.popleft()
    for d in [(1,0),(-1,0),(0,1),(0,-1)]:
      new = (now[0]+d[0], now[1]+d[1])
      if new[0]<0 or new[0]>=H:continue
      if new[1]<0 or new[1]>=W:continue
      if seen[new[0]][new[1]]==1:continue
      if S[new[0]][new[1]]=='#':continue
      seen[new[0]][new[1]] = 1
      todo.append(new)
      total[new[0]][new[1]] = total[now[0]][now[1]] + 1
  return total

d = bfs((0,0))[-1][-1]
if d == 0:
  print(-1)
  exit()
print(c['.']-d-1)

Submission status: Accepted

Solution code:
import heapq

max_d = 10**9
dest_vecs = [(1,0), (0,1), (-1,0), (0, -1)]

def solve():
    H,W = map(int, input().split())
    
    S = [list(input()) for _ in range(H)]
    wall_num = sum(S_row.count('#') for S_row in S)
    
    # 最短経路を求める
    d = [[max_d]*W for _ in range(H)]
    d[0][0] = 0
    prev = [[None]*W for _ in range(H)]
    heap_queue = [(0,0,0)]
    while heap_queue:
        src_distance,y,x = heapq.heappop(heap_queue)
        for dy,dx in dest_vecs:
            ty = y+dy
            tx = x+dx
            if ty < 0 or ty >= H or tx < 0 or tx >= W or S[ty][tx] == '#':
                continue
            
            if d[ty][tx] > src_distance+1:
                d[ty][tx] = src_distance+1
                prev[ty][tx] = (y,x)
                heapq.heappush(heap_queue, (src_distance+1, ty, tx))
                
    ret = -1
    if d[H-1][W-1] < max_d:
        ret = H*W-d[H-1][W-1]-wall_num-1
    
    print(ret)
    
solve()

Submission status: Accepted

Solution code:
import sys,math,collections,itertools
input = sys.stdin.readline

H,W=list(map(int,input().split()))
s = [input().rstrip() for _ in range(H)]
memo = [[0]*W for _ in range(H)]
memo[0][0]=1
q = collections.deque([[0,0]])
while q:
    h,w = q.popleft()
    if h>0 and s[h-1][w]=='.' and memo[h-1][w]==0:
        q.append([h-1,w])
        memo[h-1][w] = memo[h][w] +1
    if h<H-1 and s[h+1][w]=='.' and memo[h+1][w]==0:
        q.append([h+1,w])
        memo[h+1][w] = memo[h][w] +1
    if w>0 and s[h][w-1]=='.' and memo[h][w-1]==0:
        q.append([h,w-1])
        memo[h][w-1] = memo[h][w] +1
    if w<W-1 and s[h][w+1]=='.' and memo[h][w+1]==0:
        q.append([h,w+1])
        memo[h][w+1] = memo[h][w] +1
if memo[H-1][W-1] == 0:
    print(-1)
else:
    cnt = 0
    for i in range(H):
        cnt += s[i].count('#')
    print(H*W-cnt-memo[H-1][W-1])

Submission status: Accepted

Solution code:
import collections

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

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

dist = [[-1 for _ in range(W)] for _ in range(H)]

q = collections.deque()
q.append((sy, sx, 0))

while q:
    y, x, d = q.popleft()

    if y < 0 or H <= y or x < 0 or W <= x:
        continue

    if s[y][x] == '#':
        continue

    if dist[y][x] != -1:
        continue

    dist[y][x] = d + 1

    q.append((y + 1, x, d + 1))
    q.append((y - 1, x, d + 1))
    q.append((y, x + 1, d + 1))
    q.append((y, x - 1, d + 1))

if dist[-1][-1] == -1:
    print(-1)
else:
    num_white = sum(block == '.' for row in s for block in row)
    print(num_white - dist[-1][-1])

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
c=[list(input()) for _ in range(h)]
dhdw = [[-1,0],[1,0],[0,-1],[0,1]]
min_dis=[[-1]*w for _ in range(h)]
que=deque()
def bfs(x,y):
  que.append([x,y])
  min_dis[x][y]=0
  while que:
    sh,sw=que.popleft()
    for dh,dw in dhdw:
      nh,nw = sh+dh,sw+dw
      if not(0<=nh<=h-1) or not(0<=nw<=w-1) or min_dis[nh][nw]!=-1 or c[nh][nw]=='#':
        continue
      min_dis[nh][nw]=min_dis[sh][sw]+1
      que.append([nh,nw])
      if [nh,nw]==[h-1,w-1]:
        return min_dis[sh][sw]+1
a=bfs(0,0) or 0
if a==0:
  print(-1)
  exit()
ans=0
for i in c:
  ans+=i.count(".")
print(ans-1-a)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
maze=[list(input()) for i in range(h)]
distance=[[-1]*w for i in range(h)]

cnt=0
for i in maze:
  cnt+=i.count('#')

Q=[[0,0]]
distance[0][0]=1

ans=-1

while Q:
  p=Q.pop(0)
  if p[0]==h-1 and p[1]==w-1:
    ans=h*w-cnt-distance[h-1][w-1]
    break

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

  for i in range(4):
    nx=p[0]+dx[i]
    ny=p[1]+dy[i]

    if 0<=nx<h and 0<=ny<w and distance[nx][ny]==-1 and maze[nx][ny]!='#':
      Q.append([nx,ny])
      distance[nx][ny]=distance[p[0]][p[1]]+1

print(ans)

Submission status: Accepted

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

dist = [[-1]*W for _ in range(H)]
dist[0][0]=1
d=deque()
d.append((0,0))

while d:
    pop = d.popleft()
    y, x = pop[0], pop[1]

    y_lst = [y+1, y-1, y, y]
    x_lst = [x, x, x+1, x-1]

    for Y, X in zip(y_lst, x_lst):
        if not (0 <= Y < H) or not (0 <= X < W) or S[Y][X]=="#":
            continue
        if dist[Y][X]==-1:
            dist[Y][X] = dist[y][x] + 1
            d.append((Y, X))

if dist[H-1][W-1]==-1:
    print(-1)
else:
    goaltime = dist[H-1][W-1]
    white_sum = 0
    for i in S:
        white_sum += i.count(".")
    print(white_sum-goaltime)

Submission status: Accepted

Solution code:
import sys
H,W=map(int,input().split())
L = [[0 for j in range(W)] for i in range(H)]
c=0
for i in range(H):
  a=list(input())
  c+=a.count(".")
  L[i]=a
#幅優先探索？
subete=[[0,0]]
ans = [[] for i in range(H*W+1)]
ans[0].append([0,0])
for i in range(H*W+1):
  for j in range(len(ans[i-1])):
    a,b=ans[i-1][j][0],ans[i-1][j][1]
    if a+1!=H:
      if [a+1,b] not in subete and L[a+1][b]==".":
        ans[i].append([a+1,b])
        subete.append([a+1,b])
    if a!=0:
      if [a-1,b] not in subete and L[a-1][b]==".":
        ans[i].append([a-1,b])
        subete.append([a-1,b])
    if b+1!=W:
      if [a,b+1] not in subete and L[a][b+1]==".":
        ans[i].append([a,b+1])
        subete.append([a,b+1])
    if b!=0:
      if [a,b-1] not in subete and L[a][b-1]==".":
        ans[i].append([a,b-1])
        subete.append([a,b-1])
  if [H-1,W-1] in subete:
    print(c-i-1)
    sys.exit()
print(-1)

Submission status: Accepted

Solution code:
from collections import deque

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

maze = "#" * (W+2)
for _ in range(H):
  maze += "#" + input() + "#"
maze += "#" * (W+2)

dist = [-1] * (W+2) * (H+2)
q = deque()

dist[(W+2) * 1 + 1] = 0
q.append((W+2) * 1 + 1)

while len(q) != 0:
  v = q.popleft()
  
  udlr = (-W-2, W+2, -1, 1)
  for move in udlr:
    nv = v + move
    if maze[nv] == "#":
      continue
    if dist[nv] != -1:
      continue
    dist[nv] = dist[v] + 1
    q.append(nv)
if dist[(W+2) * H + W] == -1:
  print(-1)
else:
  print(W * H - maze.count("#") + 2 * (W + H + 2) - dist[(W+2) * H + W] -1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np

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

direction_x = [1, -1, 0, 0]
direction_y = [0, 0, 1, -1]
reached = np.zeros((H, W))
que_x = [0]
que_y = [0]
can_reach = False

for x, y in zip(que_x, que_y):
    if x == H - 1 and y == W - 1:
        can_reach = True
        break
    for i in range(4):
        next_x = x + direction_x[i]
        next_y = y + direction_y[i]
        if not(0 <= next_x < H) or not(0 <= next_y < W):
            continue
        if s[next_x][next_y] == '#':
            continue
        if reached[next_x][next_y] > 0:
            reached[next_x][next_y] = min(reached[next_x][next_y], reached[x][y] + 1)
            continue
        reached[next_x][next_y] = reached[x][y] + 1
        que_x.append(next_x)
        que_y.append(next_y)

res = 0
if can_reach:
    for i in range(H):
        for j in range(W):
            if s[i][j] == '.':
                res += 1
    res = res - reached[H-1][W-1] - 1
else:
    res = -1
print(int(res))

Submission status: Accepted

Solution code:
from collections import deque

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

root = [[float("inf") for _ in range(w)] for _ in range(h)]
root[0][0] = 1
D = deque([[0, 0]])
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

while D:
    p = D.popleft()

    if p == [h-1, w-1]:
        break

    for i in range(4):
        x = p[0]+dx[i]
        y = p[1]+dy[i]
        if 0<=x<=h-1 and 0<=y<=w-1 and root[x][y]==float("inf") and maze[x][y]==".":
            root[x][y] = root[p[0]][p[1]] + 1
            D.append([x, y])

white = 0
for i in range(h):
    for j in range(w):
        if maze[i][j]==".":
            white += 1

if root[h-1][w-1] ==float("inf"):
    print(-1)
else:
    print(white - root[h-1][w-1])

Submission status: Accepted

Solution code:
from collections import deque

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

maze = [list(input()) for _ in range(h)]
step = [[0] * w for _ in range(h)]
direction = [[1,0],[-1,0],[0,1],[0,-1]]

def bfs(maze,h,w):
    start = [0,0]
    #キューで座標保存
    q = deque([start])
    while q:
        x, y = q.popleft()
        for d in direction:
            nx = x + d[0]
            ny = y + d[1]
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] == "." and step[nx][ny] == 0:
                q.append([nx,ny])
                step[nx][ny] = step[x][y] + 1
        if step[h-1][w-1] != 0:
            return step[h-1][w-1]
    return -1

#壁の数
wall = 0
for i in maze:
    for j in i:
        if j == "#":
            wall += 1
if bfs(maze,h,w) >= 0:
    ans = h * w - wall - (bfs(maze,h,w) + 1)
else:
    ans = -1
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
Map = [['#'] * (w+2)]
Map += [['#'] + list(input()) + ['#'] for _ in range(h)]
Map += [['#'] * (w+2)]

cnt = 0

for i in range(h+2):
    for j in range(w+2):
        if Map[i][j] == '.':
            cnt += 1
            
stack = deque([(1,1)])
Map[1][1] = 1
moved = [[0,1], [0,-1], [1,0], [-1,0]]

while stack:
    x, y = stack.popleft()
    for s, t in moved:
        if Map[x+s][y+t] == '.':
            stack.append((x+s, y+t))
            Map[x+s][y+t] = Map[x][y] + 1

goal = Map[-2][-2]
if goal == '.':
    print(-1)
else:
    print(cnt - goal)

Submission status: Accepted

Solution code:
from queue import deque
H, W = map(int, input().split())
matrix = []
count = 0
for i in range(H):
    matrix.append(list(input()))
    count += matrix[-1].count('.')
que = deque([(0, 0, 1)])

visited = set()

while que:
    row, col, depth = que.popleft()

    if not(0 <= row < H and 0 <= col < W) or matrix[row][col] == '#':
        continue
    
    if (row, col) in visited:
        continue

    visited.add((row, col))
    if (row, col) == (H-1, W-1):
        print(count - depth)
        exit()
    
    for ud, lr in ((-1, 0), (1, 0), (0, -1), (0, 1)):
        que.append((row+ud, col+lr, depth+1))
print(-1)

Submission status: Accepted

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

h,w = map(int,input().split())
MAP = [list(input().rstrip()) for i in range(h)]  #rstripで最後の/nを省ける
sharp = 0
for i in range(h):
  sharp += MAP[i].count("#")
#print(sharp)

#必要なもの MAP(list), MOVE(list), STACK(deque)
MAP[0][0]=1
MOVE = [[1,0],[-1,0],[0,1],[0,-1]]
STACK = deque([(0,0)])
while STACK:
  y, x = STACK.popleft()
  for dy,dx in MOVE:
    ny = y + dy
    nx = x + dx
    if not(0 <= ny < h) or not(0 <= nx < w) or MAP[ny][nx]!='.':
      continue
    else:
      STACK.append((ny,nx))
      MAP[ny][nx] = MAP[y][x] + 1


if type(MAP[h-1][w-1]) == int:
  ans = h*w -MAP[h-1][w-1]-sharp
else:
  ans = -1
    
print(ans)

Submission status: Accepted

Solution code:
import collections
def f(mat):
	q,vis = collections.deque([((0,0), 1)]), set([(0,0)])
	while(q):
		u,d = q.popleft()
		if u == (len(mat)-1, len(mat[0])-1): return collections.Counter(reduce(lambda x,y:x+y, mat))['.'] - d
		for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1),(u[0],u[1]-1)]:
			if 0 <= v[0] < len(mat) and 0 <= v[1] < len(mat[0]) and (v not in vis) and mat[v[0]][v[1]] == '.':
				vis.add(v)
				q.append((v, d+1))
	return -1
print f([list(raw_input()) for l in range(map(int, raw_input().split())[0])])

Submission status: Accepted

Solution code:
import collections
h,p = map(int, raw_input().split())
def f(mat, h, p):
	q = collections.deque([((0,0), 1)])
	vis = set([(0,0)])

	while(q):
		u,d = q.popleft()
		if u == (h-1, p-1): return collections.Counter(reduce(lambda x,y:x+y, mat))['.'] - d
			
		for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1),(u[0],u[1]-1)]:
			if 0 <= v[0] < len(mat) and 0 <= v[1] < len(mat[0]):
				if v not in vis and mat[v[0]][v[1]] == '.':
					vis.add(v)
					q.append((v, d+1))
	return -1
print f([list(raw_input()) for l in range(h)], h, p)

Submission status: Accepted

Solution code:

import collections
h,p = map(int, raw_input().split())#10 37
mat = [list(raw_input()) for l in range(h)]
q = collections.deque([((0,0), 1)])

vis = set([(0,0)])
r  = float('inf')

while(q):
	u,d = q.popleft()

	if u == (h-1, p-1):
		r = d
		break
	for v in [(u[0]+1,u[1]), (u[0]-1,u[1]), (u[0],u[1]+1),(u[0],u[1]-1)]:
		if 0 <= v[0] < len(mat) and 0 <= v[1] < len(mat[0]):
			if v not in vis and mat[v[0]][v[1]] == '.':
				vis.add(v)
				q.append((v, d+1))

cc = collections.Counter()
for l in mat:
	for e in l:
		cc[e]+=1

if r < float('inf'):
	print cc['.'] - r
else:
	print -1

Submission status: Accepted

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

s = (0,0)
g = (H-1,W-1)

ans = 0
task = deque([(s,0)])
visited = [[0 for _ in range(W)] for _ in range(H)]
visited[s[0]][s[1]] = 1
flag = False
while task:
  p, c = task.popleft()
  x = p[0]
  y = p[1]
  if p == g:
    ans = c
    flag = True
    break 
  if x >= 1 and visited[x-1][y] == 0 and M[x-1][y] == ".":
    visited[x-1][y] = 1
    task.append(((x-1,y),c+1))
  if y >= 1 and visited[x][y-1] == 0 and M[x][y-1] == ".":
    visited[x][y-1] = 1
    task.append(((x,y-1),c+1))
  if x <= H-2 and visited[x+1][y] == 0 and M[x+1][y] == ".":
    visited[x+1][y] = 1
    task.append(((x+1,y),c+1))
  if y <= W-2 and visited[x][y+1] == 0 and M[x][y+1] == ".":
    visited[x][y+1] = 1
    task.append(((x,y+1),c+1))     

point = H*W -sum([M[i].count("#") for i in range(H)]) - ans -1
print(point if flag else -1)

Submission status: Accepted

Solution code:
def main():
    import sys
    from collections import deque

    def input(): return sys.stdin.readline().rstrip()

    def bfs(si, sj):
        di = [-1, 0, 1, 0]
        dj = [0, 1, 0, -1]
        que = deque([(si, sj)])
        dist[0][0] = 0
        while que:
            i, j = que.popleft()
            for k in range(4):
                ni = i+di[k]
                nj = j+dj[k]
                if (ni < 0 or ni >= h or nj < 0 or nj >= w):
                    continue
                if g[ni][nj] == '#':
                    continue
                if dist[ni][nj] > dist[i][j]+1:
                    dist[ni][nj] = dist[i][j]+1
                    que.append((ni, nj))
        

    h, w = map(int, input().split())
    g = []
    cnt = 0
    for i in range(h):
        g.append(input())
        cnt += g[-1].count('#')
    inf = 10**6
    dist = [[inf]*w for _ in range(h)]

    bfs(0, 0)
    if dist[-1][-1] == inf:
        print(-1)
    else:
        ans = h*w-cnt-dist[-1][-1]-1
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import queue

H, W = map(int, input().split())
S = []

for _ in range(H):
    S.append(list(input()))

SS = []
for _ in range(H):
    SSS = []
    for __ in range(W):
        SSS.append(-1)
    SS.append(SSS)

SS[0][0] = 0

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

q = queue.Queue()
q.put(sp)

ans = -1
complete = False
while not q.empty():

    n = q.get()
    if n[0] == W-1 and n[1] == H-1:
        ans = n[2]
        complete = True
        break

    for d in range(4):
        nx = n[0] + dx[d]
        ny = n[1] + dy[d]

        if W > nx >= 0 and H > ny >= 0 and SS[ny][nx] == -1 and S[ny][nx] != '#':
            q.put((nx, ny, n[2]+1))
            SS[ny][nx] = n[2] + 1

wcnt = 0
for _ in range(H):
    for __ in range(W):
        if S[_][__] == '.':
            wcnt += 1
if complete:
    print(wcnt - ans - 1)
else:
    print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**7)
import bisect
import heapq
import itertools
import math
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from math import gcd
from operator import add, itemgetter, mul, xor
def cmb(n,r,mod):
  bunshi=1
  bunbo=1
  for i in range(r):
    bunbo = bunbo*(i+1)%mod
    bunshi = bunshi*(n-i)%mod
  return (bunshi*pow(bunbo,mod-2,mod))%mod
mod = 10**9+7
def I(): return int(input())
def LI(): return list(map(int,input().split()))
def MI(): return map(int,input().split())
def LLI(n): return [list(map(int, input().split())) for _ in range(n)]

h,w = MI()
s = [list(input()) for _ in range(h)]
dist = [[-1]*(w) for _ in range(h)]
#最短距離を求めよう
black_cnt = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            dist[i][j] = 0
            black_cnt += 1
dist[0][0] = 0
d = deque()
d.append([0,0])
dx = [1,-1,0,0]
dy = [0,0,1,-1]
while d:
    v = d.popleft()
    x = v[0]
    y = v[1]
    for i in range(4):
        nx = x+ dx[i]
        ny = y+ dy[i]
        if nx < 0 or nx >= h or ny < 0 or ny >= w:
            continue
        if dist[nx][ny] == -1:
            dist[nx][ny] = dist[x][y] + 1
            d.append([nx,ny])
if dist[-1][-1] == -1:
    print(-1)
else:
    shortest = dist[-1][-1]
    print(h*w - black_cnt -(shortest+1))

Submission status: Accepted

Solution code:
from collections import deque

h,w = list(map(int,input().split()))
black_num = 0
graph = []
for _ in range(h):
  tmp=input()
  black_num+=tmp.count("#")
  graph.append(list(tmp))
#graph=[list(input()) for _ in range(h)]#graph初期化

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

dist=[[-1 for j in range(w)] for i in range(h)]#distance設定
dist[sx][sy]=0#スタート地点は初期値0
 
que = deque([(sx,sy,0)])#スタート地点とdist初期値を入力
 
while que:
  u,v,z = que.popleft()
  for i,j in [(-1,0),(0,-1),(1,0),(0,1)]:
    if not (0<=u+i<h and 0<=v+j<w):#座標がh,w内でなければ探索しない
      continue
    elif graph[u+i][v+j]=="#":#壁なら探索しない
      continue
    elif dist[u+i][v+j]>0:#すでに訪れていたら探索しない
      continue

    dist[u+i][v+j]=z+1#距離を前回の＋1
    que.append([u+i,v+j,z+1])#訪れてないのでqueに今の地点を追加する

if dist[gx][gy]==-1: #ゴールまでたどり着けない場合
  print(-1)
else:
  print(h*w-(dist[gx][gy]+1)-black_num)

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
G = [input() for _ in range(H)]
num = 0
for i in range(H):
    for j in range(W):
        if G[i][j] == ".":
            num += 1
q = deque([(0, 0)])
done = [[-1]*W for _ in range(H)]
done[0][0] = 1
while q:
    w, h = q.popleft()
    for dw, dh in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
        nw, nh = w+dw, h+dh
        if not (0 <= nw < W and 0 <= nh < H and G[nh][nw] == "." and done[nh][nw] == -1): continue
        done[nh][nw] = done[h][w]+1
        q.append((nw, nh))
if done[H-1][W-1] != -1:
    print(num-done[H-1][W-1])
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque
import sys
H, W = list(map(int, input().split()))

city = []

for _ in range(H):
    city.append(list(input()))

dist = [[float("inf") for _ in range(W)] for _ in range(H)]

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

queue = deque()
queue.append((0, 0))
dist[0][0] = 0

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

while len(queue) > 0:
    now_x, now_y = queue.popleft()

    for dx_, dy_ in zip(dx, dy):

        adj_x = now_x + dx_
        adj_y = now_y + dy_

        if (not 0 <= adj_x < W) or (not 0 <= adj_y < H):
            continue

        if city[adj_y][adj_x] == "#":
            continue

        if dist[adj_y][adj_x] > H*W:
            dist[adj_y][adj_x] = dist[now_y][now_x] + 1
            queue.append((adj_x, adj_y))
            dist_count[dist[adj_y][adj_x]] += 1

#すぬけ君がどうやってもたどり着けない場合
if dist[H-1][W-1] > H**W:
    print(-1)
    sys.exit()

#すぬけ君がたどり着ける場合
route_grids = dist[H-1][W-1] + 1

white_all = 0
for i in range(H):
    for j in range(W):
        if city[i][j] == ".":
            white_all += 1
ans = white_all - route_grids
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
ss = [input() for _ in range(h)]
q = deque([(0, 0, 0)])
cost = 0
visited = [[False for _ in range(w)] for _ in range(h)]


def find():
    while len(q) > 0:
        y, x, cost = q.popleft()
        if (y, x) == (h - 1, w - 1):
            return cost
        if 0 <= y < h and 0 <= x < w and ss[y][x] != '#' and not visited[y][x]:
            visited[y][x] = True
            q.append((y + 1, x, cost + 1))
            q.append((y - 1, x, cost + 1))
            q.append((y, x + 1, cost + 1))
            q.append((y, x - 1, cost + 1))
    return -1


c = find()
if c < 0:
    print(-1)
else:
    dots = 0
    for i in range(h):
        for j in range(w):
            if ss[i][j] != '#':
                dots += 1
    print(dots - c - 1)