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: Time Limit Exceeded

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

white=sum([1 if s[y][x]=='.' else 0 for x in range(W) for y in range(H)])
used=[[False for x in range(W)] for y in range(H)]
q = deque([(0,0,1)])
while True:
    if len(q)==0:
        print(-1)
        break
    x,y,l=q.popleft()
    if x==W-1 and y==H-1:
        print(white-l)
        break
    used[y][x]=True
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx=x+d[0]
        ny=y+d[1]
        if ny>=0 and ny<H and nx>=0 and nx<W and not used[ny][nx]:
            if s[ny][nx]=='.':
                q.append((nx,ny,l+1))

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
H,W=map(int,input().split())
s=[list(input()) for _ in range(H)]

white=sum([1 if s[y][x]=='.' else 0 for x in range(W) for y in range(H)])
used=[[False for x in range(W)] for y in range(H)]
q=Queue()
q.put((0,0,1))
while True:
    if q.empty():
        print(-1)
        break
    x,y,l=q.get()
    if x==W-1 and y==H-1:
        print(white-l)
        break
    used[y][x]=True
    for d in [(1,0),(0,1),(-1,0),(0,-1)]:
        nx=x+d[0]
        ny=y+d[1]
        if ny>=0 and ny<H and nx>=0 and nx<W and not used[ny][nx]:
            if s[ny][nx]=='.':
                q.put((nx,ny,l+1))

Submission status: Time Limit Exceeded

Solution code:
import heapq
import sys

sys.setrecursionlimit(1000)

BLACK = '#'
WHITE = '.'


def m():
    H, W = [int(x) for x in input().split(' ')]
    board = [[c for c in list(input())] for _ in range(H)]

    # x, y, score
    q = [(0, 0, 0)]
    is_reachable = False
    while len(q) > 0:
        p, x, y = heapq.heappop(q)
        board[x][y] = p
        if x == H - 1 and y == W - 1:
            is_reachable = True

        nexts = [(x+1, y), (x, y+1), (x-1, y), (x, y-1)]
        for i, j in nexts:
            if 0 <= i and i < H and 0 <= j and j < W:
                if board[i][j] == BLACK:
                    continue

                if board[i][j] == WHITE:
                    heapq.heappush(q, (p+1, i, j))
                    continue

                if board[i][j] > p+1:
                    heapq.heappush(q, (p+1, i, j))
                    continue

    if is_reachable:
        blacks = 0
        for i in range(H):
            for j in range(W):
                if board[i][j] == BLACK:
                    blacks += 1
        ans = H*W - blacks - board[H-1][W-1] - 1
        print(ans)
    else:
        print(-1)


m()

Submission status: Time Limit Exceeded

Solution code:
import heapq
import sys

sys.setrecursionlimit(1000)

BLACK = '#'
WHITE = '.'


def m():
    H, W = [int(x) for x in input().split(' ')]
    board = [[c for c in list(input())] for _ in range(H)]

    # x, y, score
    q = [(0, 0, 0)]
    is_reachable = False
    while len(q) > 0:
        p, x, y = heapq.heappop(q)
        board[x][y] = p
        if x == H - 1 and y == W - 1:
            is_reachable = True

        nexts = [(x+1, y), (x, y+1), (x-1, y), (x, y-1)]
        for i, j in nexts:
            if 0 <= i and i < H and 0 <= j and j < W:
                if board[i][j] == BLACK:
                    continue

                if board[i][j] == WHITE:
                    heapq.heappush(q, (p+1, i, j))
                    continue

                if board[i][j] > p+1:
                    heapq.heappush(q, (i, j, p+1))
                    continue

    if is_reachable:
        blacks = 0
        for i in range(H):
            for j in range(W):
                if board[i][j] == BLACK:
                    blacks += 1
        ans = H*W - blacks - board[H-1][W-1] - 1
        print(ans)
    else:
        print(-1)


m()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

sys.setrecursionlimit(1000)

BLACK = '#'
WHITE = '.'


