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:
from collections import deque

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

cnt = 0
for i in range(H):
    cnt += s[i].count('.')

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

visited = [[float('inf')] * W for i in range(H)]

def bfs():
    queue = deque([[0,0]])
    visited[0][0] = 1

    while queue:
        y,x = queue.popleft()

        if y == H - 1 and x == W - 1:
            return visited[y][x]
        
        for i in range(4):
            nx = x + dy[i]
            ny = y + dx[i]

            if 0 <= nx < W and 0 <= ny < H and s[ny][nx] != '#' and visited[ny][nx] == float('inf'):
                queue.append([ny,nx])
                visited[ny][nx] = visited[y][x] + 1
    
    return -1

num = bfs()

if num == -1:
    print(num)
else:
    print(cnt - num)

Submission status: Accepted

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

visit = [[False for j in range(W)] for i in range(H)]


queue = [[0,0]]
count = 0
while len(queue) > 0:
    count += 1
    next = []
    for now in queue:
        visit[now[0]][now[1]] = True
        for i, j in [[0,-1], [1,0], [0,1], [-1,0]]:
            if 0 <= now[0]+i <= H-1 and 0 <= now[1]+j <= W-1:
                if [now[0]+i,now[1]+j] not in next and not visit[now[0]+i][now[1]+j] and grid[now[0]+i][now[1]+j] == ".":
                    next.append([now[0]+i, now[1]+j])

    if visit[-1][-1]:
        break
    queue = next[:]


black = count
for i in range(H):
    black += grid[i].count("#")

if visit[-1][-1]:
    print(H*W-black)
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque

def bfs(grid, sy, sx, target, wall):
    grid[sy][sx] = wall
    queue = deque([])
    queue.append([sy, sx, 0])
    dxy = [(1,0), (-1,0), (0,1), (0,-1)]
    while queue:
        y,x,cnt = queue.popleft()
        for dy, dx in dxy:
            y_,x_ = y+dy,x+dx
            if [y_, x_] == target:
                return cnt+1
            if grid[y_][x_] == wall:
                continue
            queue.append([y_,x_,cnt+1])
            grid[y_][x_] = wall
    return -1

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

edges = ['#' for i in range(W+2) ]
grid = [edges]
white = 0
for i in range(H):
    s = input()
    grid.append(['#'])
    for j in range(W):
        grid[i+1].append(s[j])
        white += 1 if s[j] == '.' else 0
    grid[i+1].append('#')
grid.append(edges)

ans = bfs(grid, 1, 1, [H,W], '#')

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

Submission status: Accepted

Solution code:
import math
import queue
R,C = list(map(int,input().split(" ")))


gx=C -1
gy=R - 1
mass = [input() for _ in range(R)]
tejun =[ [-1 for i in range(C)] for j in range(R)]
xy = [(1,0),(0,1),(-1,0),(0,-1)]
q = queue.Queue()
q.put((0,0))
tejun[0][0] = 0
while True:
    if q.empty():
        break
    x,y = q.get()
    if x == gx and y == gy:
        break
    for go in xy:
        xmove,ymove = go
        if 0<=x + xmove < C and 0<=y + ymove < R and mass[y + ymove][x+xmove] != "#":
           if tejun[y + ymove ][x + xmove ] == -1:
               tejun[y + ymove][x + xmove]  = tejun[y][x] + 1
               q.put((x + xmove,y + ymove))
if tejun[gy][gx] == -1:
    print(-1)
    exit()

sharp = 0
for temp in mass:
    sharp+= temp.count("#")
ans = R*C -(sharp + (tejun[gy][gx] + 1))
print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
import numpy as np
INF = 1000000000


def dijkstra(grids, s):
    pq = [(s, 0)]
    while pq:
        u, dist = heapq.heappop(pq)
        if dist >= grids[u][2]:
            continue
        grids[u][2] = dist
        for v in grids[u][1]:
            heapq.heappush(pq, (v, dist + 1))


