Problem:


Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.



Sample input:
3 3
...
...
...


Sample output:
4

Submission status: Runtime Error

Solution code:
import queue
H, W = map(int, input().split())

move = [[0 for i in range(W)]for i in range(H)]

S = ["#" for i in range(H)]

M = 0

for i in range(H):
    S[i] = input()





def keisoku(sx,sy,ex,ey):
    global W
    global H
    end = False

    qx = queue.Queue()
    qy = queue.Queue()


    count = 1

    kyori = [[-1 for i in range(W)]for i in range(H)]
    kyori[ey][ex] == 0
    if ey < H-1:
        
        if S[ey+1][ex] == ".":
            kyori[ey+1][ex] = 1
            qx.put(ex)
            qy.put(ey+1)
    if ey >= 1:
        if S[ey-1][ex] == ".":
            kyori[ey-1][ex] = 1
            qx.put(ex)
            qy.put(ey-1)
    if ex < W -1:
            
        if S[ey][ex+1] == ".":
            kyori[ey][ex+1] = 1
            qx.put(ex+1)
            qy.put(ey)
    if ex >= 1:
        if S[ey][ex-1] == ".":
            kyori[ey][ex-1] = 
            qx.put(ex-1)
            qy.put(ey)

    while(not end):
        x = qx.get()
        y = qy.get()
        
        if y < H -1:
                
            if S[y+1][x] == ".":
                qx.put(x)
                qy.put(y+1)
                kyori[y+1][x] = kyori[y][x]+1
        if y >= 1:
                
            if S[y-1][x] == ".":
                qx.put(x)
                qy.put(y-1)
                kyori[y-1][x] = kyori[y][x]+1
        if x < W -1:
                
            if S[y][x+1] == ".":
                qx.put(x+1)
                qy.put(y)
                kyori[y][x+1] =  kyori[y][x]+1

        if x >= 1:
                
            if S[y][x-1] == ".":
                qx.put(x-1)
                qy.put(y)
                kyori[y][x-1] = kyori[y][x]+1

        
        if kyori[sy][sx] != -1:
            end = True
    
    return kyori[sy][sx]
                    
for sx in range(W):
    for sy in range(H):
        for ex in range(W):
            for ey in range(H):
                if S[sy][sx] == "#" or S[ey][ex] == "#" or (sx == ex and sy == ey):
                    continue

                newmax = keisoku(sx,sy,ex,ey)
                if newmax > M:
                    M = newmax 

print(M)

Submission status: Runtime Error

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]

ans = 0
for i in range(h):
    for j in range(w):
        q = deque()
        q.append([i, j, 0])
        if s[i][j] == '#': continue

        visited = np.zeros((h + 5, w + 5), dtype = bool)
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        mx = 0
        while len(q) != 0:
            x, y, z = q[0]
            ans = max(ans, z)
            visited[x][y] = True
            for p in range(4):
                nx, ny = x + dirr[p][0], y + dirr[p][1]
                if 0 <= nx < h and 0 <= ny < w:
                    if not visited[nx][ny] and s[nx][ny] == '.':
                        q.append([nx, ny, z + 1])
            q.popleft()
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
H,W = map(int,input().split())
maze = []
dx = [1,0,-1,0]
dy = [0,1,0,-1]
for i in range(H):
    maze.append(list(input()))
def bfs(sx,sy):
    INF = -1
    cost = [[INF]*W for _ in range(H)]
    P = deque()
    P.append([sx,sy])
    cost[sx][sy] = 0
    while len(P) != 0:
        p = P.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < H and 0 <= ny < W and maze[nx][ny] != "#" and cost[nx][ny] == INF:
                P.append([nx,ny])
                cost[nx][ny] = cost[p[0]][p[1]]+1
    return cost
def solve():
    ans = 0
    for i in range(H):
        for j in range(W):
            if maze[i][j] != "#"
                sx,sy = i,j
                cs = bfs(sx,sy)
                for k in range(len(cs)):
                    if max(cs[k]) > ans:
                        ans = max(cs[k])
    return ans
print(solve())

Submission status: Runtime Error

