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

def bfs(board, visited, gh, gw):
    turn = 0
    queue = deque([[0, 0, turn]])
    while queue:
        h, w, turn = queue.popleft()
        if h == gh-1 and w == gw-1:
            return turn
        for i, j in ([1,0],[-1,0],[0,1],[0,-1]):
            new_h, new_w = h+i, w+j
            if new_h >= gh or new_h < 0 or new_w >= gw or new_w < 0:
                continue
            elif board[new_h][new_w] != "#" and visited[new_h][new_w] == "x":
                visited[new_h][new_w] = "o"
                queue.append([new_h, new_w, turn+1])
    return 0

def main():
    H, W = map(int,input().split())
    board = []
    for _ in range(H):
        board.append(list(input()))
    black = 0
    for i in range(H):
        for j in range(W):
            if board[i][j] == "#":
                black += 1
    visited = [["x"]*W for _ in range(H)]
    path_area = bfs(board, visited, H, W) + 1
    print(H*W-path_area-black)
                
    
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
H,W = map(int, input().split())
maze = [input() for _ in range(H)]
stack = [(0,0)]
visited = [[False]*W for _ in range(H)]
visited[0][0] = True
canGoal = False
while stack:
    y,x = stack.pop()
    # print(y,x)
    if (y,x)==(H-1,W-1):
        canGoal = True
        break
    visited[y][x] = True
    for dy,dx in zip([0,0,1,-1], [1,-1,0,0]):
        if not(0<=y+dy<H and 0<=x+dx<W):
            continue
        if visited[y+dy][x+dx] or maze[y+dy][x+dx]=="#":
            continue
        stack.append((y+dy, x+dx))
            
if canGoal:
    ans = H*W - (H+W-1)
    for y in range(H):
        for x in range(W):
            if maze[y][x]=="#": 
                ans -= 1
    print(ans)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
def grid_repainting(H: int, W: int, S: int) -> int:
    # ルート探索用の行列。
    # R[h][w] は (0, 0) -> (h, w) の最短距離になる。
    INF = float('inf')
    R = [[INF] * W for _ in range(H)]
    R[0][0] = 1
    white_num = 0

    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                # 黒いマス目は無視
                continue
            white_num += 1
            if w > 0:
                R[h][w] = min(R[h][w], R[h][w - 1] + 1)
            if h > 0:
                R[h][w] = min(R[h][w], R[h - 1][w] + 1)

    if R[H - 1][W - 1] is INF:
        return - 1

    # R[H-1][W-1] は (0, 0) -> (H-1, W-1) に至るために必要な
    # 最小のマス数になっている。これ以外の全部の白ますは黒マスに変
    # えていいので、それが最大スコア。
    return white_num - R[H-1][W-1]


if __name__ == "__main__":
    H = 0
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]
    ans = grid_repainting(H, W, S)
    print(ans)

Submission status: Wrong Answer

Solution code:
def grid_repainting(H: int, W: int, S: int) -> int:
    # ルート探索用の行列。
    # R[h][w] は (0, 0) -> (h, w) の最短距離になる。
    INF = float('inf')
    R = [[INF] * W for _ in range(H)]
    R[0][0] = 1
    black_num = 0

    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                # 黒いマス目は無視
                black_num += 1
                continue
            if w > 0:
                R[h][w] = min(R[h][w], R[h][w - 1] + 1)
            if h > 0:
                R[h][w] = min(R[h][w], R[h - 1][w] + 1)

    if R[H - 1][W - 1] is INF:
        return - 1

    white_num = H * W - black_num

    # R[H-1][W-1] は (0, 0) -> (H-1, W-1) に至るために必要な
    # 最小のマス数になっている。これ以外の全部の白ますは黒マスに変
    # えていいので、それが最大スコア。
    return white_num - R[H-1][W-1]


if __name__ == "__main__":
    H = 0
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]
    ans = grid_repainting(H, W, S)
    print(ans)

Submission status: Wrong Answer

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

