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: Wrong Answer

Solution code:
h, w = map(int, input().split())
maze = []
wall = 0
for _ in range(h):
    row = list(input())
    wall += row.count('#')
    maze.append(row)

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

def bfs():
    from collections import deque
    que = deque([])

    d = [[float("inf")] * w for _ in range(h)]
    que.append((0, 0))
    d[0][0] = 0
    step = 0

    while que:
        step += 1
        p = que.popleft()
        if p == (h - 1, w - 1):
            break
        if step == h * w:
            return h * w + wall
        for i in range(4):
            ny = p[0] + dy[i]
            nx = p[1] + dx[i]

            if 0 <= nx and nx < w and 0 <= ny and ny < h and maze[ny][nx] != '#' and d[ny][nx] == float("inf"):
                que.append((ny, nx))
                d[ny][nx] = d[p[0]][p[1]] + 1

    return d[h - 1][w - 1]

print(h * w - wall - bfs() - 1)

Submission status: Wrong Answer

Solution code:
# ABC088 D
h, w = map(int, input().split())
maze = []
wall = 0
for _ in range(h):
    row = list(input())
    wall += row.count('#')
    maze.append(row)

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

def bfs():
    from collections import deque
    que = deque([])

    d = [[float("inf")] * w for _ in range(h)]
    que.append((0, 0))
    d[0][0] = 0
    step = 0

    while que:
        step += 1
        p = que.popleft()
        if p == (h - 1, w - 1):
            break
        if step == h * w:
            return -1
        for i in range(4):
            ny = p[0] + dy[i]
            nx = p[1] + dx[i]

            if 0 <= nx and nx < w and 0 <= ny and ny < h and maze[ny][nx] != '#' and d[ny][nx] == float("inf"):
                que.append((ny, nx))
                d[ny][nx] = d[p[0]][p[1]] + 1

    return d[h - 1][w - 1]

print(h * w - wall - bfs() - 1)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30
from collections import Counter

W = 0
def g_i(i, j):
    return i * W + (j+1) - 1

def dijkstra(n, start, nbl):
    """n: 頂点数, start: 始点, nbl: 隣接リスト"""
    import heapq
    WHITE = 1<<5
    GRAY = 1<<10
    BLACK = 1<<15
    INF = 1<<20
    color = [WHITE] * n
    distance = [INF] * n
    parent = [-1] * n
    q = []

    distance[start] = 0
    heapq.heappush(q, (0, start))
    while len(q) != 0:
        du, u = heapq.heappop(q)
        # print("u: {}, du: {}".format(u, du))
        color[u] = BLACK
        if distance[u] < du:
            continue
        for next, cost in nbl[u]:
            if color[next] != BLACK and distance[u] + cost < distance[next]:
                distance[next] = distance[u] + cost
                parent[next] = u
                color[next] = GRAY
                heapq.heappush(q, (distance[next], next))
    return (distance, parent)

def main():
    global W
    h, W = map(int, input().strip().split())
    w = W
    s = [[0] * w for _ in range(h)]
    G = [[] for _ in range(h * w)]
    for i in range(h):
        s[i] = list(input().strip())
    sc = 0
    dc = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == '#':
                sc += 1
                continue
            dc += 1
            if i != 0 and s[i-1][j] == '.':
                G[g_i(i, j)].append((g_i(i-1, j), 1))
            if i != h-1 and s[i+1][j] == '.':
                G[g_i(i, j)].append((g_i(i+1, j), 1))
            if j != 0 and s[i][j-1] == '.':
                G[g_i(i, j)].append((g_i(i, j-1), 1))
            if j != w-1 and s[i][j+1] == '.':
                G[g_i(i, j)].append((g_i(i, j+1), 1))
    # print(G)
    d, p = dijkstra(h * w, 0, G)
    # print(d[h*w - 1])
    # for i in range(h):
    #     for j in range(w):
    #         if p[g_i(i, j)] != -1:
    #             print('.', end='')
    #         else:
    #             print('#', end='')
    #     print('\n', end='')
    # print(g_i(h-1, w-2))
    # print(p[g_i(h-1, w-2)])
    # print(p)
    print(dc - d[h*w - 1] - 1)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

ans = ans2 = 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: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!
h,w=map(int,input().split())

