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())

s = []
bl = 0

for i in range(H):

    tmp = list(input())
    s.append(tmp)

for i in range(H):

    for j in range(W):

        if s[i][j] == "#":
            bl += 1

d = [[float("inf")] * W for i in range(H)]
d[0][0] = 1

from collections import deque
q = deque([(0,0)])

while len(q) > 0:

    now = q.popleft()
    x,y = now

    if x != 0 and d[x-1][y] > d[x][y] + 1:
        d[x-1][y] = d[x][y] + 1
        q.append( (x-1,y) )

    if x != H-1 and d[x+1][y] > d[x][y] + 1:
        d[x+1][y] = d[x][y] + 1
        q.append( (x+1,y) )

    if y != 0 and d[x][y-1] > d[x][y] + 1:
        d[x][y-1] = d[x][y] + 1
        q.append( (x,y-1) )

    if y != W-1 and d[x][y+1] > d[x][y] + 1:
        d[x][y+1] = d[x][y] + 1
        q.append( (x,y+1) )

if d[-1][-1] == float("inf"):
    print (-1)
else:
    print (H*W - bl - d[-1][-1])

Submission status: Wrong Answer

Solution code:

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

s = []
bl = 0

for i in range(H):

    tmp = list(input())
    s.append(tmp)

for i in range(H):

    for j in range(W):

        if s[i][j] == "#":
            bl += 1

d = [[float("inf")] * W for i in range(H)]
d[0][0] = 1

from collections import deque
q = deque([(0,0)])

while len(q) > 0:

    now = q.popleft()
    x,y = now

    if x != 0 and d[x-1][y] > d[x][y] + 1:
        d[x-1][y] = d[x][y] + 1
        q.append( (x-1,y) )

    if x != H-1 and d[x+1][y] > d[x][y] + 1:
        d[x+1][y] = d[x][y] + 1
        q.append( (x+1,y) )

    if y != 0 and d[x][y-1] > d[x][y] + 1:
        d[x][y-1] = d[x][y] + 1
        q.append( (x,y-1) )

    if y != W-1 and d[x][y+1] > d[x][y] + 1:
        d[x][y+1] = d[x][y] + 1
        q.append( (x,y+1) )

print (H*W - bl - d[-1][-1])

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def dfs(current, dist=0):
        x, y = current
        visited[x][y] = True
        if x == h and y == w:
            return dist
        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]
            if expanded_grid[next_x][next_y] == '.' and not visited[next_x][next_y]:
                dist = dfs((next_x, next_y), dist+1)
                if dist:
                    return dist
        return 0

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    d = dfs((1, 1))
    if d > 0:
        print(h*w - (d + 1) - initial_black) 
    else:
        print(-1)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def dfs(current):
        x, y = current
        visited[x][y] = True
        if x == h and y == w:
            return True
        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]
            if expanded_grid[next_x][next_y] == '.' and not visited[next_x][next_y]:
                if dfs((next_x, next_y)):
                    return True

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    assert(grid[0][0] == '.' and grid[h-1][w-1] == '.')
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    
    print(h*w - (h+w-1) - initial_black) if dfs((1, 1)) else print(-1)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def dfs(current):
        x, y = current
        visited[x][y] = True
        if x == h and y == w:
            return True
        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]
            if expanded_grid[next_x][next_y] == '.' and not visited[next_x][next_y]:
                if dfs((next_x, next_y)):
                    return True

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    
    print(h*w - (h+w-1) - initial_black) if dfs((1, 1)) else print(-1)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def dfs(current):
        x, y = current
        visited[x][y] = True
        if x == h and y == w:
            return True
        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]
            if expanded_grid[next_x][next_y] == '.' and not visited[next_x][next_y]:
                if dfs((next_x, next_y)):
                    return True
                else:
                    continue

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    
    print(h*w - (h+w-1) - initial_black) if dfs((1, 1)) else print(-1)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())


    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    def dfs(current):
        x, y = current
        visited[x][y] = True
        if x == h and y == w:
            return True
        for i in range(4):
            next_x, next_y = x + dx[i], y + dy[i]
            if expanded_grid[next_x][next_y] == '.' and not visited[next_x][next_y]:
                res = dfs((next_x, next_y))
                if res:
                    return True

    
    h, w = mi()
    grid = [input() for _ in range(h)]
    
    expanded_grid = []
    expanded_grid.append('#' * (w + 2))
    for line in grid:
        expanded_grid.append('#' + line + '#')
    expanded_grid.append('#' * (w + 2))

    visited = [[False] * (w + 2) for _ in range(h + 2)]

    initial_black = sum([line.count('#') for line in grid])
    print(max(h*w - (h+w-1) - initial_black, 0)) if dfs((1, 1)) else print(-1)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