queue=deque()
sy,sx=(0,0)
gy,gx=(H-1,W-1)
reached=[[-1 for i in range(W)] for j in range(H)]
queue.append([sy,sx])
reached[sy][sx]=0
dx=[1,-1,0,0]
dy=[0,0,1,-1]
while(queue):
    p=queue.pop()
    for i in range(4):
        y=p[0]+dy[i]
        x=p[1]+dx[i]
        if x<0 or x>=W or y<0 or y>=H or s[y][x]=="#":
            continue
        if reached[y][x]!=-1:
            continue
        reached[y][x]=reached[p[0]][p[1]]+1
        queue.appendleft([y,x])
n=H*W
for i in range(H):
    for j in range(W):
        if s[i][j]=="#":
            n-=1
if reached[gy][gx]==-1:
  n==-1
print(n-reached[gy][gx]-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w = map(int,input().split())

visited = [[-1 for i in range(w)] for j in range(h)]

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

visited[0][0] = 1

while queue:
    a = queue.popleft()
    dydx = [[1,0],[-1,0],[0,1],[0,-1]]
    for j,k in dydx:
        newy,newx = a[1]+j,a[0]+k
        if (0 <= newy <h) and (0 <= newx < w):
            if (visited[newy][newx] == -1):
                visited[newy][newx] = visited[a[1]][a[0]] + 1
                queue.append((newx,newy))


s = []
cnt = 0
for i in range(h):
    ss = input()
    s.append(ss)
    cnt += ss.count('#')


if(visited[h-1][w-1] == -1): print("-1")
else:
    print(h*w-visited[h-1][w-1]-cnt)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = [["#"] * (W + 2)]
for _ in range(H):
    S.append(["#"] + list(input()) + ["#"])
S.append(["#"] * (W + 2))
S[1][1] = 1
num = 0
for h in range(1, H + 1):
    for w in range(1, W + 1):
        if S[h][w] == "#":
            num += 1
        if S[h][w] != "." and S[h][w] != "#":
            if S[h - 1][w] == ".":
                S[h - 1][w] = S[h][w] + 1
            if S[h][w - 1] == ".":
                S[h][w - 1] = S[h][w] + 1
            if S[h + 1][w] == ".":
                S[h + 1][w] = S[h][w] + 1
            if S[h][w + 1] == ".":
                S[h][w + 1] = S[h][w] + 1
if S[H][W] == ".":
    print(-1)
else:
    print(H * W - num - S[H][W])

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs():
    d = [[float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

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

    return d[gx][gy]

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

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

res = bfs()
if res > 0:
    print(h * w - res - black - 1)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

def bfs():
    d = [[float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

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

    return d[gx][gy]

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

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

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

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W = map(int,input().split())
_input = []
for i in range(H):
    row = list(map(str,input().split()))
    _input.append(list(row[0]))

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

queue = deque([(sy,sx)])

dyx=((1,0),(-1,0),(0,1),(0,-1))

counted_map = [[-1]*W for _ in range(H)]
counted_map[sy][sx] = 0

reach = False

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

    if (y,x) == (gy,gx):
        reach = True
        break

    for dy,dx in dyx:
        ny = y + dy
        nx = x + dx

        if ny < 0 or nx < 0 or ny >= H or nx >= W:
            continue

        # 空きマスかつ未訪問
        if _input[ny][nx] == '.' and counted_map[ny][nx] == -1:
            counted_map[ny][nx] = counted_map[y][x] + 1
            queue.append((ny,nx))

if not reach:
    print(-1)
    exit()
'''
y,x = gy,gx
move_num = counted_map[gy][gx]
while move_num != 0:
    _input[y][x] = 'o'
    for dy,dx in dyx:
        ny = y + dy
        nx = x + dx

        if ny < 0 or nx < 0 or ny >= H or nx >= W:
            continue
        
        if _input[ny][nx] == '.':
            tmp_dist = counted_map[ny][nx]
            if tmp_dist < move_num:
                move_num = tmp_dist
                next_y,next_x = ny,nx
    
    y,x = next_y,next_x

_input[sy][sx] = 'o'
'''

res = 0

for raw in _input:
    for i in raw:
        if i == '.':
            res += 1

print(res-counted_map[gy][gx])

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w = map(int,input().split())
hw = [];count = 0;check = False
for i in range(h):
    ls = [x for x in input()]
    for j in range(w):
        if ls[j] == '.':count += 1
    hw.append(ls)
deq = deque()
matrix = [[False for j in range(w)] for i in range(h)]
deq.appendleft([0,0,0])
while deq:
    ls = deq.pop()
    for i in [[1,0],[-1,0],[0,1],[0,-1]]:
        x = ls[0]+i[0];y = ls[1]+i[1]
        if x < 0 or y < 0 or x >= h or y >= w:continue
        if matrix[x][y]:continue
        if h-1 == x and w-1 == y:check = True;num = ls[2];break
        deq.appendleft([x,y,ls[2]+1])
        matrix[x][y] = True
    if check:break
if check:print(count-num-2)
else:print(-1)

Submission status: Wrong Answer

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python

H,W = map(int, input().split())
S   = [ input() for _ in range(H)]
inf = float("inf")
costmap = [ [inf] * W for _ in range(H)]


kuro_num = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            kuro_num += 1
shiro_num = H*W - kuro_num

from collections import deque
q = deque()

q.append( (0,0,0) )

shortest  = inf
while q:
    h,w,cost = q.popleft()
    if h == H-1 and w == W-1:
        shortest = cost
        break

    if w < W-1 and S[h][w+1] == "." and  costmap[h][w+1]==inf:
        q.append( (h, w+1, cost+1) )
        costmap[h][w+1] = cost+1
    if h < H-1 and S[h+1][w] == "." and  costmap[h+1][w] == inf:
        q.append( (h+1, w, cost+1) )
        costmap[h+1][w] = cost+1

if shortest == inf:
    ans = -1
else:
    ans  =  shiro_num - (shortest+1)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python

H,W = map(int, input().split())
S   = [ input() for _ in range(H)]
inf = float("inf")
costmap = [ [inf] * W for _ in range(H)]


kuro_num = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            kuro_num += 1
shiro_num = H*W - kuro_num

from collections import deque
q = deque()

q.append( (0,0,0) )

shortest  =0
while q:
    h,w,cost = q.popleft()
    if h == H-1 and w == W-1:
        shortest = cost
        break
    if h == H-1:
        if S[h][w+1] == "." and cost+1 < costmap[h][w+1]:
            costmap[h][w+1] = cost+1
            q.append( (h, w+1, cost+1) )
    elif w == W-1:
        if S[h+1][w] == "." and cost+1 < costmap[h+1][w]:
            q.append( (h+1, w, cost+1) )
            costmap[h+1][w] = cost+1
    else:
        if S[h][w+1] == "." and cost+1 < costmap[h][w+1]:
            q.append( (h, w+1, cost+1) )
            costmap[h][w+1] = cost+1
        if S[h+1][w] == "." and cost+1 < costmap[h+1][w]:
            q.append( (h+1, w, cost+1) )
            costmap[h+1][w] = cost+1

ans  =  shiro_num - (shortest+1)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python

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


kuro_num = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            kuro_num += 1
shiro_num = H*W - kuro_num

from collections import deque
q = deque()

q.append( (0,0,0) )

shortest  =0
while q:
    h,w,cost = q.popleft()
    if h == H-1 and w == W-1:
        shortest = cost
        break
    if h == H-1:
        if S[h][w+1] == ".":
            q.append( (h, w+1, cost+1) )
    elif w == W-1:
        if S[h+1][w] == ".":
            q.append( (h+1, w, cost+1) )
    else:
        if S[h][w+1] == ".":
            q.append( (h, w+1, cost+1) )
        if S[h+1][w] == ".":
            q.append( (h+1, w, cost+1) )

ans  =  shiro_num - (shortest+1)
print(ans)

Submission status: Wrong Answer

Solution code:
#!/mnt/c/Users/moiki/bash/env/bin/python

H,W = map(int, input().split())
S   = [ input() for _ in range(H)]
inf = float("inf")
costmap = [ [inf] * W for _ in range(H)]

def dfs(h,w,cost):
    if h == H-1 and w == W-1: 
        costmap[h][w] = min(costmap[h][w], cost)
        return cost

    if costmap[h][w] == inf:
        return costmap[h][w]

kuro_num = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == "#":
            kuro_num += 1
shiro_num = H*W - kuro_num

from collections import deque
q = deque()

q.append( (0,0,0) )

shortest  =0
while q:
    h,w,cost = q.popleft()
    if h == H-1 and w == W-1:
        shortest = cost
        break
    if h == H-1:
        if S[h][w+1] == ".":
            q.append( (h, w+1, cost+1) )
    elif w == W-1:
        if S[h+1][w] == ".":
            q.append( (h+1, w, cost+1) )
    else:
        if S[h][w+1] == ".":
            q.append( (h, w+1, cost+1) )
        if S[h+1][w] == ".":
            q.append( (h+1, w, cost+1) )

ans  =  shiro_num - (cost+1)
print(ans)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
board = [list(input()) for _ in range(h)]

kabe = 0
for x in range(w):
    for y in range(h):
        if board[y][x] == "#":
            kabe += 1
s = [0, 0]
g = [h-1, w-1]
d = [[-1 for _ in range(w)] for _ in range(h)]
queue = []
queue.append(s)
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
while len(queue) != 0:
    p = queue.pop(0)
    if p[0] == g[0] and p[1] == g[1]:
        break
    for x, y in zip(dx, dy):
        nx = p[1] + x
        ny = p[0] + y
        if 0<=nx<w and 0<=ny<h and board[ny][nx] != "#" and d[ny][nx] == -1:
            d[ny][nx] = d[p[0]][p[1]] + 1
            queue.append([ny, nx])
print(h*w - d[g[0]][g[1]] - kabe - 2)

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
grid = [[False]*w for i in range(h)]
white_cnt = 0
for i in range(h):
    s = input()
    for j in range(w):
        if s[j] == ".":
            grid[i][j] = True
            white_cnt += 1

q = deque()
q.append((0,0))
grid[0][0] = 1
while q:
    y, x = q.pop()
    for dy, dx in [[-1,0],[1,0],[0,1],[0,-1]]:
            yn = y + dy
            xn = x + dx
            if 0<=yn<h and 0<=xn<w and grid[yn][xn] is True:
                grid[yn][xn] = grid[y][x] + 1
                q.append((yn, xn))
if grid[-1][-1] is True:
    print(-1)
else:
    print(white_cnt - grid[-1][-1])

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]
white = 0
for line in M:
    white += line.count('.')
visited = [[False for _ in range(W)] for _ in range(H)]
que = deque()
que.append((0, 0, -1))
visited[0][0] = True
dirction = ((1, 0), (0, 1), (-1, 0), (0, -1))
while que:
    h, w, count = que.popleft()
    if (h, w) == (H - 1, W - 1):
        print(white - count)
        break
    for i in range(4):
        nh, nw = (h + dirction[i][0], w + dirction[i][1])
        if 0 <= nh <= H - 1 and 0 <= nw <= W - 1:
            if M[nh][nw] == '.' and not visited[nh][nw]:
                que.append((nh, nw, count + 1))
                visited[nh][nw] = True
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]
used = [[False for _ in range(W)] for _ in range(H)]
que = deque()
que.append((0, 0))
used[0][0] = True
dic = {}
while que:
    point = que.pop()
    if point == (H - 1, W - 1):
        break
    h, w = point
    if h - 1 >= 0 and M[h - 1][w] == '.' and not used[h - 1][w]:
        dic[(h - 1, w)] = (h, w)
        que.append((h - 1, w))
        used[h - 1][w] = True
    if h + 1 <= H - 1 and M[h + 1][w] == '.' and not used[h + 1][w]:
        dic[(h + 1, w)] = (h, w)
        que.append((h + 1, w))
        used[h + 1][w] = True
    if w - 1 >= 0 and M[h][w - 1] == '.' and not used[h][w - 1]:
        dic[(h, w - 1)] = (h, w)
        que.append((h, w - 1))
        used[h][w - 1] = True
    if w + 1 <= W - 1 and M[h][w + 1] == '.' and not used[h][w + 1]:
        dic[(h, w + 1)] = (h, w)
        que.append((h, w + 1))
        used[h][w + 1] = True
else:
    print(-1)
    sys.exit()
route = 1
point = (H - 1, W - 1)
while True:
    point = dic[point]
    route += 1
    if point == (0, 0):
        break
white = 0
for line in M:
    white += line.count('.')
print(white - route)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
sx, sy = 0, 0
gx, gy = h - 1, w - 1
A = [list(input()) for i in range(h)]

INF = 100000000
D = [[INF] * w for i in range(h)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0 , -1]

def bfs():
    que = []
    que.append([sx, sy])
    D[sx][sy] = 0
    
    while que != []:
        p = que.pop(0)
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and A[nx][ny] != '#' and D[nx][ny] == INF:
                que.append([nx, ny])
                D[nx][ny] = D[p[0]][p[1]] + 1
            
    return D[gx][gy]

r = bfs()

cnt = 0
for i in range(h):
    for j in range(w):
        if A[i][j] == '.':
            cnt += 1
            
print(cnt - r - 1)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w = map(int, input().split())
adj = deque(maxlen=h*w)
sl = [list(input()) for _ in range(h)]
maze = [[0]*w for _ in range(h)]
inf = 999999
dist = [[inf]*w for _ in range(h)]
max = h*w
for l in sl:
    max -= l.count('#')


def bfs(i,j):
    if maze[i][j]=='#' or (i,j) == (w-1,j-1):
        return
    maze[i][j]='#'
    d=dist[i][j] + 1
    if i+1<h:
        if maze[i+1][j]!='#' and dist[i+1][j]>d:
            adj.append([i+1,j])
            dist[i+1][j] = d
    if j+1<w:
        if maze[i][j+1]!='#' and dist[i][j+1]>d:
            adj.append([i,j+1])
            dist[i][j+1] = d
    if i-1>=0:
        if maze[i-1][j]!='#' and dist[i-1][j]>d:
            adj.append([i-1,j])
            dist[i-1][j] = d
    if j-1>=0:
        if maze[i][j-1]!='#' and dist[i][j-1]>d:
            adj.append([i,j-1])
            dist[i][j-1] = d

adj.append([0,0])
dist[0][0]=1
# time=0
while len(adj)>0:
    p = adj.popleft()
    bfs(p[0],p[1])
    # print('{}:{}'.format(time,adj))
    # time+=1
print(max - dist[h-1][w-1])

Submission status: Wrong Answer

Solution code:
# 最短経路を探す bfs
# (全体の白の数) - (けぬす君が通ったマスの数) = (答え)
from collections import deque
H,W = map(int,input().split())
grid = [[""]*W for i in range(H)]
visited = [[0]*W for i in range(H)]
visited[0][0] = 1
white = 0

for i in range(H):
    s = input()
    for j in range(W):
        grid[i][j] = s[j]
        if grid[i][j] == ".":
            white += 1

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

while q:
    i,j = q.popleft()
    if (i,j) == (H-1,W-1):
        break
    for di,dj in d:
        if 0 <= i+di <= H-1 and 0 <= j+dj <= W-1 and visited[i+di][j+dj] == 0:
            np = [i+di,j+dj]
            visited[i+di][j+dj] = visited[i][j] + 1
            q.append(np)

ans = white - visited[H-1][W-1]
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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


masu = [input() for _ in range(H)]

# search for kuro
kuro = 0
for row in masu:
    for s in row:
        if s == '#':
            kuro += 1


# search for minimum dist by bfs
que = deque([(0, 0, 0)])
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]
visited = [[False for _ in range(W)] for _ in range(H)]

# print(len(visited[0]), len(visited))

while (que):
    i, j, cost = que.popleft()
    visited[j][i] = True
    if (j == H - 1) and (i == W - 1):
        break

    for movex, movey in move:
        tmpx, tmpy = i + movex, j + movey
        if (tmpx < 0) or(tmpx >= W) or (tmpy < 0) or (tmpy >= H):
            continue

        if (masu[tmpy][tmpx] == '.') and not(visited[tmpy][tmpx]):
            que.append((i + movex, j + movey, cost + 1))


print(H * W - kuro - cost - 1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

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

cnt = 0
for _ in range(H):
    l = input()
    cnt += l.count('.')
    grid.append([v for v in l])

# 動的計画法 dp[i][j]->grid[i][j]に行くための最短距離
dp = [[float('inf')]*W for _ in range(H)]


def dfs(i, j, dist):
    if 0 <= i < H and 0 <= j < W:
        if grid[i][j] != '#':
            if dp[i][j] < dist:
                return
            else:
                dp[i][j] = dist

                new_dist = dist+1
                dfs(i+1, j, new_dist)
                dfs(i-1, j, new_dist)
                dfs(i, j+1, new_dist)
                dfs(i, j-1, new_dist)


def solve():
    dfs(0, 0, 1)
    min_dist = dp[H-1][W-1]
    return cnt - min_dist


print(solve())

Submission status: Wrong Answer

Solution code:
h, w = list(map(int, input().split()))
li = []
for _ in range(h):
    li.append(input())

# construct graph
from collections import defaultdict
edges = defaultdict(list)
for i in range(h):
    for j in range(w):
        idx = i * w + j
        if li[i][j] == '.':
            if i + 1 < h and li[i + 1][j] == '.':
                edges[idx].append(idx + w)
                edges[idx + w].append(idx)
            if j + 1 < w and li[i][j + 1] == '.':
                edges[idx].append(idx + 1)
                edges[idx + 1].append(idx)
goal = h * w - 1
# root search
from collections import deque
Q = deque()
Q.append(0)
reach = False
visited = set()
while len(Q) > 0:
    u = Q.pop()
    if u == goal:
        reach = True
        break
    for v in edges[u]:
        if v not in visited:
            visited |= {v}
            Q.append(v)

ans = -1
if reach:
    white = sum(a.count('.') for a in li)
    ans = white - (h + w - 1)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
H, W = map(int, input().split())
con = [[1,0],[0,1],[-1,0],[0,-1]]
m=[]
c = 0
d = [[0]*(W+2) for _ in range(H+2)]
d[1][1]= 1
m.append("#"*(W+2))
for i in range(H):
    b = input()
    c +=b.count(".")
    a= "#"+b+"#"
    m.append(a)
q = deque()
m.append("#"*(W+2))
q.append((1,1))

while len(q)>0:
    y,x = q.popleft()
    if y == H and x == W:
        print(c-d[H][W])
        exit()
    for dx,dy in con:
        #print(y+dy,x+dx,d[y+dy][x+dx])
        if d[y+dy][x+dx] == 0 and m[y+dy][x+dx] ==".":
            q.append((y+dy,x+dx))
            d[y+dy][x+dx]+=d[y][x]+1
    #print(q)
print(-1)

for i in range(H+2):
    s = ""
    for j in range(W+2):
        s+=str(m[i][j])+"  "
    print(s)

for i in range(H+2):
    s = ""
    for j in range(W+2):
        s+=str(d[i][j])+"  "
    print(s)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [input() for i in range(h)]
visited = [[-1]*w for i in range(h)]
que = deque()

def bfs(i,j):
  que.append([i,j])
  visited[i][j]=0
  
  while True:
    if not que:
      return -1
    
    [current_i,current_j] = que.popleft()
    
    if  current_i == h-1 and current_j == w-1:
      return visited[current_i][current_j]
  
    for next in [[-1,0],[+1,0],[0,-1],[0,+1]]:
      next_i = current_i + next[0]
      next_j = current_j + next[1]
      if 0<=next_i<h and 0<=next_j<w:
        if visited[next_i][next_j] == -1 and s[next_i][next_j]==".":
          visited[next_i][next_j] = visited[current_i][current_j]+1
          que.append([next_i,next_j])

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

if bfs(0,0)==-1:
  print(-1)
else:
  print(count_point-bfs(0,0)-1)

Submission status: Wrong Answer

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [input() for i in range(h)]
visited = [[-1]*w for i in range(h)]
que = deque()

def bfs(i,j):
  que.append([i,j])
  visited[i][j]=0
  
  while True:
    if not que:
      return -1
    
    [current_i,current_j] = que.popleft()
    
    if  current_i == h-1 and current_j == w-1:
      return visited[current_i][current_j]
  
    for next in [[-1,0],[+1,0],[0,-1],[0,+1]]:
      next_i = current_i + next[0]
      next_j = current_j + next[1]
      if 0<=next_i<h and 0<=next_j<w:
        if visited[next_i][next_j] == -1 and s[next_i][next_j]==".":
          visited[next_i][next_j] = visited[current_i][current_j]+1
          que.append([next_i,next_j])

count_point=0
for i in range(h):
  for j in range(w):
    if s[i][j] == ".":
      count_point += 1 
  
print(count_point-bfs(0,0)-1)

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
a = [list(input()) for _ in range(h)]
 
def check(x):
    if x == 'U':
        y = i-1
        z = j
    elif x == 'D':
        y = i+1
        z = j
    elif x == 'L':
        y = i
        z = j-1
    else:
        y = i
        z = j+1
        
    if a[y][z] != '.':
        return
    else:
        a[y][z] = a[i][j]+1
        
 
 
cnt = 0
for i in range(h):
    for j in range(w):
        if a[i][j] == '#':
            cnt += 1
            
        if i == j == 0:
            a[i][j] = 0
            check('R')
            check('D')
        elif i == h-1 and j == w-1:
            break
        elif (a[i][j] != '.') and (a[i][j] != '#'):
            if i == h-1 and j == 0:
                check('U')
                check('R')
            elif i == 0 and j == w-1:
                check('L')
                check('D')
            elif 0 < i < h-1 and j == 0:
                check('U')
                check('D')
                check('R')
            elif 0 < i < h-1 and j == w-1:
                check('U')
                check('D')
                check('L')
            elif i == 0 and 0 < j < w-1:
                check('L')
                check('R')
                check('D')
            elif i == h-1 and 0 < j < w-1:
                check('L')
                check('R')
                check('U')
            else:
                check('U')
                check('D')
                check('L')
                check('R')
 
if (a[h-1][w-1] == '.') or (a[h-1][w-1] == '#'):
    print(-1)
else:
    print(h*w - cnt - (a[h-1][w-1] + 1))

Submission status: Wrong Answer

Solution code:
from collections import deque

INF = float('inf')

dr = (-1, 0, 0, 1)
dc = (0, -1, 1, 0)

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

s = []
total_white_count = 0
for _ in range(H):
    t = tuple(map(lambda x: 1 if x == '.' else 0, list(input())))
    s.append(t)
    total_white_count += sum(t)
p = [[INF for _ in range(W)] for _ in range(H)]

ans = -1

dq = deque()
dq.append((0, 0, 1))
while dq:
    r, c, d = dq.pop()

    nd = d + 1
    for i in range(4):
        nr = r + dr[i]
        nc = c + dc[i]
        if not (0 <= nr < H and 0 <= nc < W): continue
        if s[nr][nc] == 0 : continue
        if p[nr][nc] <= nd: continue
        p[nr][nc] = nd
        if nr == H - 1 and nc == W - 1:
            ans = total_white_count - nd
            break
        dq.append((nr, nc, nd))
    else:
        continue
    break

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

INF = float('inf')

dr = (-1, 0, 0, 1)
dc = (0, -1, 1, 0)

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

s = []
total_white_count = 0
for _ in range(H):
    t = list(map(lambda x: 1 if x == '.' else 0, list(input())))
    s.append(t)
    total_white_count += sum(t)
p = [[INF for _ in range(W)] for _ in range(H)]

ans = -1

dq = deque()
dq.append((0, 0, 1))
while dq:
    r, c, d = dq.pop()
    if p[r][c] <= d:
        continue
    else:
        p[r][c] = d
    if r == H - 1 and c == W - 1:
        ans = total_white_count - d
        break

    for i in range(4):
        nr = r + dr[i]
        nc = c + dc[i]
        nd = d + 1
        if not (0 <= nr < H and 0 <= nc < W): continue
        if not s[nr][nc] & 1 : continue
        dq.append((nr, nc, nd))

print(ans)