maze=[]
m=[]
wn=0
INF = 10**4
INF_row=[INF for _ in range(w)]

for i in range(h):
    row=list(input())
    maze.append(row)
    m.append(INF_row)
    for j in range(w):
        if row[j]==".":
            wn+=1

print(100)

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

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

while len(queue)>0:
    y,x=queue.pop(0)
    maze[y][x]=="#"
    for i in range(4):
        ny=y+dy[i]
        nx=x+dx[i]
        if 0<=ny<h and 0<=nx<w:
            if maze[ny][nx]==".":
                queue.append([ny,nx])
                m[ny][nx]=min(m[ny][nx],m[y][x]+1)


if m[-1][-1]==INF:
    print(-1)
else:
    print(wn-2-(m[-1][-1]-1))

Submission status: Wrong Answer

Solution code:
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)

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

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
moves = ((0, 1), (1, 0), (0, -1), (-1, 0))
path = [[float('inf')]*w for _ in range(h)]
path[0][0] = 0
def bfs():
    q = deque([[0, 0]])
    while q:
        y, x = q.popleft()
        if y == h and x == w:
            return 
        for dy, dx in moves:
            ny = y + dy 
            nx = x + dx 
            if 0 <= ny < h and 0 <= nx < w and s[ny][nx] == '.' and path[ny][nx] == float('inf'):
                path[ny][nx] = min(path[ny][nx], path[y][x]+1)
                q.append([ny, nx])

bfs()

black = 0

for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            black += 1 

print(h*w - black - path[h-1][w-1] - 1)

Submission status: Wrong Answer

Solution code:
import copy
import queue
import numpy as np

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







#import queue
def bfs(array,start,goal,height,width):
    v=[[-1]*width for _ in range(height)]

    q=queue.Queue()
    q.put([start[0],start[1]])
    move=[[0,1],[0,-1],[1,0],[-1,0]]
    v[start[0]][start[1]]=0
    while not q.empty():
        pos=q.get()
        if pos[0]==goal[0] and pos[1]==goal[1]:          
            break
        
        for m in move:
            y=pos[0]+m[0]
            x=pos[1]+m[1]
            if y>=0 and y<height and x>=0 and x<width and array[y][x]=="." and v[y][x]==-1 :
                v[y][x]=v[pos[0]][pos[1]]+1
                q.put([y,x])
    return v[goal[0]][goal[1]]


cnt=0
for i in range(H):
    for j in range(W):
        if c[i][j]=="#":
            cnt+=1

d=bfs(c,[0,0],[H-1,W-1],H,W)

print(H*W-1-d-cnt)

