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())
A = ''
for _ in [0]*H:
    A += input()
from collections import deque
max_len = len(A)
visited = [0] * (H*W)
def walk(x):
    global ans
    for i in x:
        visited[i] = 1 
    ans += 1
    num = deque(x)
    next_num = []
    while num:
        now = num.popleft()
        if now == H*W-1:
            return
        #migi
        if now+1 % W != 0 and now+1<max_len:
            if A[now+1] == '.':
                if visited[now+1] == 0:
                    next_num.append(now+1)
        if now % W != 0 and now-1 >= 0:
            if A[now-1] == '.':
                if visited[now-1] == 0:
                    next_num.append(now-1)
        if now + W < max_len:
            if A[now+W] == '.':
                if visited[now+W] == 0:
                    next_num.append(now+W)
        if now-W >= 0:
            if A[now-W] =='.':
                if visited[now-W] == 0:
                    next_num.append(now-W)
    if next_num:
        walk(next_num)
    return ans
ans = 0
black = sum([True for i in A if i == '#'])
min_path = walk([0])
if visited[max_len-1] == 1:
    print(H*W - black - min_path)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
A = ''
for _ in [0]*H:
    A += input()
from collections import deque
from collections import deque
max_len = len(A)
visited = [0] * (H*W)
def walk(x):
    global ans
    global can
    ans += 1
    num = deque(x)
    next_num = []
    while num:
        now = num.popleft()
        if now == H*W-1:
            return
        #migi
        if now+1 % W != 0 and now+1<max_len:
            if A[now+1] == '.':
                if visited[now+1] == 0:
                    visited[now+1] = 1
                    next_num.append(now+1)
        if now % W != 0 and now-1 >= 0:
            if A[now-1] == '.':
                if visited[now-1] == 0:
                    visited[now-1] = 1
                    next_num.append(now-1)
        if now + W < max_len:
            if A[now+W] == '.':
                if visited[now+W] == 0:
                    visited[now+W] = 1
                    next_num.append(now+W)
        if now-W >= 0:
            if A[now-W] =='.':
                if visited[now-W] == 0:
                    visited[now-W] = 1
                    next_num.append(now-W)
    if next_num:
        walk(next_num)
    return ans
ans = 0
black = sum([True for i in A if i == '#'])
min_path = walk([0])
if visited[max_len-1] == 1:
    print(H*W - black - min_path)
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
A = ''
for _ in [0]*H:
    A += input()
from collections import deque

max_len = len(A)
visited = [0] * (H*W)
def walk(x):
    global ans
    ans += 1
    num = deque(x)
    next_num = []
    while num:
        now = num.popleft()
        if now == H*W-1:
            return
        #migi
        if now+1 % W != 0 and now+1<max_len:
            if A[now+1] == '.':
                if visited[now+1] == 0:
                    visited[now+1] = 1
                    next_num.append(now+1)
        if now % W != 0 and now-1 >= 0:
            if A[now-1] == '.':
                if visited[now-1] == 0:
                    visited[now-1] = 1
                    next_num.append(now-1)
        if now + W < max_len:
            if A[now+W] == '.':
                if visited[now+W] == 0:
                    visited[now+W] = 1
                    next_num.append(now+W)
        if now-W >= 0:
            if A[now-W] =='.':
                if visited[now-W] == 0:
                    visited[now-W] = 1
                    next_num.append(now-W)
    if next_num:
        walk(next_num)
    return ans
ans = 0
black = sum([True for i in A if i == '#'])
print(H*W - black - walk([0]))

Submission status: Wrong Answer

Solution code:
from queue import Queue
from itertools import product


def main():
    h, w = map(int, input().split())
    grid = ["." * w for _ in range(h)]
    for i in range(h):
        grid[i] = input()
    num_white = 0
    for i, j in product(range(h), range(w)):
        if grid[i][j] == ".":
            num_white += 1
    dist = [[-1] * w for _ in range(h)]
    q = Queue()
    q.put((0, 0))
    dist[0][0] = 1
    di = [-1, 0, 1, 0]
    dj = [0, 1, 0, -1]
    while not q.empty():
        i, j = q.get()
        d = dist[i][j]
        for k in range(4):
            ni = i + di[k]
            nj = j + dj[k]
            if ni < 0 or ni >= h or nj < 0 or nj >= w:
                continue
            if grid[ni][nj] == "#":
                continue
            if dist[ni][nj] != -1 and dist[ni][nj] <= d:
                continue
            dist[ni][nj] = d + 1
            q.put((ni, nj))
    print(num_white - dist[h - 1][w - 1])


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[INF] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)