def main():
    h, w = [int(e) for e in input().split()]
    board = [input() for _ in range(h)]
    grids = [[0, [], INF] for _ in range(h * w)]
    blocks = h * w
    for i, s in enumerate(board):
        for j, c in enumerate(s):
            if c == '.':
                grids[(i * w) + j][0] = 1
                blocks -= 1
    for i, g in enumerate(grids):
        if g[0] == 0:
            continue
        if i % w > 0 and grids[i - 1][0] == 1:
            grids[i][1].append(i - 1)
        if i % w < w - 1 and grids[i + 1][0] == 1:
            grids[i][1].append(i + 1)
        if i // w > 0 and grids[i - w][0] == 1:
            grids[i][1].append(i - w)
        if i // w < h - 1 and grids[i + w][0] == 1:
            grids[i][1].append(i + w)
    dijkstra(grids, 0)
    print(max(-1, (h * w) - (blocks + grids[(h * w) - 1][2] + 1)))


main()

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
field=[list(input()) for _ in range(h)]
cost=[[float('inf')]*w for _ in range(h)]
cost[0][0]=1
queue=deque([[0,0]])
count=0
for i in range(h):
    for j in range(w):
        if field[i][j]=='.':
            count+=1
def bfs():
    while queue:
        x,y=queue.popleft()
        for dx,dy in [[1,0],[-1,0],[0,1],[0,-1]]:
            if 0<=x+dx<h and 0<=y+dy<w:
                if field[x+dx][y+dy]=='.' and cost[x+dx][y+dy]==float('inf'):
                    cost[x+dx][y+dy]=cost[x][y]+1
                    queue.append([x+dx,y+dy])
bfs()
#print(cost)
if cost[-1][-1]<float('inf'):
    print(count-cost[-1][-1])
else:
    print(-1)

Submission status: Accepted

Solution code:
from collections import deque
INF = float('inf')
H,W = map(int,input().split())
s = [input() for _ in range(H)]
cost = [[INF]*W for _ in range(H)]
cost[0][0] = 1
 
def bfs():
    que = deque([])
    que.append([0,0])
    while que:
        h,w = que.popleft()
        for dh,dw in [[1,0],[-1,0],[0,1],[0,-1]]:
            if 0<=h+dh<H and 0<=w+dw<W:
                if s[h+dh][w+dw] == '.' and cost[h+dh][w+dw] == INF:
                    cost[h+dh][w+dw] = cost[h][w]+1
                    que.append([h+dh,w+dw])
bfs()
if cost[-1][-1] == INF:
    print(-1)
else:
    ans = H*W-cost[-1][-1]
    for h in range(H):
        ans -= s[h].count('#')
    print(ans)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
l=[]
l.append(['#' for i in range(w+2)])
for i in range(h):
  l.append(list('#'+input()+'#'))
l.append(['#' for i in range(w+2)])
ctw=0
for i in range(1,h+1):
  for j in range(1,w+1):
    if l[i][j]=='.':ctw+=1
L=[[1,1]]
ct=0
x=0
for i in range(h*w):
  L2=[]
  for j in range(len(L)):
    L3=[[L[j][0]-1,L[j][1]],[L[j][0]+1,L[j][1]],[L[j][0],L[j][1]-1],[L[j][0],L[j][1]+1]]
    for k in range(4):
      if l[L3[k][0]][L3[k][1]]=='.':
        L2.append(L3[k])
        l[L3[k][0]][L3[k][1]]='#'
  ct+=1
  L=L2
  if [h,w] in L:
    x=ct
    break
if x==0:print(-1)
else:print(ctw-ct-1)

Submission status: Accepted

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(inputs):
    H = len(inputs)
    W = len(inputs[0])
    alter = inputs
    count_dot = 0
    reached_alter = []
    for line in alter:
        a = []
        for mass in line:
            if mass == ".":
                count_dot += 1
            a.append(False)
        reached_alter.append(a)
    queue = deque([[0, 0, 0]])

    min = -1
    while len(queue) > 0:
        [x, y, step_num] = queue.popleft()
        if x == -1 or x == W or y == -1 or y == H:
            continue
        if x == W - 1 and y == H - 1:
            min = step_num
            break
        if alter[y][x] == "#" or reached_alter[y][x]:
            continue
        reached_alter[y][x] = True

        queue.append([x - 1, y, step_num + 1])
        queue.append([x + 1, y, step_num + 1])
        queue.append([x, y - 1, step_num + 1])
        queue.append([x, y + 1, step_num + 1])

    if min == -1:
        return -1
    return count_dot - min - 1


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    [H, W] = string_to_int(input())
    ret = solve(inputs(H))
    print(ret)