def m():
    H, W = [int(x) for x in input().split(' ')]
    board = [[c for c in list(input())] for _ in range(H)]

    # x, y, score
    q = deque([(0, 0, 0)])
    is_reachable = False
    while len(q) > 0:
        x, y, p = q.popleft()
        board[x][y] = p
        if x == H - 1 and y == W - 1:
            is_reachable = True

        nexts = [(x+1, y), (x, y+1), (x-1, y), (x, y-1)]
        for i, j in nexts:
            if 0 <= i and i < H and 0 <= j and j < W:
                if board[i][j] == BLACK:
                    continue
                if board[i][j] == WHITE:
                    q.append((i, j, p+1))
                    continue
                if board[i][j] > p+1:
                    q.append((i, j, p+1))
                    continue

    if is_reachable:
        blacks = 0
        for i in range(H):
            for j in range(W):
                if board[i][j] == BLACK:
                    blacks += 1
        ans = H*W - blacks - board[H-1][W-1] - 1
        print(ans)
    else:
        print(-1)


m()

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
h,w = map(int, input().split(' '))
s = [list(input()) for _ in range(h)]
num_w = 0
for i in range(h):
    num_w += s[i].count("#")
q = Queue()
cnt = 0
q.put((0,0,0))
Z = -1
while not q.empty():
    (x,y,cnt) = q.get()
    s[x][y] = "#"
    if (x,y) == (h-1,w-1):
        Z = cnt
        break
    if x!=h-1 and s[x+1][y]!="#":
        q.put((x+1,y,cnt+1))
    if x!=0 and s[x-1][y]!="#":
        q.put((x-1,y,cnt+1))
    if y!=w-1 and s[x][y+1]!="#":
        q.put((x,y+1,cnt+1))
    if y!=0 and s[x][y-1]!="#":
        q.put((x,y-1,cnt+1))
if Z == -1:
    print(-1)
else:
    print(h*w-Z-1-num_w)

Submission status: Time Limit Exceeded

Solution code:
#一個だけRE、わからねえ
#解答見る
import sys
sys.setrecursionlimit(10000)
h,w=map(int,input().split())

def go_next(I,J):
    global dp,w,h
    if 0<=I<h-1:
        if x[I+1][J]=="." and dp[I+1][J]>dp[I][J]+1:
            dp[I+1][J]=dp[I][J]+1
            go_next(I+1,J)
    if 0<I<=h-1:
        if x[I-1][J]=="." and dp[I-1][J]>dp[I][J]+1:
            dp[I-1][J]=dp[I][J]+1
            go_next(I-1,J)
    if 0<=J<w-1:
        if x[I][J+1]=="." and dp[I][J+1]>dp[I][J]+1:
            dp[I][J+1]=dp[I][J]+1
            go_next(I,J+1)
    if 0<J<=w-1:
        if x[I][J-1]=="." and dp[I][J-1]>dp[I][J]+1:
            dp[I][J-1]=dp[I][J]+1
            go_next(I,J-1)

x=[]
for i in range(h):
    x.append(list(input()))
#print(x)
c=0
for i in range(h):
    for j in range(w):
        if x[i][j]==".":
            c+=1
dp=[[10000000000 for i in range(w)]for j in range(h)]
dp[0][0]=1
go_next(0,0)
if dp[h-1][w-1]==10000000000:
    print(-1)