for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1

if S[0][0] == "#":
    print("-1")
    exit()
while q:
    h, w = q.pop()
    # if S[h][w] == "#":
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = min(dist[h][w] + 1, dist[nh][nw])
                visited[nh][nw] = True
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
if dist[H-1][W-1] == INF:
    print(-1)
else:
    print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[INF] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)
for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1
while q:
    h, w = q.pop()
    # if S[h][w] == "#":
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = min(dist[h][w] + 1, dist[nh][nw])
                visited[nh][nw] = True
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
if dist[H-1][W-1] == INF:
    print(-1)
else:
    print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[INF] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)
for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1
while q:
    h, w = q.pop()
    # if S[h][w] == "#":
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = min(dist[h][w] + 1, dist[nh][nw])
                visited[h][w] = True
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
if dist[H-1][W-1] == INF:
    print(-1)
else:
    print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[INF] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)
for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1
while q:
    h, w = q.popleft()
    visited[h][w] = True
    # if S[h][w] == "#":
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            # print(nw, nh)
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = min(dist[h][w] + 1, dist[nh][nw])
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[INF] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)
for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1
while q:
    h, w = q.pop()
    visited[h][w] = True
    # if S[h][w] == "#":
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            # print(nw, nh)
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = min(dist[h][w] + 1, dist[nh][nw])
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[0] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)
for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1
while q:
    h, w = q.popleft()
    visited[h][w] = True
    # if S[h][w] == "#":
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            # print(nw, nh)
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = dist[h][w] + 1
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
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()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W = MAP()
s = ["#"*(W+2)] + ["#"+input()+"#" for _ in range(H)] + ["#"*(W+2)]

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

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

q = deque()
q.append((1, 1))
dist = [[-1]*(W+2) for _ in range(H+2)]
dist[1][1] = 0
cnt = 0
while q:
	y, x = q.popleft()
	for i in range(4):
		ny = y+dy[i]
		nx = x+dx[i]
		if s[ny][nx] == "." and dist[ny][nx]==-1:
			dist[ny][nx] = dist[y][x]+1
			q.append((ny, nx))

print(white-dist[H][W]-1 if dist[H][W] != -1 else 0)

Submission status: Wrong Answer

Solution code:
import sys, re, os
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
from bisect import bisect, bisect_left, bisect_right

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

H, W = MAP()
S = [input() for h in range(H)]
q = deque([(0, 0)])
# s : 0, 0
# g : H - 1, W - 1
visited = [[False] * W for i in range(H)]
dw = [0, 1, 0, -1]
dh = [1, 0, -1, 0]
dist = [[0] * W for i in range(H)]
dist[0][0] = 1

dic = defaultdict(int)
for h in range(H):
    for w in range(W):
        dic[S[h][w]] += 1
while q:
    h, w = q.popleft()
    visited[h][w] = True
    for i in range(4):
        nw = w + dw[i]
        nh = h + dh[i]
        if 0 <= nw < W and 0 <= nh < H:
            # print(nw, nh)
            if S[nh][nw] != "#" and visited[nh][nw] == False:
                dist[nh][nw] = dist[h][w] + 1
                q.append((nh, nw))
# print(visited)
# print(*dist, sep="\n")
print(dic["."] - dist[H-1][W-1])

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000)
H, W = map(int, input().split())
S = []
white = 0
for i in range(H):
  s = str(input())
  S.append(s)
  white += s.count('.')
  