Submission status: Accepted

Solution code:
delta = [[0,1],[1,0],[0,-1],[-1,0]]
def search(s):
    visited = [[0 for _ in range(W)] for __ in range(H)]
    queue = [[0,0]]
    visited[0][0] = 1
    while queue:
        [i,j] = queue.pop(0)
        for k in range(4):
            i_next = i + delta[k][0]
            j_next = j + delta[k][1]
            if i_next in range(H) and j_next in range(W) and s[i_next][j_next]=='.' and visited[i_next][j_next]==0:
                visited[i_next][j_next] = visited[i][j]+1
                queue.append([i_next,j_next])
    if visited[-1][-1]==0:
        print(-1)
#        for l in range(H):
#            print(visited[l])
        exit()
    else:
        return visited[H-1][W-1]

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

white = 0
for i in range(H):
    white += len(s[i].replace('#',''))

print(white - search(s))

Submission status: Accepted

Solution code:
from collections import deque
d=[(0,1),(1,0),(0,-1),(-1,0)]
h,w=map(int,input().split())
v=[[0]*w for _ in range(h)]
a=[]
for i in range(h):
    s=input()
    a.append([i for i in s])

wh=sum([''.join(i).count('.') for i in a])

def bfs(t,s):
    rt=0
    q=deque([(t,s)])
    v[t][s]=1
    while q:
        y,x=q.popleft()
        if (y,x)==(h-1,w-1):  # condtion for finish
            return
        for dx,dy in d:
            if 0<=y+dy<h and 0<=x+dx<w and v[y+dy][x+dx]==0:
                if a[y+dy][x+dx]=='.':  # condition that the next cell is fine
                    q.append((y+dy,x+dx))
                    v[y+dy][x+dx]=v[y][x]+1
    return -1

bfs(0,0)
dis=v[-1][-1]
ans=wh-dis if dis>0 else -1
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
sw = [input() for _ in range(H)]

white = 0
for i in range(H):
	white += sw[i].count(".")
# print(white)

count = [[None]*W for _ in range(H)]
q = deque([])

dy = [1, 0, -1, 0]
dx = [0, -1, 0, 1]
def BFS():
	i, j = q.popleft()
	
	for x, y in zip(dx, dy):
		ny = i + y
		nx = j + x
		if 0 <= ny <= H-1 and 0 <= nx <= W-1 and sw[ny][nx] != '#' and count[ny][nx] == None:
			count[ny][nx] = count[i][j] + 1
			q.append((ny, nx))

	if len(q) != 0:
		BFS()


q.append((0, 0))
count[0][0] = 0

BFS()
# for i in count:
# 	print(i)
if count[H-1][W-1]:
	print(white-(count[H-1][W-1]+1))
else:
	print(-1)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
# template

# BEGIN CUT HERE
from queue import Queue
def bfs(field, sy, sx, wall, dir):
    h = len(field)
    w = len(field[0])
    dp = [[-1 for _j in range(w)] for _i in range(h)]
    q = Queue()

    dp[sy][sx] = 0
    q.put((sy, sx))
    
    dy = [1, -1, 0, 0, 1, 1, -1, -1]
    dx = [0, 0, 1, -1, 1, -1, 1, -1]
    def isin(x,y): return 0 <= y and y < h and 0 <= x and x < w
    
    while not q.empty():
        y, x = q.get()
        for k in range(dir):
            ny,nx = y+dy[k],x+dx[k]
            if not isin(nx, ny) or field[ny][nx] == wall:
                continue
            elif dp[ny][nx] != -1:
                continue
            dp[ny][nx] = dp[y][x] + 1
            q.put((ny,nx))
        
    return dp
    
# END CUT HERE

def ABC088_D():
    h, w = mi()
    s = [['' for _j in range(w)] for _i in range(h)]
    for i in range(h):
        s[i] = li()
    dp = bfs(s, 0, 0, '#', 4)
    if dp[h - 1][w - 1] < 0:
        print(-1)
    else:
        cnt = 0
        for i in range(h):
            for j in range(w):
                cnt += s[i][j] == '.'
        print(cnt - (dp[h - 1][w - 1] + 1))