que = [(0,0)]
keiro = {}
keiro[(0,0)] = 1
# print(m)
while que:
    h, w = que.pop(0)
    # print(h,w)
    if h+1 < H:
        if m[h+1][w] == '.':
            if (h+1,w) in keiro:
                keiro[(h+1,w)] = min(keiro[(h+1,w)],keiro[(h,w)]+1)
            else:
                keiro[(h+1,w)] = keiro[(h,w)]+1
                que.append((h+1,w))
    if w+1 < W:
        if m[h][w+1] == '.':
            if (h,w+1) in keiro:
                keiro[(h,w+1)] = min(keiro[(h,w+1)],keiro[(h,w)]+1)
            else:
                keiro[(h,w+1)] = keiro[(h,w)]+1
                que.append((h,w+1))

if (H-1,W-1) in keiro:
    print(count-keiro[(H-1,W-1)])
else:
    print(-1)

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
cnt = 0
L = []
for i in range(h):
    s = input()
    cnt +=s.count("#")
    L.append(list(s))
#print(L,cnt)

d = [[-1]*w for i in range(h)]
d[0][0] = 0
from collections import deque
q = deque([[0,0]])
#print(d,q)

li = ((1,0),(0,1),(-1,0),(0,-1))

while q:
    j,i = q.popleft()
    for dy,dx in li:
        #print(j,i,dy,dx,q)
        ny,nx = j+dy,i+dx
        if (ny < 0 or ny >= h) or (nx < 0 or nx >= w) or L[ny][nx] == "#":
            continue
        else:
            if d[ny][nx] == -1:
                d[ny][nx] = d[j][i] + 1
                q.append((j+dy,i+dx))
print(h*w - cnt - d[h-1][w-1]-1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)

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

from collections import deque
b = 0
INF = float("inf")
checked = [[INF]*w for i in range(h)]

q = deque([])
q.append((0,0))
checked[0][0] = 1
while len(q)>0:
    pos = q.popleft()
    if pos == (h-1,w-1):
        b = (checked[h-1][w-1])
        break
    if pos[0] > 0:
        if not maze[pos[0] - 1][pos[1]] == '#' and checked[pos[0] - 1][pos[1]] == INF:
            checked[pos[0] - 1][pos[1]] = checked[pos[0]][pos[1]] + 1
            q.append((pos[0] - 1, pos[1]))

    if pos[0] < h - 1:
        if not maze[pos[0] + 1][pos[1]] == '#' and checked[pos[0] + 1][pos[1]] == INF:
            checked[pos[0] + 1][pos[1]] = checked[pos[0]][pos[1]] + 1
            q.append((pos[0] + 1, pos[1]))

    if pos[1] > 0:
        if not maze[pos[0]][pos[1] - 1] == '#' and checked[pos[0]][pos[1] - 1] == INF:
            checked[pos[0]][pos[1] - 1] = checked[pos[0]][pos[1]] + 1
            q.append((pos[0], pos[1] - 1))

    if pos[1] < w - 1:
        if not maze[pos[0]][pos[1] + 1] == '#' and checked[pos[0]][pos[1] + 1] == INF:
            checked[pos[0]][pos[1] + 1] = checked[pos[0]][pos[1]] + 1
            q.append((pos[0], pos[1] + 1))
a = []
for i in range(h):
    a.append(maze[i].count("."))
print(sum(a)-b)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w = map(int,input().split())
m = ["#"*(w+2)]+["#"+input()+"#" for i in range(h)]+["#"*(w+2)]
temp = [[-1]*(w+2) for i in range(h+2)]
sy,sx = 1,1
temp[sy][sx] = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
dq = deque([(sy,sx)])
while dq:
    y,x = dq.popleft()
    for i in opt:
        y1 = y+i[0]
        x1 = x+i[1]
        if m[y1][x1] == "." and temp[y1][x1] == -1:
            temp[y1][x1] = temp[y][x]+1
            dq.append((y1,x1))

cnt = 0
for i in m:
    cnt+=i.count("#")
print((h+2)*(w+2)-cnt-temp[h][w]-1)

Submission status: Wrong Answer

Solution code:
cin = open(0).read().strip().split('\n')
h,w = map(int, cin[0].split(' '))
s = [list(a) for a in cin[1:]]

from collections import deque
q = deque()

dist = [[-1 for _ in range(w)] for _ in range(h)]
dist[0][0]=0

q.append((0,0))
while q:
    ph, pw = q.popleft()
    for dyi, dxi in zip([0,-1,0,1],[1,0,-1,0]):
        if 0<=ph+dyi<h and 0<=pw+dxi<w:
            if dist[ph+dyi][pw+dxi] != -1: continue
            if s[ph+dyi][pw+dxi] == '#': continue
            q.append((ph+dyi, pw+dxi))
            dist[ph+dyi][pw+dxi] = dist[ph][pw]+1

last = dist[h-1][w-1]
print(sum(s, []).count('.')-last-1)