Solution code:
    h, w = list(map(int, input().split()))
     
    s = []
    for i in range(h):
        line = input()
        s.append(line)
     
    ans = []
    for i in range(h):
        for j in range(w):
            if s[i][j] == '#':
                continue
            d = [[1<<10 for x in range(w)] for y in range(h)]
     
            stack = []
            stack.append((i, j))
            d[i][j] = 0
            while stack:
                y, x = stack.pop()
                if y > 0 and s[y-1][x] == '.' and d[y-1][x] > d[y][x]+1:
                    d[y-1][x] = d[y][x] + 1
                    stack.append((y-1, x))
                if x < w-1 and s[y][x+1] == '.' and d[y][x+1] > d[y][x]+1:
                    d[y][x+1] = d[y][x] + 1
                    stack.append((y, x+1))
                if y < h-1 and s[y+1][x] == '.' and d[y+1][x] > d[y][x]+1:
                    d[y+1][x] = d[y][x] + 1
                    stack.append((y+1, x))
                if x > 0 and s[y][x-1] == '.' and d[y][x-1] > d[y][x]+1:
                    d[y][x-1] = d[y][x] + 1
                    stack.append((y, x-1))
            ma = 0
            for y in range(h):
                for x in range(w):
                    if d[y][x] > ma:
                        ma = d[y][x]

            ans.append(ma)
    ans.sort()
    print(ans[-1])

Submission status: Runtime Error

Solution code:
from collections import deque

H, W = map(int, input().split())
maze = []
for _ in range(H):
    maze.append(list(input()))


def successors(x, y):
    locations = []
    # 下に行けるかの判定
    if (x + 1 < H) and (maze[x + 1][y] != '#'):
        locations.append((x + 1, y))
    # 上に行けるかの判定
    if (x - 1 >= 0) and (maze[x - 1][y] != '#'):
        locations.append((x - 1, y))
    # 右に行けるかの判定
    if (y + 1 < W) and (maze[x][y + 1] != '#'):
        locations.append((x, y + 1))
    # 左に行けるかの判定
    if (y - 1 >= 0) and (maze[x][y - 1] != '#'):
        locations.append((x, y - 1))
    return locations


def bfs(initial, goal, successors):
    frontier = deque()
    frontier.append((initial, None))
    # tuple
    explored = {initial}

    while len(frontier):
        current_node = frontier.popleft()
        current_state = current_node[0]
        if current_state == goal:
            return current_node
        for child in successors(*current_state):
            if str(child) in [str(i) for i in explored]:
                continue
            explored.add(child)
            frontier.append((child, current_node))
    return None


def node_to_path_count(node):
    path = [node[0]]
    counter: int = 0
    while node[1] is not None:
        counter += 1
        node = node[1]
        path.append(node[0])
    path.reverse()
    #return path, counter
    return counter


ans = 0
for x in range(H):
    for y in range(W):
        for gx in range(H):
            for gy in range(W):
                if (x != gx and y != gy) and maze[x][y] == '.' and maze[gx][gy] == '.':
                    solution = bfs((x, y), (gx, gy), successors)
                    counter = node_to_path_count(solution)
                    if ans < counter:
                        ans = counter

print(ans)

Submission status: Runtime Error

Solution code:
from typing import List, Any, Union


def clear_maze(sx, sy, maze):

    INF=-10**9
    global cnt
    cnt=0


    distance = [[INF for i in range(w+1)] for j in range(h+1)]
    #    distance = [[None]*field_x_length]*field_y_length



    def bfs():
        global cnt
        queue = []

        queue.insert(0, (sx, sy))

        distance[sx][sy] = 0

        while len(queue):
            x, y = queue.pop()



            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]


                if (0 <= nx and  0 <= ny  and maze[nx][ny] != '#' and distance[nx][ny] == INF):
                    queue.insert(0, (nx, ny))

                    distance[nx][ny] = distance[x][y] + 1
                    if cnt<=distance[nx][ny]:
                        cnt=distance[nx][ny]





        return cnt

    cnt=0
    distance = [[INF for i in range(w + 1)] for j in range(h + 1)]




    return bfs()

h,w = map(int, input().split())
maze=[list(input()) for i in range(h)]
t=[[0]*w for i in range(h)]
for i in range(h):
    maze[i]=['#']+maze[i]+['#']

maze=[['#' for i in range(w+2)]]+maze+[['#' for i in range(w+2)]]




ans=0

for i in range(1,h+1):
    for j in range(1,w+1):
        if maze[i][j]=='#':
            continue
        v=(clear_maze(i, j, maze))

        if ans<=v:
            ans=v
print(ans)

Submission status: Runtime Error