# verified on 2019/06/13
# Pypy3:233ms https://atcoder.jp/contests/abc088/submissions/5898207
# https://atcoder.jp/contests/abc088/tasks/abc088_d

if __name__ == '__main__':
    ABC088_D()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
# template

# BEGIN CUT HERE
from queue import Queue
def bfs(field, sy, sx, wall, dir):
    h = len(field)
    w = len(field[0])
    dp = [[-1 for _j in range(w)] for _i in range(h)]
    q = Queue()

    dp[sy][sx] = 0
    q.put((sy, sx))
    
    dy = [1, -1, 0, 0, 1, 1, -1, -1]
    dx = [0, 0, 1, -1, 1, -1, 1, -1]
    def isin(x,y): return 0 <= y and y < h and 0 <= x and x < w
    
    while not q.empty():
        y, x = q.get()
        for k in range(dir):
            ny,nx = y+dy[k],x+dx[k]
            if not isin(nx, ny) or field[ny][nx] == wall:
                continue
            elif dp[ny][nx] != -1:
                continue
            dp[ny][nx] = dp[y][x] + 1
            q.put((ny,nx))
        
    return dp
    
# END CUT HERE

def ABC088_D():
    h, w = mi()
    s = [['' for _j in range(w)] for _i in range(h)]
    for i in range(h):
        s[i] = li()
    dp = bfs(s, 0, 0, '#', 4)
    if dp[h - 1][w - 1] < 0:
        print(-1)
    else:
        cnt = 0
        for i in range(h):
            for j in range(w):
                cnt += s[i][j] == '.'
        print(cnt - (dp[h-1][w-1]+1))

if __name__ == '__main__':
    ABC088_D()

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
S = [input() for i in range(H)]
g = 0
q = deque()
q.append((0, 0))
dist = [[0 for j in range(W)] for i in range(H)]
dr = [(1,0),(-1,0),(0,1),(0,-1)]

while len(q):
    r = q.popleft()
    x = r[1]
    y = r[0]
    now = dist[y][x]
    if y == H-1 and x == W-1:
        g = 1
        break
    for d in range(4):
        nx = x + dr[d][0]
        ny = y + dr[d][1]
        if 0 <= nx < W and 0 <= ny < H:
            if S[ny][nx] != "#" and dist[ny][nx] == 0:
                dist[ny][nx] = now+1
                q.append((ny,nx))

sharp = sum([i.count("#") for i in S])
if  g == 1:
  print(H * W - now - sharp - 1)
else:
  print(-1)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

def bfs(graph,start,end):
    queue = [start]
    visited = {}
    visited[start[0],start[1]] = 1
    while queue:
        i,j = queue.pop(0)
        if (i,j) == end:
            return visited[i,j]
        for di,dj in [(1,0),(-1,0),(0,1),(0,-1)]:
            if 0 <= i+di < len(graph) and\
                0 <= j+dj < len(graph[0]) and\
                graph[i+di][j+dj] != "#" and\
                (i+di,j+dj) not in visited:
                visited[i+di,j+dj] = visited[i,j] + 1
                queue.append((i+di,j+dj))
    return -1

def get_black_cnt(graph):
    return(sum([s.count("#") for s in graph]))


def solve(H,W,S):
    res = bfs(S,(0,0),(H-1,W-1))
    if res > 0:
        res = H*W-res-get_black_cnt(S)
    print(res)
    pass

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    # Failed to predict input format
    H,W = list(map(int,input().split()))
    S = []
    for i in range(H):
        S.append(input())
    solve(H,W,S)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
L=["#"*(W+2)]
n=0
for i in range(H):
  S=input()
  n+=S.count(".")
  L.append("#"+S+"#")
L.append("#"*(W+2))
r=[(1,1)]
dic={(1,1):1}
m=[(1,1)]
i=1
mm=[]
nyan=[(0,1),(0,-1),(1,0),(-1,0)]
while m:
  i+=1
  for a,b in m:
    for c,d in nyan:
      x,y=a+c,b+d
      if L[x][y]=="." and (x,y) not in r:
        r.append((x,y))
        mm.append((x,y))
        dic[(x,y)]=i
  m=mm[:]
  mm=[]