def main(h, w, cnt, l):
  global H
  global W
  global S
  global white
  tmp = []
  if h < H-1:
    if (S[h+1][w]=='.') and ([h+1, w] not in l):
      tmp.append([h+1, w])
  if w < W-1:
    if (S[h][w+1]=='.') and ([h, w+1] not in l):
      tmp.append([h, w+1])
  if 0 < h:
    if (S[h-1][w]=='.') and ([h-1, w] not in l):
      tmp.append([h-1, w])
  if 0 < w:
    if (S[h][w-1]=='.') and ([h, w-1] not in l):
      tmp.append([h, w-1])
  cnt += 1
  l = l + tmp
  if tmp == []:
    return white+1
  elif [H-1, W-1] in tmp:
    return cnt
  else:
    for n in tmp:
      return main(n[0], n[1], cnt, l)
    
ans = white - main(0, 0, 1, [[0,0]])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10000)
H, W = map(int, input().split())
S = []
white = 0
for i in range(H):
  s = str(input())
  S.append(s)
  white += s.count('.')
  
def main(h, w, cnt, l):
  global H
  global W
  global S
  tmp = []
  if h < H-1:
    if (S[h+1][w]=='.') and ([h+1, w] not in l):
      tmp.append([h+1, w])
  if w < W-1:
    if (S[h][w+1]=='.') and ([h, w+1] not in l):
      tmp.append([h, w+1])
  if 0 < h:
    if (S[h-1][w]=='.') and ([h-1, w] not in l):
      tmp.append([h-1, w])
  if 0 < w:
    if (S[h][w-1]=='.') and ([h, w-1] not in l):
      tmp.append([h, w-1])
  cnt += 1
  l = l + tmp
  if tmp == []:
    return -1
  elif [H-1, W-1] in tmp:
    return cnt
  else:
    for n in tmp:
      return main(n[0], n[1], cnt, l)
    
ans = white - main(0, 0, 1, [[0,0]])
print(ans)

Submission status: Wrong Answer

Solution code:
#幅優先探索
H,W=map(int,input().split())
sy,sx=0,0
gy,gx=H-1,W-1
MAZE=[0]*H
queue=[]
queue.append([sy,sx])
black=0
for i in range(H):
  MAZE[i]=list(str(input()))
  black+=MAZE[i].count('#')
MAZE[sy][sx]='#'

d=[[100000000]*W for i in range(H)]
d[sy][sx]=0
dx=[1,0,-1,0]
dy=[0,1,0,-1]

while len(queue)>0:
  #Qを取り出す
  Q=queue.pop(0)
  move=d[Q[0]][Q[1]]
  #もし取り出したところがゴールなら出力して終了
  if Q==[gy,gx]:
    break
  #4方向をループする
  for j in range(4):
    y=Q[0]+dy[j]
    x=Q[1]+dx[j]
    if 0<=y<H and 0<=x<W and MAZE[y][x] == '.':
      queue.append([y,x])
      MAZE[y][x] = '#'
      d[y][x] = move+1
print(H*W-black-move-1)

Submission status: Wrong Answer

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

H,W = map(int, input().split())
mapmatrix = [None]*H
before_black_cnt = 0
for i in range(H):
    st = input()
    before_black_cnt += st.count('#')
    mapmatrix[i] = list(st)


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

move = ((-1,0),(1,0),(0,-1),(0,1))

while queue:
    x,y = queue.popleft()
    
    distance = distancelist[y][x]
    for dx,dy in move:
        X = x + dx; Y = y + dy
        if X >= 0 and X < W and Y >= 0 and Y < H:
            if distancelist[Y][X] == -1 and mapmatrix[Y][X] == '.':
                distancelist[Y][X] = distance + 1
                queue.append((X,Y))

after_black_cnt = W*H - distancelist[H-1][W-1]
print(after_black_cnt - before_black_cnt)

Submission status: Wrong Answer

Solution code:
print(-1)

Submission status: Wrong Answer

Solution code:
import copy
import math
import time
import statistics
import math
import itertools
import bisect
import sys
from decimal import *
from collections import deque


def get_int():
    return int(input())

def get_string():
    return input()

def get_int_list():
    return [int(x) for x in input().split()]

def get_string_list():
    return input().split()

def get_int_multi():
    return map(int, input().split())

def get_string_char_list():
    return list(str(input()))

# print("{} {}".format(a, b))
# a_list = [0] * a
sys.setrecursionlimit(10 ** 6)