Solution code:
# 2020/01/12

from copy import deepcopy
import sys
from collections import deque

sys.setrecursionlimit(10**7)


def main():
    dr=[(-1,0),(0,-1),(0,1),(1,0)]

    h,w=map(int,input().split())
    g=[list('#')*(w+2)]
    for _ in range(h):
        g+=[['#']+list(input())+['#']]
    g+=[list('#')*(w+2)]


    def bfs(sx,sy,maze):
        res=0
        x,y=sx,sy
        maze[x][y]=0
        que=deque()
        que.append((x,y))

        while que:
            x,y=que.popleft()
            for dx,dy in dr:
                nx=dx+x
                ny=dy+y
                if maze[nx][ny]=='#':continue
                if maze[nx][ny]!='.' and maze[nx][ny]=<maze[x][y]:continue
                maze[nx][ny]=maze[x][y]+1
                que.append((nx,ny))
                res=max(res,maze[nx][ny])
        return res


    ans=0
    maze=deepcopy(g)

    for i in range(1,h+1):
        for j in range(1,w+1):
            if g[i][j]=='#':continue
            res=bfs(i,j,maze)
            ans=max(res,ans)
            maze=deepcopy(g)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import numpy as np
from collections import deque
infinity = -10**5
H,W = map(int,input().split())

A = np.zeros((H+1,W+1))

for i in range(H):
    s = input()
    for j in range(W):
        if s[j] == ".":
            A[i][j] = 1
        else:
            A[i][j] = -1

N = H*W
G=[[] for i in range(N)]

for i in range(H):
    for j in range(W):
        if A[i][j] ==1:
            if A[i+1][j] == 1:
                G[W*(i+1)+j].append(W*i+j)
                G[W*i+j].append(W*(i+1)+j)

            if A[i][j+1] == 1:
                G[W*i+(j+1)].append(W*i+j)
                G[W*i+j].append(W*i+(j+1))

def BFS (s):
    queue = deque()
    d = [infinity]*N
    
    queue.append(s)
    d[s]= 0
    
    while len(queue)!=0:
      u = queue.popleft()
      for v in G[u]:
      	if d[v] == infinity:
        	d[v] = d[u]+1
        	queue.append(v) 	  
  
    return d

ans = 0

for i in range(H):
    for j in range(W):
        if A[i][j] == 1:
            d = BFS(W*i+j)
        ans = max(ans,max(d))
print(ans)

Submission status: Runtime Error

Solution code:
def main():
    import sys
    import numpy as np
    H,W=list(map(int,sys.stdin.readline().split()))
    meiz=[]
    for i in range(H):
        S=sys.stdin.readline().strip()
        meiz.append([0 if s=='.' else 1 for s in S])

    #道→0 壁→1
    
    #meiz=np.array(meiz)
    
    #dp=[[0]*W for _ in range(H)]
    
    #FRTO=np.array(H,W,H,W)

    def dfs(x,y,tx,ty,d):
        if x==tx and y==ty:
            return 0

        if AL[y][x]:
            return 10**6

        AL[y][x]=1
        out=10**6
        if x!=0 and meiz[y][x-1]==0:
            t=dfs(x-1,y,tx,ty,d+1)
            out=t if t<out else out

        if x!=W-1 and meiz[y][x+1]==0 :
            t=dfs(x+1,y,tx,ty,d+1)
            out=t if t<out else out
        if y!=0 and meiz[y-1][x]==0:
            t=dfs(x,y-1,tx,ty,d+1)
            out=t if t<out else out
        if y!=H-1 and meiz[y+1][x]==0 :
            t=dfs(x,y+1,tx,ty,d+1)
            out=t if t<out else out
        
        return out+1

    mx=0
    for y in range(H):
        for x in range(W):
            for ty in range(H):
                for tx in range(W):
                    if meiz[y][x]==1:
                        continue
                    if meiz[ty][tx]==1:
                        continue
                    if y==ty and x==tx:
                        continue
                    if x not in [0,W-1] and meiz[y][x-1]==0 and meiz[y][x+1]==0:
                        continue
                    if y not in [0,H-1] and meiz[y-1][x]==0 and meiz[y+1][x]==0:
                        continue           
                    AL=[[0]*W for _ in range(H)]
                    t=dfs(x,y,tx,ty,0)
                    mx=t if t>mx else mx

    print(mx)

main()

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000000)
from collections import deque