if (H,W) in r:
  print(n-dic[(H,W)])
else:
  print(-1)

Submission status: Accepted

Solution code:
from collections import namedtuple
import pdb

H, W = map(int, input().split())
s = []
visited = []
step = []

Prev = namedtuple('Prev', ('row', 'col', 'num'))
default_black = 0

for _ in range(H):
    line = input()
    for c in line:
        if c=='#':
            default_black += 1
    s.append(line)
    visited.append([0 for _ in range(W)])
    step.append([0 for _ in range(W)])
    

queue = []

step[0][0] = 1

Point = namedtuple('Point', ('row', 'col'))
st = Point(0, 0)
en = Point(H-1, W-1)



def valid(p):
    return (0 <= p.row and p.row < H and 0 <= p.col and p.col < W)

def around_p(p):
    around = [Point(p.row-1, p.col), Point(p.row+1, p.col), Point(p.row, p.col-1), Point(p.row, p.col+1)]
    for a in around:
        yield a

def goal(p):
    return p.row == H-1 and p.col == W-1

def bfs():
    queue = [st]

    while queue:
        cur_p = queue[0]
        queue = queue[1:]
        if goal(cur_p):
            return step[cur_p.row][cur_p.col]
        if visited[cur_p.row][cur_p.col] == 1:
            continue
        cur_step = step[cur_p.row][cur_p.col]
        visited[cur_p.row][cur_p.col] = 1

        for next_p in around_p(cur_p): 
            if not valid(next_p):
                continue
            if s[next_p.row][next_p.col] == '#':
                continue
            if visited[next_p.row][next_p.col] == 1:
                continue
            queue.append(next_p)
            step[next_p.row][next_p.col] = cur_step + 1
                        
    return -1

def main():
    ans = bfs()
    if ans == -1:
        print(ans)
    else:
        print(H*W - default_black - ans)


main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[]
for i in range(h):
    s.append(list(input()))
a=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#':
            a+=1

visited = [[0]*w for _ in range(h)]

def dfs(s,visit,h,w,a):
    stack=[[0,0,1]]
    visit[0][0]=1
    while stack:
        sh,sw,c=stack.pop(0)
        if sh==h-1 and sw==w-1:
            return h*w-a-c
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_h, new_w = sh+j, sw+k
            if new_h < 0 or new_h >= h or new_w < 0 or new_w >= w:
                continue
            elif s[new_h][new_w] != "#" and visit[new_h][new_w] == 0:
                visit[new_h][new_w] = 1
                stack.append([new_h,new_w,c+1])
    return -1
  
print(dfs(s,visited,h,w,a))

Submission status: Accepted

Solution code:
from collections import deque

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

graph = [[float('inf')] * W for _ in range(H)]
offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def bfs(x, y):
    graph[x][y] = 0

    deq = deque()
    deq.append((x, y))
    
    while deq:
        x, y = deq.popleft()
        
        for i, j in offsets:
            if (not 0 <= x + i < H) or (not 0 <= y + j < W):
                continue
                
            if graph[x + i][y + j] < float('inf'):
                continue
                
            if grid[x + i][y + j] == '#':
                continue
                
            graph[x + i][y + j] = graph[x][y] + 1
            deq.append((x + i, y + j))
            

bfs(0, 0)
if graph[-1][-1] == float('inf'):
    print(-1)
else:
    black = sum(s.count('#') for s in grid)
    print(H * W - graph[-1][-1] - black - 1)

Submission status: Accepted

Solution code:
H, W=map(int, input().split())
graph=[]
road=0
for i in range(H):
    s=list(input())
    road=road+s.count(".")
    graph.append(s)

not_visited=[]
not_visited=[[True for i in range(W)] for j in range(H)]
need_visited=[]
need_visited=[[0 for i in range(W)] for j in range(H)]
need_visited[H-1][W-1]=True
queue=[]

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