Submission status: Wrong Answer

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)]
    bl = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == "#":
                bl += 1

    ql = [[0, 0, 0]]
    ql = collections.deque(ql)
    fq = collections.defaultdict(list)
    fq[0, 0]
    mc = 10 ** 10
    while True:
        if len(ql) != 0:
            cost, xv, yv = ql.popleft()
            if xv == h - 1 and yv == w - 1:
                mc = min(mc, 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
    print(h * w - mc - 1 - bl)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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)]
    bl = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == "#":
                bl += 1

    ql = [[0, 0, 0]]
    ql = collections.deque(ql)
    fq = collections.defaultdict(list)
    fq[0, 0]
    mc = 0
    while True:
        if len(ql) != 0:
            cost, xv, yv = ql.popleft()
            mc = max(mc, 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
    print(h * w - mc - 1 - bl)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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)]
    bl = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == "#":
                bl += 1

    ql = [[0, 0, 0]]
    ql = collections.deque(ql)
    fq = collections.defaultdict(list)
    fq[0, 0]
    mc = 0
    while True:
        if len(ql) != 0:
            cost, xv, yv = ql.popleft()
            mc = max(mc, 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[i][j] != "#":
                        ql.append([cost + 1, xv, yv])
                        fq[xv, yv]
        else:
            break
    print(h * w - mc - 1 - bl)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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)]
    bl = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == "#":
                bl += 1

    ql = [[0, 0, 0]]
    ql = collections.deque(ql)
    fq = collections.defaultdict(list)
    fq[0, 0]
    mc = 0
    while True:
        if len(ql) != 0:
            cost, xv, yv = ql.popleft()
            mc = max(mc, 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:
                        ql.append([cost + 1, xv, yv])
                        fq[xv, yv]
        else:
            break
    print(h * w - mc - 1 - bl)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
import numpy as np


def main():
    H, W = map(int, input().split())

    ps = np.zeros([H, W])
    for i in range(H):
        ps[i, :] = list(map(lambda x: -1 if x == "#" else 0, input()))

    hashnum = np.sum(ps)

    costs = np.zeros([H, W])
    s = (0, 0)
    g = (H-1, W-1)
    dd = ((1, 0), (-1, 0), (0, 1), (0, -1))
    q = [s]
    costs[s] = 1
    ps[s] = 1
    moves = 1

    while q:
        qn = []
        moves += 1
        for x, y in q:
            for dx, dy in dd:
                nx, ny = int(x + dx), int(y + dy)
                if 0 <= nx < H and 0 <= ny < W:
                    if ps[nx, ny] == 0:
                        costs[nx, ny] = moves
                        ps[nx, ny] = 1
                        qn.append((nx, ny))

        q = qn
        if g in q:
            break

    print(int(H * W + hashnum - np.max(costs)))


main()

Submission status: Wrong Answer

Solution code:
def BFS(x,y): # 配列dの幅優先探索
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    que=[]
    que.append([x,y])
    d[x][y]=0
    while len(que)!=0:
        [qx,qy]=que[0]
        que.pop(0)
        for i in range(4):
            nx=qx+dx[i]
            ny=qy+dy[i]
            if nx>=0 and h>nx and ny>=0 and w>ny and maze[nx][ny]=="." and d[nx][ny]==-1:
                d[nx][ny]=d[qx][qy]+1
                que.append([nx,ny])
    return d[h-1][w-1]

def main():
    global h,w,maze,d
    h,w = map(int,input().split())
    d=[[-1 for _ in range(w)] for _ in range(h)]
    maze=[]
    for _ in range(h):
        maze.append(list(input()))
    n=BFS(0,0)
    if n==-1:
        print(-1)
    else:
        cnt=0
        for i in range(h):
            for j in range(w):
                if maze[i][j]==".":
                    cnt+=1
        print(cnt-h-w+1)
        
    





if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(4100000)

H,W = map(int,input().split(' '))
sx,sy = 0,0
move_list = [ list(input()) for _ in range(H) ]
possible_list = [ [-1 for _ in range(W) ] for _ in range(H) ]
possible_list[sx][sy] = 0

x_start_list = [sx]
y_start_list = [sy]

def bfs(target_list,possible_list,x_queue,y_queue,cnt=0):
    x_list = [1,-1,0,0,]
    y_list = [0,0,1,-1]
    cnt += 1
    next_x_queue = []
    next_y_queue = []

    for i in range(4):
        for j in range(len(x_queue)):
            dx = x_queue[j] + x_list[i]
            dy = y_queue[j] + y_list[i]
            if dx < 0 or H <= dx or dy < 0 or W <= dy:
                continue
            if target_list[dx][dy] == '#':
                continue
            if possible_list[dx][dy] != -1:
                continue
            possible_list[dx][dy] = cnt
            next_x_queue.append(dx)
            next_y_queue.append(dy)
    if len(next_x_queue) > 0:
        bfs(target_list,possible_list,next_x_queue,next_y_queue,cnt)
    else:
        return

bfs(move_list,possible_list,x_start_list,y_start_list)

cnt_all_panel = 0
for row in move_list:
    for val in row:
        if val == '.':
            cnt_all_panel += 1

print(cnt_all_panel - possible_list[H-1][W-1] -1)

Submission status: Wrong Answer

Solution code:
H,W = map(int, input().split())
field = [list(input()) for _ in range(H)]
dy = [1,-1,0,0]
dx = [0,0,1,-1]


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: Wrong Answer

Solution code:
H,W = map(int, input().split())
field = [list(input()) for _ in range(H)]
dy = [1,-1,0,0]
dx = [0,0,1,-1]


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
print(whites - count-1)

Submission status: Wrong Answer

Solution code:
H,W = map(int, input().split())
field = [list(input()) for _ in range(H)]
dy = [1,-1,0,0]
dx = [0,0,1,-1]


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
print(whites,count)
print(whites - count-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

p = [[0 for j in range(W)] for i in range(H)]
p[0][0] = 1
visited = [[False for j in range(W)] for i in range(H)]
Q = deque()
Q.append((0, 0))
while len(Q) > 0:
    i, j = Q.popleft()
    neighbors = [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]
    for ni, nj in neighbors:
        if 0 <= ni < H and 0 <= nj < W and s[ni][nj] != '#' and p[ni][nj] == 0 and not visited[ni][nj]:
            p[ni][nj] = p[i][j] + 1
            Q.append((ni, nj))
    visited[i][j] = True

n_black = sum([row.count('#') for row in s])
print(H * W - n_black - p[H - 1][W - 1] if p[H - 1][W - 1] == 0 else - 1)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

p = [[0 for j in range(W)] for i in range(H)]
p[0][0] = 1
visited = [[False for j in range(W)] for i in range(H)]
Q = deque()
Q.append((0, 0))
while len(Q) > 0:
    i, j = Q.popleft()
    neighbors = [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]
    for n in neighbors:
        if 0 <= n[0] < H and 0 <= n[1] < W and s[n[0]][n[1]] != '#' and p[n[0]][n[1]] == 0 and not visited[n[0]][n[1]]:
            p[n[0]][n[1]] = p[i][j] + 1
            Q.append(n)
    visited[i][j] = True

n_black = sum([row.count('#') for row in s])
print(H * W - n_black - p[H - 1][W - 1] if p[H - 1][W - 1] < H * W else - 1)

Submission status: Wrong Answer

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

p = [[H * W for j in range(W)] for i in range(H)]
p[0][0] = 1
n_black = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == '#':
            n_black += 1
        else:
            neighbor = p[i][j] + 1
            if i - 1 >= 0:
                p[i - 1][j] = min(p[i - 1][j], neighbor)
            if i + 1 < H:
                p[i + 1][j] = min(p[i + 1][j], neighbor)
            if j - 1 >= 0:
                p[i][j - 1] = min(p[i][j - 1], neighbor)
            if j + 1 < W:
                p[i][j + 1] = min(p[i][j + 1], neighbor)

print(H * W - n_black - p[H - 1][W - 1] if p[H - 1][W - 1] < H * W else - 1)

Submission status: Wrong Answer

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:
                        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: Wrong Answer

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)
    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:
                        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: Wrong Answer

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)
    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:
                        ql.append([cost + 1, xv, yv])
                        fq[xv, yv]
        else:
            break
    cnt = 0
    for i in range(h):
        cnt += s[i].count("#")
    print(h * w - cnt - (mt + 1))


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque

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