def main():
    start = time.time()

    h, w = get_int_multi()

    d = [[-1] * (w+2) for _ in range(h+2)]

    shiro = 0
    for i in range(h):
        wk = get_string()
        for ii in range(w):
            if wk[ii] == ".":
                d[i+1][ii+1] = 10**9
                shiro += 1


    d[1][1] = 1
    q = deque([])
    q.append([1,1])

    while q:
        wk = q.popleft()
        i = wk[0]
        ii = wk[1]
        hosuu = d[i][ii]

        if i == h and ii == w:
            print(shiro-hosuu)
            break

        def add_que(i,ii,hosuu):
            if d[i][ii] == 10**9:
                d[i][ii] = hosuu + 1
                q.append([i,ii])

        add_que(i-1,ii, hosuu)
        add_que(i+1,ii, hosuu)
        add_que(i,ii-1, hosuu)
        add_que(i,ii+1, hosuu)




if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
INFTY = 10000
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
A = [[0 for _ in range(W)] for _ in range(H)]
cnt = 0
for i in range(H):
    for j in range(W):
        if S[i][j]=="#":
            A[i][j]=INFTY
            cnt += 1
que = deque([(0,0,0)])
while que:
    i,j,d = que.popleft()
    if j+1<W and A[i][j+1]==0:
        A[i][j+1]=d+1
        que.append((i,j+1,d+1))
    if i-1>=0 and A[i-1][j]==0:
        A[i-1][j]=d+1
        que.append((i-1,j,d+1))
    if j-1>=0 and A[i][j-1]==0:
        A[i][j-1]=d+1
        que.append((i,j-1,d+1))
    if i+1<H and A[i+1][j]==0:
        que.append((i+1,j,d+1))
if A[H-1][W-1]==0:
    print(-1)
else:
    print(H*W-cnt-A[H-1][W-1]-1)

Submission status: Wrong Answer

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


def read():
    H, W = map(int, input().strip().split())
    S = []
    for i in range(H):
        s = list(input().strip())
        S.append(s)
    return H, W, S


def solve(H, W, S):
    n_cells = 0
    for y in range(H):
        for x in range(W):
            if S[y][x] == ".":
                n_cells += 1
    A = [[-1 for j in range(W)] for i in range(H)]
    A[0][0] = 1
    D = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    q = deque()
    q.append((0, 0))
    while q:
        y, x = q.popleft()
        for dy, dx in D:
            ny, nx = y + dy, x + dx
            if 0 <= ny < H and 0 <= nx < W and S[ny][nx] == "." and A[ny][nx] == -1:
                A[ny][nx] = A[y][x] + 1
                q.append((ny, nx))
    shortest = A[H-1][W-1]
    return n_cells - shortest


if __name__ == '__main__':
    inputs = read()
    print(solve(*inputs))

Submission status: Wrong Answer

Solution code:
from collections import deque

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

adj = [[] for _ in range(W*H)]
dx = [1,-1,0,0]
dy = [0,0,1,-1]
ans = 0

for i in range(H):
    for j in range(W):
        if s[i][j] == '#': continue
        ans += 1
        for k in range(4):
            y = i + dy[k]
            x = j + dx[k]
            if 0 <= y < H and 0 <= x < W:
                if s[y][x] == '.':
                    adj[W*i + j].append(W*y + x)

queue = deque([0])
visit = [-1] * (H*W)
visit[0] = 1

while queue:
    now = queue.popleft()
    for u in adj[now]:
        if visit[u] < 0:
            queue.append(u)
            visit[u] = visit[now] + 1

print(ans - visit[H*W-1])

Submission status: Wrong Answer

Solution code:
H,W = map(int,input().split())
S = [input() for i in range(H)]
blk = sum(row.count('#') for row in S)

from collections import deque
dxy = [(0,1),(1,0),(0,-1),(-1,0)]
dist = [[0]*W for i in range(H)]
visited = [[0]*W for i in range(H)]
visited[0][0] = 1
q = deque([(0,0)])
while q:
    x,y = q.popleft()
    for dx,dy in dxy:
        nx,ny = x+dx,y+dy
        if not 0 <= nx < W: continue
        if not 0 <= ny < H: continue
        if visited[ny][nx]: continue
        if S[ny][nx] == '#': continue
        visited[ny][nx] = 1
        dist[ny][nx] = dist[y][x] + 1
        q.append((nx,ny))