start_point=[0, 0]
queue.append(start_point)
while len(queue)!=0:
    now_point=queue.pop(0)
    for i in range(4):
        search_point=[now_point[0]+dx[i], now_point[1]+dy[i]]
        if 0<=search_point[0]<H and 0<=search_point[1]<W:
            if graph[search_point[0]][search_point[1]]!="#" and not_visited[search_point[0]][search_point[1]]:
                not_visited[search_point[0]][search_point[1]]=False
                queue.append(search_point)
                need_visited[search_point[0]][search_point[1]]=need_visited[now_point[0]][now_point[1]]+1

if need_visited[H-1][W-1]==True:
    print(-1)
else:
    print(road-need_visited[H-1][W-1]-1)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# 2019. 6/6
# Grid Repainting

from collections import deque

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


class Coordinate(object):
    def __init__(self, x, y, dist=INF):
        self.x = x
        self.y = y
        self.dist = dist


if __name__ == '__main__':
    cnt = 0
    H, W = map(int, input().split())
    grid = [['#'] * (W + 2)]
    for i in range(H):
        line = list(input())
        cnt += line.count('.')
        grid.append(['#'] + line + ['#'])
    grid.append(['#'] * (W + 2))

    # BFS
    queue = deque()
    start = Coordinate(1, 1, 1) # dist means the panels needed to goal
    goal = Coordinate(W, H)
    queue.append(start)
    distance = [[INF]*(W+2) for i in range(H+2)]
    distance[1][1] = 0

    while len(queue):
        head = queue[0]
        queue.popleft()
        if head.x == goal.x and head.y == goal.y:
            goal.dist = head.dist
            break
        for i in range(4):
            next_p = Coordinate(head.x + dx[i], head.y + dy[i], head.dist)
            if (1 <= next_p.x <= W and 1 <= next_p.y <= H and
                    grid[next_p.y][next_p.x] != '#'
                        and distance[next_p.y][next_p.x] == INF):
                next_p.dist = head.dist + 1
                distance[next_p.y][next_p.x] = next_p.dist
                queue.append(next_p)

    if goal.dist == INF:
        print(-1)
    else:
        print(cnt - goal.dist)

Submission status: Accepted

Solution code:
from collections import deque

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

L = []

black = 0

for i in range(H) :
    S = input()
    black += S.count("#")
    L.append(S)

dxy = [(-1,0),(1,0),(0,-1),(0,1)]

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

DISTANCE = [[float("inf") for x in range(W)] for y in range(H)]
DISTANCE[0][0] = 0

while q :
    y,x = q.popleft()
    
    for dy,dx in dxy :
        ny,nx = y+dy,x+dx
        
        if (ny < 0) or (ny >= H) or (nx < 0) or (nx >= W) :
            continue
        
        if L[ny][nx] == "#" :
            continue
        
        if DISTANCE[y][x] + 1 >= DISTANCE[ny][nx] :
            continue
        
        DISTANCE[ny][nx] = DISTANCE[y][x] + 1
        q.append([ny,nx])

if DISTANCE[H-1][W-1] == float("inf") :
    ans = -1
else :
    ans = H*W - (DISTANCE[H-1][W-1] + 1) - black

print(ans)

Submission status: Accepted

Solution code:
H,W = list(map(int,input().split()))

s = [input() for i in range(H)]

e_list = [[] for i in range(H*W)]

count = 0
for i in range(H):
    for j in range(W):
        if s[i][j]==".":
            if i!=H-1:
                if s[i+1][j]==".":
                    e_list[i*W+j].append((i+1)*W+j)
                    e_list[(i+1)*W+j].append(i*W+j)
            if j!=W-1:
                if s[i][j+1]==".":
                    e_list[i*W+j].append(i*W+j+1)
                    e_list[i*W+j+1].append(i*W+j)
            count+=1

vi = 0 #時と場合によってここを変える
from collections import deque
Q = deque([vi])
N=H*W
checked_list = [False for i in range(N)]
checked_list[vi]=True
min_path_list = [10**27 for i in range(N)] #問題によりここを変える
min_path_list[vi] = 0
while len(Q)>0:
    v = Q.pop()
    for v1 in e_list[v]:
        if not checked_list[v1]:
            checked_list[v1]=True
            Q.appendleft(v1)
            min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) #問題によりここを変える
if min_path_list[H*W-1]<10**9:
    print(count-(1+min_path_list[H*W-1]))
else:
    print(-1)

Submission status: Accepted