d = deque()
d.append([0, 0])
while(d):
    y,x = d.popleft()
    difflist = [[1,0], [0,1], [-1, 0], [0, -1]]
    for dy, dx in difflist:
        y2 = y + dy
        x2 = x + dx
        if 0 <= y2 < h and 0 <= x2 < w and maze[y2][x2] != '#' and dist[y2][x2] == INF:
            d.append([y2, x2])
            dist[y2][x2] = dist[y][x] + 1

distribution = [0]*(h*w)
ans = 0
for i in range(h):
    for j in range(w):
        if dist[i][j] != INF:
            distribution[dist[i][j]] += 1
        elif maze[i][j] == '.':
            ans += 1
distend = dist[h-1][w-1]
ans += sum(distribution) - distend -1
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

def exist_route():
  que = deque()
  que.append([1,1])

  min_route = H*W+1
  while len(que) != 0:
    pos = que.pop()
    for nxt_i, nxt_j in [[pos[0]+1,pos[1]], [pos[0],pos[1]+1]]:
      #print(nxt_i, nxt_j)
      if nxt_i > W or nxt_j > H: continue
      elif nxt_i == W and nxt_j == H: return True
      elif S[nxt_j][nxt_i] == 1: que.append([nxt_i, nxt_j])
    #print(que)
  return False

H,W = map(int,input().split())
S = [[0]*(W+1)] + [[0] + [1 if s=='.' else 0 for s in input()] for _ in range(H)]

if exist_route() is False: print(-1)
else: print(sum([sum(row) for row in S])-(H+W-1))
#print(res)

Submission status: Wrong Answer

Solution code:
from collections import deque