print(H*W - blk - dist[-1][-1] - 1)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
dist = [[-1 for _ in range(w+2)] for _ in range(h+2)]
dist[1][1] = 1
white = 0
dl = [[1, 0], [0, 1], [-1, 0], [0, -1]]
tmp = ["#" for _ in range(w+2)]
S = [tmp]
for i in range(h):
    S.append([])
    for j in range(w):
        white += 1 if s[i][j] == "." else 0
    S[i+1].extend("#")
    S[i+1].extend(s[i])
    S[i+1].extend("#")
S.append(tmp)


def dfs():
    global S, dl
    queue = [[1, 1]]

    while len(queue) != 0:
        [x, y] = queue.pop()
        for d in dl:
            if dist[x + d[0]][y + d[1]] == -1 and S[x + d[0]][y + d[1]] == ".":
                dist[x + d[0]][y + d[1]] = dist[x][y] + 1
                queue.append([x + d[0], y + d[1]])


dfs()
if dist[h][w] == -1:
    print(-1)
else:
    print(white-dist[h][w])

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
f = [[False for _ in range(w)] for _ in range(h)]
white = 0

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


def dfs():
    queue = [[0, 0, 1]]
    solve = False
    while len(queue) != 0:
        q = queue.pop()
        if q[0] == h - 1 and q[1] == w - 1:
            solve = True
            break
        facing = []
        if q[0] != 0:
            facing.append([-1, 0])
        if q[0] != h - 1:
            facing.append([1, 0])
        if q[1] != 0:
            facing.append([0, -1])
        if q[1] != w - 1:
            facing.append([0, 1])
        for d in facing:
            if s[q[0] + d[0]][q[1] + d[1]] == ".":
                if not f[q[0] + d[0]][q[1] + d[1]]:
                    f[q[0] + d[0]][q[1] + d[1]] = True
                    queue.append([q[0] + d[0], q[1] + d[1], q[2] + 1])
    if q[0] == h - 1 and q[1] == w - 1:
        solve = True
    return q[2] if solve else -1


d = dfs()
print(white-d if d != -1 else -1)

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
f = [[False for _ in range(w)] for _ in range(h)]
white = 0

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


def dfs():
    queue = [[0, 0, 0]]
    solve = False
    while len(queue) != 0:
        q = queue.pop()
        if q[0] == h - 1 and q[1] == w - 1:
            solve = True
            break
        facing = []
        if q[0] != 0:
            facing.append([-1, 0])
        if q[0] != h - 1:
            facing.append([1, 0])
        if q[1] != 0:
            facing.append([0, -1])
        if q[1] != w - 1:
            facing.append([0, 1])
        for d in facing:
            if s[q[0] + d[0]][q[1] + d[1]] == ".":
                if not f[q[0] + d[0]][q[1] + d[1]]:
                    f[q[0] + d[0]][q[1] + d[1]] = True
                    queue.append([q[0]+d[0], q[1]+d[1], q[2]+1])
    return q[2] if solve else -1


d = dfs()
print(white-d-1 if d != -1 else -1)

Submission status: Wrong Answer

Solution code:
from collections import deque
H,W = map(int,input().split())
S = []
Blank = 0
for i in range(H):
  temp = str(input());temp = list(temp)
  Blank += temp.count(".")
  S.append(temp)
#print(S,Blank)
INF = float("inf")
Q = deque([])
Q.append([0,0])
dxdy = [[1,0],[-1,0],[0,1],[0,-1]]
visited = [[INF]*W for _ in range(H)]
visited[0][0] = 1
while Q:
  temp = Q.popleft()
  x = temp[0]; y = temp[1]
  for i in range(4):
    nx = x+dxdy[i][0]
    ny = y+dxdy[i][1]
    if 0<=nx<H and 0<=ny<W and visited[nx][ny] == INF and S[nx][ny] == ".":
      visited[nx][ny] = visited[x][y] + 1
      Q.append([nx,ny])
      if [nx,ny] == [H,W]:
        break
#print(visited)
ans = Blank - visited[H-1][W-1]
print(ans)