Solution code:
H,W=map(int,input().split())
MAP=[["#"]*(W+2)] + [["#"]+list(input())+["#"] for i in range(H)] + [["#"]*(W+2)]
white=0
for line in MAP:
    white+=line.count('.')
from collections import deque
check=deque([(1,1,1)])
dist=float('inf')
while len(check)>0:
    d,x,y=check.popleft()
    for i,j in [(-1,0),(1,0),(0,1),(0,-1)]:
        if MAP[x+i][y+j]==".":
            if x+i==H and y+j==W:
                dist=d+1
                check=[]
                break
            check.append((d+1,x+i,y+j))
            MAP[x+i][y+j]="#"
if dist>10**10:
    print(-1)
else:
    print(white-dist)

Submission status: Accepted

Solution code:
import queue

class BreadthFirstSearch:
    def __init__(self, h, w, start_xy, goal_xy, board):
        self.h, self.w = h, w
        (self.sx, self.sy) = start_xy
        (self.gx, self.gy) = goal_xy
        self.board = board
        self.hist = [[False] * w for i in range(h)]

    def get_step(self, wall="#"):
        q = queue.Queue()
        q.put((self.sx, self.sy))
        step = 0
        count = 1
        next_count = 1
        ans = 0
        # キューが空になるまで
        while not q.empty():
            x, y = q.get()
            count -= 1
            if count == 0:
                step += 1
                count = next_count
                next_count = 0
            # ゴールにたどり着くまでのステップ
            if x == self.gx and y == self.gy:
                ans = step
                break
            for (i, j) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                if not(0 <= x+i <= w - 1) or not(0 <= y+j <= h - 1):
                    continue
                if self.board[y+j][x+i] == wall:
                    continue
                if self.hist[y+j][x+i]:
                    continue
                self.hist[y+j][x+i] = True
                q.put((x+i, y+j))
                next_count += 1
        return ans

# 図の形
h, w = map(int, input().split())
# スタート地点
s_xy = (0, 0)
# ゴール
g_xy = (w - 1, h - 1)
# ボードの読み込み
board = [[i for i in list(str(input()))] for i in range(h)]
# 既に通ったかどうか
bfs = BreadthFirstSearch(h, w, s_xy, g_xy, board)
ans = bfs.get_step()
count_black = 0
for y in range(h):
    for x in range(w):
        if board[y][x] == "#":
            count_black += 1
if ans == 0:
    print("-1")
else:
    print(h * w - ans - count_black)

Submission status: Accepted

Solution code:
import queue

q = queue.Queue()

h, w = map(int, input().split())
sx, sy = 0, 0
gx, gy = w - 1, h - 1
board = [[i for i in list(str(input()))] for i in range(h)]
hist = [[False] * w for i in range(h)]

q.put((sx, sy))
step = 0
count = 1
next_count = 1
ans = 0
while not q.empty():
    x, y = q.get()
    count -= 1
    if count == 0:
        step += 1
        count = next_count
        next_count = 0
    if x == gx and y == gy:
        ans = step
        break
    for (i, j) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
        if not(0 <= x+i <= w - 1) or not(0 <= y+j <= h - 1):
            continue
        if board[y+j][x+i] == "#":
            continue
        if hist[y+j][x+i]:
            continue
        hist[y+j][x+i] = True
        q.put((x+i, y+j))
        next_count += 1
count_black = 0
for y in range(h):
    for x in range(w):
        if board[y][x] == "#":
            count_black += 1

if ans == 0:
    print("-1")
else:
    print(h * w - ans - count_black)

Submission status: Accepted

Solution code:
import sys
from collections import deque

def bfs(maze, visited):
    sy,sx=0,0
    gy,gx=H-1,W-1
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        if [y, x] == [gy, gx]:
            return visited[y][x]

        p=[]
        if x>0 : p.append([0,-1])
        if x<W-1: p.append([0,1])
        if y>0: p.append([-1,0])
        if y<H-1: p.append([1,0])
        for j, k in p:
            new_y, new_x = y+j, x+k
            if 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])
    return -1

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

visited=[[-1]*W for i in range(H)]
ans=sum(m[i].count(".") for i in range(H))
p=bfs(m,visited)
print( p if p==-1 else ans-p-1)