def bfs(sx,sy,gx,gy):
    d = [[float("inf")] * w for i in range(h)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

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

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and d[nx][ny] == float("inf"):
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]

h,w=map(int,input().split())
s = [list(input()) for i in range(h)]
ans=0
def check(i,j):
    if 1<=j<=w-2:
        if s[0][j-1]=='#' or s[0][j+1]=='#' or s[1][j]=='#':
            return True
    elif 1<=j<=w-2:
        if s[h][j-1]=='#' or s[h][j+1]=='#' or s[h-1][j]=='#':
            return True
    elif 1<=i<=h-2:
        if s[i-1][0]=='#' or s[i+1][0]=='#' or s[i][1]=='#':
            return True
    elif 1<=i<=h-2:
        if s[i-1][w]=='#' or s[i+1][w]=='#' or s[i][w-1]=='#':
            return True
    elif 1<=i<=h-2 and 1<=j<=w-2:
        if s[i][j+1]=='#' or s[i][j-1]=='#' or s[i+1][j]=='#' or s[i-1][j]=='#':
            return True
    elif i==0 and j==0:
        return True
    elif i==0 and j==w-1:
        return True
    elif i==h-1 and j==0:
        return True
    elif i==h-1 and j==w-1:
        return True
    else:
        return False
for i in range(h):
    for j in range(w):
        if s[i][j]=='.' and check(i,j):
            if j != w:
                for m in range(j+1,w):
                    if s[i][m]=='.' and check(i,m):
                        ans = max(ans,bfs(i,j,i,m))
            for k in range(i+1,h):
                for l in range(w):
                    if s[k][l]=='.' and check(k,l):
                        ans = max(ans,bfs(i,j,k,l))
print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000000)
from collections import deque

def bfs(sx,sy,gx,gy):
    d = [[float("inf")] * w for i in range(h)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

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

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and d[nx][ny] == float("inf"):
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]

h,w=map(int,input().split())
s = [list(input()) for i in range(h)]
ans=0
def check(i,j):
    if 1<=j<=w-2:
        if s[0][j-1]=='#' or s[0][j+1]=='#' or s[1][j]=='#':
            return True
    elif 1<=j<=w-2:
        if s[h][j-1]=='#' or s[h][j+1]=='#' or s[h-1][j]=='#':
            return True
    elif 1<=i<=h-2:
        if s[i-1][0]=='#' or s[i+1][0]=='#' or s[i][1]=='#':
            return True
    elif 1<=i<=h-2:
        if s[i-1][w]=='#' or s[i+1][w]=='#' or s[i][w-1]=='#':
            return True
    elif 1<=i<=h-2 and 1<=j<=w-2:
        if s[i][j+1]=='#' or s[i][j-1]=='#' or s[i+1][j]=='#' or s[i-1][j]=='#':
            return 0
    elif i==0 and j==0:
        return True
    elif i==0 and j==w-1:
        return True
    elif i==h-1 and j==0:
        return True
    elif i==h-1 and j==w-1:
        return True
    else:
        return False
for i in range(h):
    for j in range(w):
        if s[i][j]=='.' and check(i,j):
            if j != w:
                for m in range(j+1,w):
                    if s[i][m]=='.' and check(i,m):
                        ans = max(ans,bfs(i,j,i,m))
            for k in range(i+1,h):
                for l in range(w):
                    if s[k][l]=='.' and check(k,l):
                        ans = max(ans,bfs(i,j,k,l))
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