else:
    print(c-dp[h-1][w-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

cnt=0
for i in range(H):
    temp=list(input())
    cnt+=temp.count(".")
    s.append(temp)

d=[[0,0]]
step=[[-1,0],[0,-1],[1,0],[0,1]]
c={(0,0):1}

while d:
    h0,w0=d.pop(0)
    s[h0][w0]="#"
    for h1,w1 in step:
        h = h0 + h1
        w = w0 + w1
        if h<0 or h>=H or w<0 or w>=W or s[h][w]=="#":
            continue
        if h==H-1 and w==W-1:
            ans = cnt - c[(h0,w0)]-1
            print(ans)
            exit()
        c[(h,w)]=c[(h0,w0)]+1
        d.append([h,w])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

cnt=0
for i in range(H):
    temp=list(input())
    cnt+=temp.count(".")
    s.append(temp)

d=deque([[0,0]])
step=[[-1,0],[0,-1],[1,0],[0,1]]
c={(0,0):1}

while d:
    h0,w0=d.popleft()
    s[h0][w0]="#"
    for h1,w1 in step:
        h = h0 + h1
        w = w0 + w1
        if h<0 or h>=H or w<0 or w>=W or s[h][w]=="#":
            continue
        if h==H-1 and w==W-1:
            ans = cnt - c[(h0,w0)]-1
            print(ans)
            exit()
        c[(h,w)]=c[(h0,w0)]+1
        d.append([h,w])
print(-1)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

cnt=0
for i in range(H):
    temp=list(input())
    cnt+=temp.count("#")
    s.append(temp)

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

while d:
    h0,w0,c=d.popleft()
    s[h0][w0]="#"
    c+=1
    for h1,w1 in step:
        h = h0 + h1
        w = w0 + w1
        if h<0 or h>=H or w<0 or w>=W or s[h][w]=="#":
            continue
        if h==H-1 and w==W-1:
            c+=1
            ans = H * W - cnt - c
            print(ans)
            exit()
        d.append([h,w,c])
print(-1)

Submission status: Time Limit Exceeded

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

maze=[]
m=[]
wn=0
INF = 10**5

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


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

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

while len(queue)>0:

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


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

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    from collections import deque
    #class ctmp():
    #    def __init__(self,ij,dis):
    #        self.ij=ij
    #        self.dis=dis
    H,W=map(int,input().split())
    ls=["#"*(W+2)]#
    for i in range(H):
        ls.append("#"+input()+"#")
    ls.append("#"*(W+2))#
    q=deque([])
    qd=deque([])
    #tmp=ctmp((1,1),0)
    q.append((1,1))
    qd.append(0)
    #df={}
    lf=[[0 for _ in range(W+2)] for _ in range(H+2)]#
    lf[1][1]=0
    while q:
        tmpij=q.popleft()
        tmpd=qd.popleft()
        #df[tmpij]=1
        #lf[tmpij[0]][tmpij[1]]=1
        if tmpij==(H,W):
            break
        lind=[(-1,0),(1,0),(0,-1),(0,1)]#
        for i in range(4):
            #ntmpij=(tmpij[0]+(i<2)*(2*i-1),tmpij[1]+(i>1)*(2*i-5))
            ntmpij=(tmpij[0]+lind[i][0],tmpij[1]+lind[i][1])
            #print(ntmpij)
            #if ntmpij not in df and ls[ntmpij[0]][ntmpij[1]]==".":
            if lf[ntmpij[0]][ntmpij[1]]==0 and ls[ntmpij[0]][ntmpij[1]]==".":
                #c_tmp=ctmp(ntmpij,tmp.dis+1)
                #q.append(c_tmp)
                q.append(ntmpij)
                qd.append(tmpd+1)
                lf[tmpij[0]][tmpij[1]]=1
                #lf[ntmpij[0]][ntmpij[1]]=lf[tmpij[0]][tmpij[1]]+1
    if tmpij==(H,W):
        nw=0
        for i in range(1,H+1):
            #for j in range(1,W+1):
             #   if ls[i][j]==".":
              #      nw+=1
            nw+=ls[i].count(".")
        print(nw-tmpd-1)
        #print(nw-lf[H][W]-1)
    else:
        print(-1)

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    from collections import deque
    #class ctmp():
    #    def __init__(self,ij,dis):
    #        self.ij=ij
    #        self.dis=dis
    H,W=map(int,input().split())
    ls=["#"*(W+2)]#
    for i in range(H):
        ls.append("#"+input()+"#")
    ls.append("#"*(W+2))#
    q=deque([])
    qd=deque([])
    #tmp=ctmp((1,1),0)
    q.append((1,1))
    qd.append(0)
    #df={}
    lf=[[0 for _ in range(W+2)] for _ in range(H+2)]#
    lf[1][1]=0
    while q:
        tmpij=q.popleft()
        tmpd=qd.popleft()
        #df[tmpij]=1
        lf[tmpij[0]][tmpij[1]]=1
        if tmpij==(H,W):
            break
        lind=[(-1,0),(1,0),(0,-1),(0,1)]#
        for i in range(4):
            #ntmpij=(tmpij[0]+(i<2)*(2*i-1),tmpij[1]+(i>1)*(2*i-5))
            ntmpij=(tmpij[0]+lind[i][0],tmpij[1]+lind[i][1])
            #print(ntmpij)
            #if ntmpij not in df and ls[ntmpij[0]][ntmpij[1]]==".":
            if lf[ntmpij[0]][ntmpij[1]]==0 and ls[ntmpij[0]][ntmpij[1]]==".":
                #c_tmp=ctmp(ntmpij,tmp.dis+1)
                #q.append(c_tmp)
                q.append(ntmpij)
                qd.append(tmpd+1)
                #lf[ntmpij[0]][ntmpij[1]]=lf[tmpij[0]][tmpij[1]]+1
    if tmpij==(H,W):
        nw=0
        for i in range(1,H+1):
            #for j in range(1,W+1):
             #   if ls[i][j]==".":
              #      nw+=1
            nw+=ls[i].count(".")
        print(nw-tmpd-1)
        #print(nw-lf[H][W]-1)
    else:
        print(-1)

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    input=sys.stdin.readline
    from collections import deque
    #class ctmp():
    #    def __init__(self,ij,dis):
    #        self.ij=ij
    #        self.dis=dis
    H,W=map(int,input().split())
    ls=["#"*(W+2)]
    for i in range(H):
        ls.append("#"+input()+"#")
    ls.append("#"*(W+2))
    q=deque([])
    qd=deque([])
    #tmp=ctmp((1,1),0)
    q.append((1,1))
    qd.append(0)
    df={}
    while q:
        tmpij=q.popleft()
        tmpd=qd.popleft()
        df[tmpij]=1
        if tmpij==(H,W):
            break
        for i in range(4):
            ntmpij=(tmpij[0]+(i<2)*(2*i-1),tmpij[1]+(i>1)*(2*i-5))
            #print(ntmpij)
            if ntmpij not in df and ls[ntmpij[0]][ntmpij[1]]==".":
                #c_tmp=ctmp(ntmpij,tmp.dis+1)
                #q.append(c_tmp)
                q.append(ntmpij)
                qd.append(tmpd+1)
    if tmpij==(H,W):
        nw=0
        for i in range(1,H+1):
            #for j in range(1,W+1):
             #   if ls[i][j]==".":
              #      nw+=1
            nw+=ls[i].count(".")
        print(nw-tmpd-1)
    else:
        print(-1)

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
#class ctmp():
#    def __init__(self,ij,dis):
#        self.ij=ij
#        self.dis=dis
H,W=map(int,input().split())
ls=["#"*(W+2)]
for i in range(H):
    ls.append("#"+input()+"#")
ls.append("#"*(W+2))
q=deque([])
qd=deque([])
#tmp=ctmp((1,1),0)
q.append((1,1))
qd.append(0)
df={}
while q:
    tmpij=q.popleft()
    tmpd=qd.popleft()
    df[tmpij]=1
    if tmpij==(H,W):
        break
    for i in range(4):
        ntmpij=(tmpij[0]+(i<2)*(2*i-1),tmpij[1]+(i>1)*(2*i-5))
        #print(ntmpij)
        if ntmpij not in df and ls[ntmpij[0]][ntmpij[1]]==".":
            #c_tmp=ctmp(ntmpij,tmp.dis+1)
            #q.append(c_tmp)
            q.append(ntmpij)
            qd.append(tmpd+1)
if tmpij==(H,W):
    nw=0
    for i in range(1,H+1):
        #for j in range(1,W+1):
         #   if ls[i][j]==".":
          #      nw+=1
        nw+=ls[i].count(".")
    print(nw-tmpd-1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
class ctmp():
    def __init__(self,ij,dis):
        self.ij=ij
        self.dis=dis
H,W=map(int,input().split())
ls=["#"*(W+2)]
for i in range(H):
    ls.append("#"+input()+"#")
ls.append("#"*(W+2))
q=deque([])
tmp=ctmp((1,1),0)
q.append(tmp)
df={}
while q:
    tmp=q.popleft()
    df[tmp.ij]=1
    if tmp.ij==(H,W):
        break
    for i in range(4):
        ntmpij=(tmp.ij[0]+(i<2)*(2*i-1),tmp.ij[1]+(i>1)*(2*i-5))
        #print(ntmpij)
        if ntmpij not in df and ls[ntmpij[0]][ntmpij[1]]==".":
            c_tmp=ctmp(ntmpij,tmp.dis+1)
            q.append(c_tmp)

if tmp.ij==(H,W):
    nw=0
    for i in range(1,H+1):
        #for j in range(1,W+1):
         #   if ls[i][j]==".":
          #      nw+=1
        nw+=ls[i].count(".")
    print(nw-tmp.dis-1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
class ctmp():
    def __init__(self,ij,dis):
        self.ij=ij
        self.dis=dis
H,W=map(int,input().split())
ls=["#"*(W+2)]
for i in range(H):
    ls.append("#"+input()+"#")
ls.append("#"*(W+2))
q=deque([])
tmp=ctmp((1,1),0)
q.append(tmp)
df={}
while q:
    tmp=q.popleft()
    df[tmp.ij]=1
    if tmp.ij==(H,W):
        break
    if (tmp.ij[0]-1,tmp.ij[1]) not in df and ls[tmp.ij[0]-1][tmp.ij[1]]==".":
        c_tmp=ctmp((tmp.ij[0]-1,tmp.ij[1]),tmp.dis+1)
        q.append(c_tmp)
    if (tmp.ij[0]+1,tmp.ij[1]) not in df and ls[tmp.ij[0]+1][tmp.ij[1]]==".":
        c_tmp=ctmp((tmp.ij[0]+1,tmp.ij[1]),tmp.dis+1)
        q.append(c_tmp)
    if (tmp.ij[0],tmp.ij[1]-1) not in df and ls[tmp.ij[0]][tmp.ij[1]-1]==".":
        c_tmp=ctmp((tmp.ij[0],tmp.ij[1]-1),tmp.dis+1)
        q.append(c_tmp)
    if (tmp.ij[0],tmp.ij[1]+1) not in df and ls[tmp.ij[0]][tmp.ij[1]+1]==".":
        c_tmp=ctmp((tmp.ij[0],tmp.ij[1]+1),tmp.dis+1)
        q.append(c_tmp)
if tmp.ij==(H,W):
    nw=0
    for i in range(1,H+1):
        #for j in range(1,W+1):
         #   if ls[i][j]==".":
          #      nw+=1
        nw+=ls[i].count(".")
    print(nw-tmp.dis-1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
class ctmp():
    def __init__(self,ij,dis):
        self.ij=ij
        self.dis=dis
H,W=map(int,input().split())
ls=["#"*(W+2)]
for i in range(H):
    ls.append("#"+input()+"#")
ls.append("#"*(W+2))
q=deque([])
tmp=ctmp((1,1),0)
q.append(tmp)
df={}
while q:
    tmp=q.popleft()
    df[tmp.ij]=1
    if tmp.ij==(H,W):
        break
    if (tmp.ij[0]-1,tmp.ij[1]) not in df and ls[tmp.ij[0]-1][tmp.ij[1]]==".":
        c_tmp=ctmp((tmp.ij[0]-1,tmp.ij[1]),tmp.dis+1)
        q.append(c_tmp)
    if (tmp.ij[0]+1,tmp.ij[1]) not in df and ls[tmp.ij[0]+1][tmp.ij[1]]==".":
        c_tmp=ctmp((tmp.ij[0]+1,tmp.ij[1]),tmp.dis+1)
        q.append(c_tmp)
    if (tmp.ij[0],tmp.ij[1]-1) not in df and ls[tmp.ij[0]][tmp.ij[1]-1]==".":
        c_tmp=ctmp((tmp.ij[0],tmp.ij[1]-1),tmp.dis+1)
        q.append(c_tmp)
    if (tmp.ij[0],tmp.ij[1]+1) not in df and ls[tmp.ij[0]][tmp.ij[1]+1]==".":
        c_tmp=ctmp((tmp.ij[0],tmp.ij[1]+1),tmp.dis+1)
        q.append(c_tmp)
if tmp.ij==(H,W):
    nw=0
    for i in range(1,H+1):
        for j in range(1,W+1):
            if ls[i][j]==".":
                nw+=1
    print(nw-tmp.dis-1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
#なんかどうやらBFSにおいて自分含め誰かが訪れた点は行かなくてよい
from collections import deque
class ctmp():
    #def __init__(self,ij,df_ij,df_c,dis):
    #def __init__(self,ij,pij,df_ij,df_c,dis):
    def __init__(self,ij,dis):
        self.ij=ij
        #self.pij=pij
        #self.lf=lf
        #self.df_ij=df_ij
        #self.df_c=df_c#これ要らなくね？
        self.dis=dis
H,W=map(int,input().split())
#ls=[["#"]*(W+2)]
#ls=[["#"*(W+2)]]
ls=["#"*(W+2)]
for i in range(H):
    #ls.append(["#"]+list(map(int,input().split()))+["#"])
    #ls.append(["#"]+input().split()+["#"])
    #s=input()
    #ls.append(["#"+input()+"#"])
    ls.append("#"+input()+"#")
#ls.append(["#"]*(W+2))
ls.append("#"*(W+2))
#print("ls",ls)
#print(ls[0])
#print(ls[0][0])
q=deque([])
#tmp=(1,1)
#tmp=ctmp((1,1),{(1,1):1},0)
#tmp=ctmp((1,1),{},{},0)
#tmp=ctmp((1,1),(0,0),{},{},0)
tmp=ctmp((1,1),0)
q.append(tmp)
#lf=[]
#for i in range(H):
#dng={}
df={}
#while tmp.ij!=(H,W) and q:
while q:
    #f=0#行き止まり判定
    #if tmpls[tmp[0]-1,tmp[1]]="."
    #print(q)
    tmp=q.popleft()
    df[tmp.ij]=1
    #print(tmp.ij)
    if tmp.ij==(H,W):
        break
    #ind=bisect_left(tmp.lf,(tmp.ij[0]-1,tmp.ij[1]))
    #if lf[ind]!=lf[ind+1] and ls[tmp.ij[0]][tmp.ij[1]]=".":
    #    qin=tmp((tmp.ij[0]-1,tmp.ij[1]),tmp.lf)
    #    q.append()
    #if (tmp.ij[0]-1,tmp.ij[1]) not in tmp.df_ij and ls[tmp.ij[0]-1][tmp.ij[1]]=="." and (tmp.ij[0]-1,tmp.ij[1]) not in dng:
    if (tmp.ij[0]-1,tmp.ij[1]) not in df and ls[tmp.ij[0]-1][tmp.ij[1]]==".":
        #c_df_ij=copy.copy(tmp.df_ij)
        #c_df_ij[(tmp.ij[0],tmp.ij[1])]=1
        #c_df_c=copy.copy(tmp.df_c)
        #c_df_c[tmp]=1
        c_tmp=ctmp((tmp.ij[0]-1,tmp.ij[1]),tmp.dis+1)
        q.append(c_tmp)
        #f=1
        #print(1)
    if (tmp.ij[0]+1,tmp.ij[1]) not in df and ls[tmp.ij[0]+1][tmp.ij[1]]==".":
        #c_df_ij=copy.copy(tmp.df_ij)
        #c_df_ij[(tmp.ij[0],tmp.ij[1])]=1
        #c_df_c=copy.copy(tmp.df_c)
        #c_df_c[tmp]=1
        c_tmp=ctmp((tmp.ij[0]+1,tmp.ij[1]),tmp.dis+1)
        q.append(c_tmp)
        #f=1
        #print(2)
    if (tmp.ij[0],tmp.ij[1]-1) not in df and ls[tmp.ij[0]][tmp.ij[1]-1]==".":
        #c_df_ij=copy.copy(tmp.df_ij)
        #c_df_ij[(tmp.ij[0],tmp.ij[1])]=1
        #c_df_c=copy.copy(tmp.df_c)
        #c_df_c[tmp]=1
        c_tmp=ctmp((tmp.ij[0],tmp.ij[1]-1),tmp.dis+1)
        q.append(c_tmp)
        #f=1
        #print(3)
    #print((tmp.ij[0],tmp.ij[1]+1) not in tmp.df_ij)
    #print(tmp.ij[0],tmp.ij[1]+1,ls[tmp.ij[0]][tmp.ij[1]+1]==".")
    if (tmp.ij[0],tmp.ij[1]+1) not in df and ls[tmp.ij[0]][tmp.ij[1]+1]==".":
        #c_df_ij=copy.copy(tmp.df_ij)
        #c_df_ij[(tmp.ij[0],tmp.ij[1])]=1
        #c_df_c=copy.copy(tmp.df_c)
        #c_df_c[tmp]=1
        c_tmp=ctmp((tmp.ij[0],tmp.ij[1]+1),tmp.dis+1)
        q.append(c_tmp)
        #f=1
        #print(4)
    #if f==0:
    #    dng[tmp.ij]=1
if tmp.ij==(H,W):
    nw=0
    for i in range(1,H+1):
        for j in range(1,W+1):
            if ls[i][j]==".":
                nw+=1
    print(nw-tmp.dis-1)
else:
    print(-1)

Submission status: Time Limit Exceeded

Solution code:
import heapq

H, W = map(int, input().split())
board = []
goal_dst = [[float("inf") for _ in range(W)] for _ in range(H)]
no = 0

for _ in range(H):
	board.append(list(map(str, input())))
	no += board[-1].count("#")
	
# bfsで最短路を求める
Q = [[1, 0, 0]]
juuji = [[-1, 0], [1, 0], [0, -1], [0, 1]]

while Q:
	cur = heapq.heappop(Q)
	dist = cur[0]
	if goal_dst[cur[1]][cur[2]] < dist or goal_dst[-1][-1] < dist: continue
	goal_dst[cur[1]][cur[2]] = dist
	for move in juuji:
		new_y = cur[1] + move[0]
		new_x = cur[2] + move[1]
		if not (0 <= new_x and new_x <= W - 1 and 0 <= new_y and new_y <= H - 1): continue 
		if board[new_y][new_x] == ".":
			heapq.heappush(Q, [dist + 1, new_y, new_x])
			
if goal_dst[-1][-1] == float("inf"):
	print(-1)
else:
	print(H * W - goal_dst[-1][-1] - no)

Submission status: Time Limit Exceeded

Solution code:
import heapq

H, W = map(int, input().split())
board = []
visited = [[False for _ in range(W)] for _ in range(H)]
goal_dst = [[float("inf") for _ in range(W)] for _ in range(H)]
no = 0

for _ in range(H):
	board.append(list(map(str, input())))
	no += board[-1].count("#")
	
# bfsで最短路を求める
Q = [[1, 0, 0]]
juuji = [[-1, 0], [1, 0], [0, -1], [0, 1]]

while Q:
	cur = heapq.heappop(Q)
	visited[cur[1]][cur[2]] = True
	dist = cur[0]
	if goal_dst[cur[1]][cur[2]] < dist or goal_dst[-1][-1] < dist: continue
	goal_dst[cur[1]][cur[2]] = dist
	for move in juuji:
		new_y = cur[1] + move[0]
		new_x = cur[2] + move[1]
		if not (0 <= new_x and new_x <= W - 1 and 0 <= new_y and new_y <= H - 1): continue 
		if board[new_y][new_x] == "." and visited[new_y][new_x] == False:
			heapq.heappush(Q, [dist + 1, new_y, new_x])
			
if goal_dst[-1][-1] == float("inf"):
	print(-1)
else:
	print(H * W - goal_dst[-1][-1] - no)

Submission status: Time Limit Exceeded

Solution code:
import heapq

H, W = map(int, input().split())
board = []
visited = [[False for _ in range(W)] for _ in range(H)]
goal_dst = [[float("inf") for _ in range(W)] for _ in range(H)]
no = 0

for _ in range(H):
	board.append(list(map(str, input())))
	no += board[-1].count("#")
	
# bfsで最短路を求める
Q = [[0, 0, 1]]
juuji = [[-1, 0], [1, 0], [0, -1], [0, 1]]

while Q:
	cur = heapq.heappop(Q)
	visited[cur[0]][cur[1]] = True
	dist = cur[2]
	if goal_dst[cur[0]][cur[1]] < dist or goal_dst[-1][-1] < dist: continue
	goal_dst[cur[0]][cur[1]] = dist
	for move in juuji:
		new_y = cur[0] + move[0]
		new_x = cur[1] + move[1]
		if not (0 <= new_x and new_x <= W - 1 and 0 <= new_y and new_y <= H - 1): continue 
		if board[new_y][new_x] == "." and visited[new_y][new_x] == False:
			heapq.heappush(Q, [new_y, new_x, dist + 1])
			
if goal_dst[-1][-1] == float("inf"):
	print(-1)
else:
	print(H * W - goal_dst[-1][-1] - no)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
board = []
visited = [[False for _ in range(W)] for _ in range(H)]
goal_dst = [[float("inf") for _ in range(W)] for _ in range(H)]
no = 0

for _ in range(H):
	board.append(list(map(str, input())))
	no += board[-1].count("#")
	
# bfsで最短路を求める
Q = [[0, 0, 1]]
juuji = [[-1, 0], [1, 0], [0, -1], [0, 1]]

while Q:
	cur = Q.pop(0)
	visited[cur[0]][cur[1]] = True
	dist = cur[2]
	if goal_dst[cur[0]][cur[1]] < dist: continue
	goal_dst[cur[0]][cur[1]] = dist
	for move in juuji:
		new_y = cur[0] + move[0]
		new_x = cur[1] + move[1]
		if not (0 <= new_x and new_x <= W - 1 and 0 <= new_y and new_y <= H - 1): continue 
		if board[new_y][new_x] == "." and visited[new_y][new_x] == False:
			Q.append([new_y, new_x, dist + 1])
			
if goal_dst[-1][-1] == float("inf"):
	print(-1)
else:
	print(H * W - goal_dst[-1][-1] - no)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
board = []
visited = [[False for _ in range(W)] for _ in range(H)]
goal_dst = float("inf")
no = 0

for _ in range(H):
	board.append(list(map(str, input())))
	no += board[-1].count("#")
	
# bfsで最短路を求める
Q = [[0, 0, 1]]
juuji = [[-1, 0], [1, 0], [0, -1], [0, 1]]

while Q:
	cur = Q.pop(0)
	visited[cur[0]][cur[1]] = True
	dist = cur[2]
	if cur[0] == H - 1 and cur[1] == W - 1:
		goal_dst = min(goal_dst, dist)
	if goal_dst < dist: continue
	for move in juuji:
		new_y = cur[0] + move[0]
		new_x = cur[1] + move[1]
		if not (0 <= new_x and new_x <= W - 1 and 0 <= new_y and new_y <= H - 1): continue 
		if board[new_y][new_x] == "." and visited[new_y][new_x] == False:
			Q.append([new_y, new_x, dist + 1])
			
if goal_dst == float("inf"):
	print(-1)
else:
	print(H * W - goal_dst - no)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8 
# Your code here! 
H,W=map(int,input().split()) 
S=[] 

ku=0
for _ in range(H): 
    S.append(list(input()))
    ku+=S[-1].count(".")


def bfs(h,w,num):
    if h==H-1 and w==W-1:
        print(ku-num-1)
        exit() 
    else:
        S[h][w]="#"

    if h!=0: 
        if S[h-1][w]!="#": 
            temp.append([h-1,w]) 

    if w!=0: 
        if S[h][w-1]!="#": 
            temp.append([h,w-1]) 

    if h!=H-1: 
        if S[h+1][w]!="#": 
            temp.append([h+1,w]) 

    if w!=W-1: 
        if S[h][w+1]!="#": 
            temp.append([h,w+1]) 
        
q=[[0,0]] 
count=-1
while True: 
    count+=1
    temp=[]
    while q:
        l=q.pop(0)
        bfs(l[0],l[1],count)
        
    q=temp[:]
    if len(q)==0:
        print(-1)
        exit()

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8 
# Your code here! 
H,W=map(int,input().split()) 
S=[] 

ku=0
for _ in range(H): 
    S.append(list(input()))
    ku+=S[-1].count(".")


def bfs(h,w,num):
    if h==H-1 and w==W-1:
        print(ku-num-1)
        exit() 
    else:
        S[h][w]="#"

    if h!=0: 
        if S[h-1][w]!="#": 
            temp.append([h-1,w]) 

    if w!=0: 
        if S[h][w-1]!="#": 
            temp.append([h,w-1]) 

    if h!=H-1: 
        if S[h+1][w]!="#": 
            temp.append([h+1,w]) 

    if w!=W-1: 
        if S[h][w+1]!="#": 
            temp.append([h,w+1]) 
        
q=[[0,0]] 
count=-1
while True: 
    count+=1
    temp=[]
    while q:
        l=q.pop(0)
        bfs(l[0],l[1],count)
        
    q=temp[:]

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
S = ['#'*(W+2)]
white_num = 0
for _ in range(H):
    s = input()
    white_num += s.count('.')
    S.append('#'+s+'#')
S.append('#'*(W+2))

C = [[-1]*(W+2) for _ in range(H+2)]
q = deque()
q.append((1, 1, 0))
xlist = [0, 0, 1, -1]
ylist = [1, -1, 0, 0]
while len(q) > 0:
    x, y, c = q.popleft()
    C[x][y] = c + 1
    for i in range(4):
        mx = x + xlist[i]
        my = y + ylist[i]
        if S[mx][my] == '#' or C[mx][my] >= 0:
            continue
        q.append((mx, my, c+1))
if C[H][W] == -1:
    print(-1)
else:
    print(white_num - C[H][W])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
S = []
white_num = 0
for _ in range(H):
    s = input()
    white_num += s.count('.')
    S.append(s)

C = [[-1]*W for _ in range(H)]
C[0][0] = 0
q = deque()
q.append((0, 0, 0))
xlist = [0, 0, 1, -1]
ylist = [1, -1, 0, 0]
while len(q) > 0:
    x, y, c = q.popleft()
    C[x][y] = c + 1
    for i in range(4):
        mx = x + xlist[i]
        my = y + ylist[i]
        if mx < 0 or my < 0 or mx >= H or my >= W or S[mx][my] == '#' or C[mx][my] >= 0:
            continue
        q.append((mx, my, c+1))
if C[H-1][W-1] == -1:
    print(-1)
else:
    print(white_num - C[H-1][W-1])