def exist_route():
  que = deque()
  que.append([[1,1],[[1,1]]])

  while len(que) != 0:
    pos, done = que.pop()
    for nxt_i, nxt_j in [[pos[0]-1,pos[1]], [pos[0]+1,pos[1]], [pos[0],pos[1]-1], [pos[0],pos[1]+1]]:
      #print(nxt_i, nxt_j)
      if nxt_i > W or nxt_j > H: continue
      if nxt_i == W and nxt_j == H: return True
      if S[nxt_j][nxt_i] == 1 and [nxt_i, nxt_j] not in done: que.append([[nxt_i, nxt_j],done+[[nxt_i, nxt_j]]])
    #print(que)
  return False

H,W = map(int,input().split())
S = [[0]*(W+1)] + [[0] + [1 if s=='.' else 0 for s in input()] for _ in range(H)]

if exist_route() is False: print(-1)
else: print(sum([sum(row) for row in S])-(H+W-1))

Submission status: Wrong Answer

Solution code:
from collections import deque

r, c = map(int, input().split())
s_y, s_x = 1, 1
g_y, g_x = r, c
s_y -= 1
s_x -= 1
g_y -= 1
g_x -= 1

maze = [list(input()) for i in range(r)]
dot_num = 0
for i in maze:
    dot_num += i.count('.')
reached = [[0] * c for i in range(r)]

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

queue = deque([[s_y, s_x, 0]])
reached[s_y][s_x] = 1

while queue:
    now = queue.popleft()
    depth = now[2] + 1
    for d in directions:
        next_y = now[0] + d[0]
        next_x = now[1] + d[1]
        if 0 <= next_y < r and 0 < next_x < c:
            if maze[next_y][next_x] == '.':
                if reached[next_y][next_x] == 0:
                    queue.append([next_y, next_x, depth])
                    reached[next_y][next_x] = 1

                    if next_y == g_y and next_x == g_x:
                        print(dot_num - depth - 1)
                        exit()
print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

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

dxdy = [(0,1),(0,-1),(1,0),(-1,0)]
queue = deque()
queue.append((0,0))

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

    if S[x][y] == "#":
        continue

    for dx,dy in dxdy:
        if 0 <= x+dx < H  and  0 <= y+dy < W:
            if S[x+dx][y+dy] == "." and A[x+dx][y+dy] == -1:
                A[x+dx][y+dy] = A[x][y] + 1
                queue.append((x+dx,y+dy))

cnt_white = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == ".":
            cnt_white += 1

print(cnt_white - A[H-1][W-1])

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
a=['*'*(w+2)]+['*'+input()+'*' for _ in range(h)]+['*'*(w+2)]
s=0
for i in range(1,h+1):
  s+=a[i].count('.')
from collections import deque
d=deque()
d.append([1,1])
c=[[10000]*w for _ in range(h)]
c[0][0]=1
di=[[0,1],[1,0],[-1,0],[0,-1]]
while d:
  g=d.popleft()
  for i in di:
    x=g[0]+i[0]
    y=g[1]+i[1]
    if a[x][y]=='.':
      if c[x-1][y-1]==10000:
        d.append([x,y])
        c[x-1][y-1]=c[g[0]-1][g[1]-1]+1
print(s-c[h-1][w-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w=map(int,input().split())
l=[["#" for i in range(w+2)]]
for i in range(h):
  l1=list(input())
  l1=["#"]+l1+["#"]
  l.append(l1)
l2=["#" for i in range(w+2)]
l.append(l2)
q=deque([[1,1]])
inf=1000000000
d=[[inf for i in range(w+2)] for j in range(h+2)]
d[1][1]=0
move=[[1,0],[-1,0],[0,1],[0,-1]]
while q:
  a=q.popleft()
  n1=a[0]
  n2=a[1]
  for i in move:
    m1=i[0]
    m2=i[1]
    if l[n1+m1][n2+m2]!="#":
      if d[n1+m1][n2+m2]>d[n1][n2]+1:
        d[n1+m1][n2+m2]=d[n1][n2]+1
        q.append([n1+m1,n2+m2])
dis=d[h][w]
count=0
for i in range(1,h+1):
  for j in range(1,w+1):
    if l[i][j]=="#":
      count+=1
print(h*w-dis-1-count)