H, W = map(int, input().split())
maze = [input() for _ in range(H)]
V = []
E = {}
for i, j in product(range(H), range(W)):
    if maze[i][j] == '#': continue
    V += [(i, j)]
    check = [(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for x, y in check:
        if maze[x][y] == '.':
            E.setdefault((i, j), [])
            E.setdefault((x, y), [])
            E[(i, j)].append((x, y))
            E[(x, y)].append((i, j))

def bfs(s):
    q = deque([(s, 0)])
    dist = {v: -1 for v in V}
    while q:
        v, d = q.popleft()
        if dist[v] >= 0: continue
        dist[v] = d
        for u in E[v]:
            if dist[u] < 0:
                q.append((u, d+1))
    return dist

ans = 0
for v in V:
    dist = bfs(v)
    ans = max(ans, max(dist.values()))
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import copy
import math
import bisect
import pprint
import bisect
from functools import reduce
from copy import deepcopy

glist=[]

def makelist(num):
    if num == max:
        glist.append(list)
    else:
        list1 = copy.deepcopy(list)
        list1[num]=-1
        makelist(max,num+1,list1)
        list2 = copy.deepcopy(list)
        list2[num]=1
        makelist(max,num+1,list2)

def checkcost (h,w):
    if  h-1 > -1:
        if glist[h-1][w] == -1 or glist[h-1][w] > glist[h][w] +1:
            glist[h - 1][w] =glist[h][w] +1
            checkcost(h-1,w)

    if w - 1 > -1:
        if glist[h][w-1] == -1 or glist[h][w-1] > glist[h][w] +1:
            glist[h ][w-1] =glist[h][w] +1
            checkcost(h,w-1)

    if h + 1 < maxh:
        if glist[h+1][w] == -1 or glist[h+1][w] > glist[h][w] +1:
            glist[h + 1][w] =glist[h][w] +1
            checkcost(h+1,w)

    if w + 1 < maxw:
        if glist[h][w+1] == -1 or glist[h][w+1] > glist[h][w] +1:
            glist[h ][w+1] =glist[h][w] +1
            checkcost(h,w+1)

maxh = 0
maxw = 0


def clacmaxxostaddress(maxh,maxw):
    max = -1
    maxh2= -1
    maxj2= -1
    for i in range(maxh):
        for j in range(maxw):
            if max < glist[i][j] :
                max = glist[i][j]
                maxh2=i
                maxj2=j
    return maxh2,maxj2

def clacmaxxost(maxh,maxw):
    max = -1
    maxh2= -1
    maxj2= -1
    for i in range(maxh):
        for j in range(maxw):
            if max < glist[i][j] :
                max = glist[i][j]
                maxh2=i
                maxj2=j
    return max

if __name__ == '__main__':
    a,b  = map(int, input().split())
    maze = []
    maxh = a
    maxw = b
    for i in range(a):
        s = input()
        list = []
        for j in s:
            list.append(j)
        maze.append(list)
    address_h = -1
    address_w = -1
    for i in range(a):
        for j in range(b):
            if maze[i][j] == ".":
                address_h = i
                address_w = j
                break
        if maze[i][j] == ".":
            address_h = i
            address_w = j
            break

    glist=  [[-1] * a for i in range(b)]
    glist[address_h][address_w] = 0
    checkcost(address_h,address_w)
    checkh,checkw=clacmaxxostaddress(a,b)
    glist=  [[-1] * a for i in range(b)]
    glist[checkh][checkw] = 0

    checkcost(checkh,checkw)
    print(clacmaxxost(a,b))

Submission status: Runtime Error

Solution code:
import sys
import copy
import math
import bisect
import pprint
import bisect
from functools import reduce
from copy import deepcopy

glist=[]

def makelist(num):
    if num == max:
        glist.append(list)
    else:
        list1 = copy.deepcopy(list)
        list1[num]=-1
        makelist(max,num+1,list1)
        list2 = copy.deepcopy(list)
        list2[num]=1
        makelist(max,num+1,list2)

def checkcost (h,w):
    if  h-1 > -1:
        if glist[h-1][w] == -1 or glist[h-1][w] > glist[h][w] +1:
            glist[h - 1][w] =glist[h][w] +1
            checkcost(h-1,w)

    if w - 1 > -1:
        if glist[h][w-1] == -1 or glist[h][w-1] > glist[h][w] +1:
            glist[h ][w-1] =glist[h][w] +1
            checkcost(h,w-1)

    if h + 1 < maxh:
        if glist[h+1][w] == -1 or glist[h+1][w] > glist[h][w] +1:
            glist[h + 1][w] =glist[h][w] +1
            checkcost(h+1,w)

    if w + 1 < maxw:
        if glist[h][w+1] == -1 or glist[h][w+1] > glist[h][w] +1:
            glist[h ][w+1] =glist[h][w] +1
            checkcost(h,w+1)

maxh = 0
maxw = 0


def clacmaxxostaddress(maxh,maxw):
    max = -1
    maxh2= -1
    maxj2= -1
    for i in range(maxh):
        for j in range(maxw):
            if max < glist[i][j] :
                max = glist[i][j]
                maxh2=i
                maxj2=j
    return maxh2,maxj2

def clacmaxxost(maxh,maxw):
    max = -1
    maxh2= -1
    maxj2= -1
    for i in range(maxh):
        for j in range(maxw):
            if max < glist[i][j] :
                max = glist[i][j]
                maxh2=i
                maxj2=j
    return max

if __name__ == '__main__':
    a,b  = map(int, input().split())
    maze = []
    maxh = a
    maxw = b
    for i in range(a):
        s = input()
        list = []
        for j in s:
            list.append(j)
        maze.append(list)
    address_h = -1
    address_w = -1
    for i in range(a):
        for j in range(b):
            if maze[i][j] == ".":
                address_h = i
                address_w = j
                break
        if maze[i][j] == ".":
            address_h = i
            address_w = j
            break

    glist=  [[-1] * a for i in range(b)]
    glist[address_h][address_w] = 0
    checkcost(address_h,address_w)
    checkh,checkw=clacmaxxostaddress(a,b)
    glist=  [[-1] * a for i in range(b)]
    glist[address_h][address_w] = 0

    checkcost(checkh,checkw)
    print(clacmaxxost(a,b))

Submission status: Runtime Error

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

wall = "#"
road = "."
mp = [list(input()) for _ in range(H)]
mp = list(zip(*(mp[::-1])))
mp = [list(x) for x in mp]
# print(mp)

def get_mass(x, y):
  # print("get_mass", x, y, 0 < x < W, )
  if 0 <= x < W and 0 <= y < H:
    return mp[x][y]
  else:
    return wall
def set_mass(val, x, y):
  if 0 <= x < W and 0 <= y < H:
    if (mp[x][y] == road) or (type(mp[x][y]) == int and mp[x][y] > val):
      # print("set", val,(x, y))
      mp[x][y] = val

def north(x, y):
  return x, y+1
def east(x, y):
  return x+1, y
def west(x, y):
  return x, y-1
def south(x, y):
  return x-1, y

goals = []
  
def movable(now_pos, go_pos):
  now = get_mass(*now_pos)
  go = get_mass(*go_pos)
  # print("movalbe calc", now_pos, now, go_pos, go)
  if go == road:
    return True
  if type(now) == int and type(go) == int and now < go:
    # 行く先の方が値でかいなら行くべき
    return True
  return False
  
def arrived(cnt, pos):
  # 今posにいて、そこに来るまでにcnt回移動してきた。
  set_mass(cnt, *pos)
  # print("cnt", cnt, "pos", pos)
  
  if (H - 1) == pos[1] and (W - 1) == pos[0]:
	# posがゴールならcnt回をゴール回数集に足す
    # print("goal", pos)
    goals.append(cnt)  
  else:
    # posの東西南北が移動できるなら、cnt+1を渡して再帰させる
    cnt += 1
    if movable(pos, north(*pos)):
      arrived(cnt, north(*pos))
    if movable(pos, east(*pos)):
      arrived(cnt, east(*pos))
    if movable(pos, south(*pos)):
      arrived(cnt, south(*pos))
    if movable(pos, west(*pos)):
      arrived(cnt, west(*pos))

arrived(0, (0,0))
print(min(goals))
# print("goals", goals)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000000)
from collections import deque

def bfs(sx,sy,gx,gy):
    d = [[float("inf")] * w for i in range(h)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

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

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != "#" and d[nx][ny] == float("inf"):
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]

h,w=map(int,input().split())
s = [list(input()) for i in range(h)]
ans=0
def check(i,j):
    if 1<=j<=w-2:
        if s[0][j-1]=='#' or s[0][j+1]=='#' or s[1][j]=='#':
            return True
    elif 1<=j<=w-2:
        if s[h][j-1]=='#' or s[h][j+1]=='#' or s[h-1][j]=='#':
            return True
    elif 1<=i<=h-2:
        if s[i-1][0]=='#' or s[i+1][0]=='#' or s[i][1]=='#':
            return True
    elif 1<=i<=h-2:
        if s[i-1][w]=='#' or s[i+1][w]=='#' or s[i][w-1]=='#':
            return True
    elif i==0 and j==0:
        return True
    elif i==0 and j==w-1:
        return True
    elif i==h-1 and j==0:
        return True
    elif i==h-1 and j==w-1:
        return True
    else:
        return False
for i in range(h):
    for j in range(w):
        if s[i][j]=='.' and check(i,j):
            if j != w:
                for m in range(j+1,w):
                    if s[i][m]=='.' and check(i,m):
                        ans = max(ans,bfs(i,j,i,m))
            for k in range(i+1,h):
                for l in range(w):
                    if s[k][l]=='.' and check(k,l):
                        ans = max(ans,bfs(i,j,k,l))
print(ans)

Submission status: Runtime Error

Solution code:
import sys
import copy
import math
import bisect
import pprint
import bisect
from functools import reduce
from copy import deepcopy

glist=[]

def makelist(num):
    if num == max:
        glist.append(list)
    else:
        list1 = copy.deepcopy(list)
        list1[num]=-1
        makelist(max,num+1,list1)
        list2 = copy.deepcopy(list)
        list2[num]=1
        makelist(max,num+1,list2)

def checkcost (h,w):
    if  h-1 > -1:
        if glist[h-1][w] == -1 or glist[h-1][w] > glist[h][w] +1:
            glist[h - 1][w] =glist[h][w] +1
            checkcost(h-1,w)

    if w - 1 > -1:
        if glist[h][w-1] == -1 or glist[h][w-1] > glist[h][w] +1:
            glist[h ][w-1] =glist[h][w] +1
            checkcost(h,w-1)

    if h + 1 < maxh:
        if glist[h+1][w] == -1 or glist[h+1][w] > glist[h][w] +1:
            glist[h + 1][w] =glist[h][w] +1
            checkcost(h+1,w)

    if w + 1 < maxw:
        if glist[h][w+1] == -1 or glist[h][w+1] > glist[h][w] +1:
            glist[h ][w+1] =glist[h][w] +1
            checkcost(h,w+1)

maxh = 0
maxw = 0


def clacmaxxostaddress(maxh,maxw):
    max = -1
    maxh2= -1
    maxj2= -1
    for i in range(maxh):
        for j in range(maxw):
            if max < glist[i][j] :
                max = glist[i][j]
                maxh2=i
                maxj2=j
    return maxh2,maxj2

def clacmaxxost(maxh,maxw):
    max = -1
    maxh2= -1
    maxj2= -1
    for i in range(maxh):
        for j in range(maxw):
            if max < glist[i][j] :
                max = glist[i][j]
                maxh2=i
                maxj2=j
    return max

if __name__ == '__main__':
    a,b  = map(int, input().split())
    maze = []
    maxh = a
    maxw = b
    for i in range(a):
        s = input()
        list = []
        for j in s:
            list.append(j)
        maze.append(list)
    address_h = -1
    address_w = -1
    for i in range(a):
        for j in range(b):
            if maze[i][j] == ".":
                address_h = i
                address_w = j
                break
        if maze[i][j] == ".":
            address_h = i
            address_w = j
            break

    glist=  [[-1] * a for i in range(b)]
    glist[address_h][address_w] = 0
    checkcost(address_h,address_w)
    maxh,maxj=clacmaxxostaddress(a,b)
    glist=  [[-1] * a for i in range(b)]
    checkcost(maxh,maxj)


    print(clacmaxxost(a,b))

Submission status: Runtime Error

Solution code:

import numpy as np
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))

def is_inner(x,H,W):
    if np.all(0<=x) and np.all(x<(H,W)):
        return True
    else:
        return False
    
directions = np.array([[1, 0], [0, 1], [-1, 0], [0, -1]])
directions = list(map(np.array, directions))

def searchfrom(x):
    global H,W
    dp=[[9999 for j in range(W)]for i in range(H)]
    dp[x[0]][x[1]]=0
    queue=[x]
    while True:
        x=queue.pop()
        for d in directions:
            nx=x+d
            if is_inner(nx,H,W) and dp[nx[0]][nx[1]]>=dp[x[0]][x[1]]+1 and field[nx[0]][nx[1]]!="#":
                dp[nx[0]][nx[1]]=dp[x[0]][x[1]]+1
                queue.append(nx)
        
        if len(queue)==0:
            return dp

def solve_from(x):
    global field
    res = searchfrom(x)

    mv = -1
    for rr in res:
        rr=[r for r in rr if  r<=1000]
        tmp = max(rr)

        if tmp<1000:
            mv = max(mv, tmp)
    return mv






H,W=acinput()

field=[]
for i in range(H):
    field.append(list(input()))



print(max(solve_from([0,0]),solve_from([H-1,0]),solve_from([0,W-1]),solve_from([H-1,W-1])))