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

Solution code:
from collections import deque
H, W = map(int, input().split())
field = [['#'] * (W + 2)]
for i in range(H):
    field.append(list('#' + input() + '#'))
field.append(['#'] * (W + 2))

def num_to_coo(p):
    h, w = divmod(p, W)
    h += 1
    w += 1
    return h, w

def bfs(s):
    cost = [-1] * (H * W)
    q = deque()
    q.append((s, 0))
    while q:
        p, c = q.popleft()
        cost[p] = c
        h, w = num_to_coo(p)
        if (field[h - 1][w] == '.') and p - W >= 0 and (cost[p - W] == -1):
            q.append((p - W, c + 1))
        if (field[h + 1][w] == '.') and p + W < H * W and (cost[p + W] == -1):
            q.append((p + W, c + 1))
        if (field[h][w - 1] == '.') and p - 1 >= 0 and (cost[p - 1] == -1):
            q.append((p - 1, c + 1))
        if (field[h][w + 1] == '.') and p + 1 < H * W and (cost[p + 1] == -1):
            q.append((p + 1, c + 1))
    return c

ans = -1
for s in range(H * W):
    h, w = num_to_coo(s)
    if field[h][w] == '.':
        ans = max(ans, bfs(s))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
#s = np.array(s)
#s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == '#':
        return 0
    else:
        pre = 0
        p = np.full((h, w), -1)
        check = deque([((i, j), 0)])#(from,now, dist)
        while check:
            now, d = check.popleft()
            p[now[0]][now[1]] = d
            pre = max(pre, d)
            for b, c in neext((now[0], now[1])):
                if b < 0 or c < 0 or b >= h or c >= w:
                    continue 
                if p[b][c] != -1 or s[b][c] == '#':
                    continue
                else:
                    check.append(((b, c), d + 1))
        return pre
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
#s = np.array(s)
#s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == '#':
        return 0
    else:
        pre = 0
        p = [[-1] * w for _ in range(h)]
        check = deque([((i, j), 0)])#(from,now, dist)
        while check:
            now, d = check.popleft()
            p[now[0]][now[1]] = d
            pre = max(pre, d)
            for b, c in neext((now[0], now[1])):
                if b < 0 or c < 0 or b >= h or c >= w:
                    continue 
                if p[b][c] != -1 or s[b][c] == '#':
                    continue
                else:
                    check.append(((b, c), d + 1))
        return pre
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
#s = np.array(s)
#s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == '#':
        return 0
    else:
        pre = 0
        p = [[-1] * w for _ in range(h)]
        check = deque([((i, j), 0)])#(from,now, dist)
        while check:
            now, d = check.popleft()
            p[now[0]][now[1]] = d
            pre = max(pre, d)
            for b, c in neext((now[0], now[1])):
                if b < 0 or c < 0 or b >= h or c >= w:
                    continue 
                if p[b][c] != -1 or s[b][c] == '#':
                    continue
                else:
                    check.append(((b, c), d + 1))
        return pre
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
s = np.array(s)
s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == 0:
        return 0
    else:
        pre = 0
        p = np.full_like(s, -1)
        check = deque([((i, j), 0)])#(from,now, dist)
        while check:
            now, d = check.popleft()
            p[now[0]][now[1]] = d
            pre = max(pre, d)
            for b, c in neext((now[0], now[1])):
                if b < 0 or c < 0 or b >= h or c >= w:
                    continue 
                if p[b][c] != -1 or s[b][c] == 0:
                    continue
                else:
                    check.append(((b, c), d + 1))
        return pre
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
s = np.array(s)
s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == 0:
        return 0
    else:
        pre = 0
        p = np.full_like(s, -1)
        check = deque([((-1, -1), (i, j), 0)])#(from,now, dist)
        while check:
            From, now, d = check.popleft()
            p[now[0]][now[1]] = d
            pre = max(pre, d)
            for b, c in neext((now[0], now[1])):
                if b < 0 or c < 0 or b >= h or c >= w:
                    continue 
                if (b == From[0] and c == From[1]) or p[b][c] != -1 or s[b][c] == 0:
                    continue
                else:
                    check.append(((i, j), (b, c), d + 1))
        return pre
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

h, w = map(int, input().split())
s = [['#'] * (w + 2)] + [list('#' + input() + '#') for _ in range(h)] + [['#'] * (w + 2)]
s = np.array(s)
s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == 0:
        return 0
    else:
        pre = 0
        p = np.full_like(s, -1)
        check = [((-1, -1), (i, j), 0)]#(from,now, dist)
        while check:
            From, now, d = check.pop(0)
            p[now[0]][now[1]] = d
            pre = max(pre, d)
            for b, c in neext((now[0], now[1])):

                if (b == From[0] and c == From[1]) or p[b][c] != -1 or s[b][c] == 0:
                    continue
                else:
                    check.append(((i, j), (b, c), d + 1))
        return pre
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

h, w = map(int, input().split())
s = [['#'] * (w + 2)] + [list('#' + input() + '#') for _ in range(h)] + [['#'] * (w + 2)]
s = np.array(s)
s = (s == ".") * 1
def neext(a):
    l, m = a[0], a[1]
    return [(l, m+1), (l, m-1), (l+1, m), (l-1, m)]
def solve(i, j):
    if s[i][j] == 0:
        return 0
    else:
        p = np.full_like(s, -1)
        check = [((-1, -1), (i, j), 0)]#(from,now, dist)
        while check:
            From, now, d = check.pop(0)
            p[now[0]][now[1]] = d
            for b, c in neext((now[0], now[1])):

                if (b == From[0] and c == From[1]) or p[b][c] != -1 or s[b][c] == 0:
                    continue
                else:
                    check.append(((i, j), (b, c), d + 1))
        return np.max(p)
ans = 0
for H in range(len(s)):
    for W in range(len(s[0])):
        ans = max(ans, solve(H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import numpy as np
H,W = map(int,input().split())
Maze=[list(input()) for i in range(H)]
for hi in range(0,H):
    for wi in range(0,W):
        if Maze[hi][wi]=="#":
            continue
        maze1=[[0]*W for _ in range(H)]
        stack=deque([[hi,wi]])
        while stack:
            h,w=stack.popleft()
            for i,j in [[1,0],[-1,0],[0,1],[0,-1]]:
                new_h,new_w=h+i,w+j
                if new_h <0 or new_w <0 or new_h >=H or new_w >=W:
                    continue
                elif Maze[new_h][new_w]!="#" and maze1[new_h][new_w]==0:
                    maze1[new_h][new_w]+=maze1[h][w]
                    stack.append([new_h,new_w])
        
        maze1[hi][wi]=0
        ans=max(ans,np.max(maze1))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
S = []
for _ in range(H):
    S.append(input())

import queue, itertools

dxy = ((1,0), (-1,0), (0,1), (0,-1))
ans = 0
for s in itertools.product(range(H), range(W)):
    if S[s[0]][s[1]] == '#': continue
    
    q = queue.Queue()
    seen = [[0]*W for _ in range(H)]
    dist = [[0]*W for _ in range(H)]     

    q.put(s)
    while not q.empty():
        v = q.get()
        x, y = v[1], v[0]
        seen[y][x] = 1
        for dx, dy in dxy:
            nx, ny = x+dx, y+dy
            if nx<0 or ny<0 or nx>=W or ny>=H or S[ny][nx] == '#' or seen[ny][nx] == 1: continue
            dist[ny][nx] = dist[y][x] + 1
            q.put((ny, nx))
    
    ans = max(ans, max(map(max, dist)))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
S = []
for _ in range(H):
    S.append(input())

import queue, itertools

dxy = ((1,0), (-1,0), (0,1), (0,-1))
ans = 0
for s, t in itertools.combinations(itertools.product(range(H), range(W)), 2):
    if S[s[0]][s[1]] == '#' or S[t[0]][t[1]] == '#': continue
    
    q = queue.Queue()
    seen = [[0]*W for _ in range(H)]
    dist = [[0]*W for _ in range(H)]     

    q.put(s)
    while not q.empty():
        v = q.get()
        x, y = v[1], v[0]
        seen[y][x] = 1
        for dx, dy in dxy:
            nx, ny = x+dx, y+dy
            if nx<0 or ny<0 or nx>=W or ny>=H or S[ny][nx] == '#' or seen[ny][nx] == 1: continue
            dist[ny][nx] = dist[y][x] + 1
            q.put((ny, nx))
    
    ans = max(ans, dist[t[0]][t[1]])

print(ans)

Submission status: Time Limit Exceeded

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

for i in range(H):
    for j in range(W):
        c=0
        sy=i
        sx=j
        A[i][j]=1
        route=deque([(sy,sx,0)])
        while route:
            a,b,n=route.popleft()
            c=n
            if 0<=a<=H-1 and 0<=b<=W-1:
                if S[a][b]=='.':
                    S[a][b]=='#'
                    route.append((a+1,b,n+1))
                    route.append((a-1,b,n+1))
                    route.append((a,b+1,n+1))
                    route.append((a,b-1,n+1))
        ans.append(c)

print(max(ans))

Submission status: Time Limit Exceeded

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

for i in range(H):
    for j in range(W):
        sy=i
        sx=j
        if S[i][j]=='#':
            continue
        A[i][j]=1
        route=deque([(sy,sx,0)])
        while route:
            B=[]
            a,b,n=route.popleft()
            if 0<=a<=H-1 and 0<=b<=W-1:
                if S[a][b]=='.':
                    S[a][b]=='#'
                    B.append(n)
                    route.append((a+1,b,n+1))
                    route.append((a-1,b,n+1))
                    route.append((a,b+1,n+1))
                    route.append((a,b-1,n+1))
        ans.append(max(B))

print(max(ans))

Submission status: Time Limit Exceeded

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

for i in range(H):
    for j in range(W):
        sy=i
        sx=j
        if S[i][j]=='#':
            continue
        A[i][j]=1
        for k in range(H):
            for l in range(W):
                ey=k
                ex=l
                if S[k][l]=='#':
                    continue
                if A[ey][ex]==1:
                    continue
                route=deque([(sy,sx,0)])
                while route:
                    a,b,n=route.popleft()
                    if a==ey and b==ex:
                        ans.append(n)
                        break
                    if 0<=a<=H-1 and 0<=b<=W-1:
                        if S[a][b]=='.':
                            S[a][b]=='#'
                            route.append((a+1,b,n+1))
                            route.append((a-1,b,n+1))
                            route.append((a,b+1,n+1))
                            route.append((a,b-1,n+1))

print(max(ans))

Submission status: Time Limit Exceeded

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

ans=[]

for i in range(H):
    for j in range(W):
        sy=i
        sx=j
        if S[i][j]=='#':
            continue
        for k in range(H):
            for l in range(W):
                ey=k
                ex=l
                if S[k][l]=='#':
                    continue
                route=deque([(sy,sx,0)])
                while route:
                    a,b,n=route.popleft()
                    if a==ey and b==ex:
                        ans.append(n)
                        break
                    if 0<=a<=H-1 and 0<=b<=W-1:
                        if S[a][b]=='.':
                            S[a][b]=='#'
                            route.append((a+1,b,n+1))
                            route.append((a-1,b,n+1))
                            route.append((a,b+1,n+1))
                            route.append((a,b-1,n+1))

print(max(ans))

Submission status: Time Limit Exceeded

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

ans=[]

for i in range(H):
    for j in range(W):
        sy=i
        sx=j
        for k in range(H):
            for l in range(W):
                ey=k
                ex=l
                route=deque([(sy,sx,0)])
                while route:
                    a,b,n=route.popleft()
                    if a==ey and b==ex:
                        ans.append(n)
                        break
                    if 0<=a<=H-1 and 0<=b<=W-1:
                        if S[a][b]=='.':
                            S[a][b]=='#'
                            route.append((a+1,b,n+1))
                            route.append((a-1,b,n+1))
                            route.append((a,b+1,n+1))
                            route.append((a,b-1,n+1))

print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
import collections
def BFS(xNow,yNow,stage,visit):
    dist = [[0] * len(stage[0]) for i in range(len(stage))]
    deq = collections.deque()
    deq.append([xNow,yNow])
    cnt = 0
    while len(deq):
        [xNow,yNow] = deq.popleft()
        visit[xNow][yNow] = 1
        if stage[xNow+1][yNow] != "#" and visit[xNow+1][yNow] == 0:
            deq.append([xNow+1,yNow])
            dist[xNow+1][yNow] = dist[xNow][yNow] + 1
        if stage[xNow-1][yNow] != "#" and visit[xNow-1][yNow] == 0:
            deq.append([xNow-1,yNow])
            dist[xNow-1][yNow] = dist[xNow][yNow] + 1
        if stage[xNow][yNow+1] != "#" and visit[xNow][yNow+1] == 0:
            deq.append([xNow,yNow+1])
            dist[xNow][yNow+1] = dist[xNow][yNow] + 1
        if stage[xNow][yNow-1] != "#" and visit[xNow][yNow-1] == 0:
            deq.append([xNow,yNow-1])
            dist[xNow][yNow-1] = dist[xNow][yNow] + 1
    res = -1
    for i in range(len(dist)):
        res = max(res,max(dist[i]))
        #print(*dist[i])
    return res

[h,w] = [int(i) for i in input().split()]
s = [["#"] * (w+2)]
for i in range(h):
    tmp = input()
    tmp_ls = ["#"]
    for j in range(len(tmp)):
        tmp_ls.append(tmp[j])
    tmp_ls.append("#")
    s.append(tmp_ls)
s.append(["#"] * (w+2))

ans = -1
for i in range(1,h+1):
    for j in range(1,w+1):
        visited = [[0] * (w+2) for i in range(h+2)]
        if s[i][j] == ".":
            ans = max(ans,BFS(i,j,s,visited))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import product

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


def neighbors(ih, iw):
    for ih1, iw1 in (
        (ih - 1, iw),
        (ih + 1, iw),
        (ih, iw - 1),
        (ih, iw + 1),
    ):
        if 0 <= ih1 < h and 0 <= iw1 < w and maze[ih1][iw1] == '.':
            yield (ih1, iw1)



def len_maze(ih, iw):
    # BFS
    if maze[ih][iw] == '#':
        return 0

    stepped = [[False] * w for _ in range(h)]
    q0 = [(ih, iw)]
    l = -1
    while q0:
        q1 = []
        for ih0, iw0 in q0:
            stepped[ih0][iw0] = True
            for ih1, iw1 in neighbors(ih0, iw0):
                if not stepped[ih1][iw1]:
                    q1.append((ih1, iw1))
        q0 = q1
        l += 1

    return l


answer = max(len_maze(ih, iw) for ih, iw in product(range(h), range(w)))
print(answer)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

# (sx, sy) から (gx, gy) への最短距離を求める
# 辿り着けないと INF
def bfs(sx, gx, sy, gy):
    # すべての点を INF で初期化
    d = [[float("inf")] * m for i in range(n)]

    # 移動4方向のベクトル
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    # スタート地点をキューに入れ、その点の距離を0にする
    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    # キューが空になるまでループ
    while que:
        # キューの先頭を取り出す
        p = que.popleft()
        # 取り出してきた状態がゴールなら探索をやめる
        if p[0] == gx and p[1] == gy:
            break
        # 移動4方向をループ
        for i in range(4):
            # 移動した後の点を (nx, ny) とする
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            # 移動が可能かの判定とすでに訪れたことがあるかの判定
            # d[nx][ny] != INF なら訪れたことがある
            if 0 <= nx < n and 0 <= ny < m and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                # 移動できるならキューに入れ、その点の距離を p からの距離 +1 で確定する
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]

n, m = map(int, input().split())
maze = [list(input()) for i in range(n)]
ans = 1

for x in range(n):
    for y in range(m):
        sx = x
        sy = y
        for i in range(n):
            for j in range(m):
                gx = i
                gy = j
                if sx == gx and sy == gy:
                    continue
                if maze[sx][sy] == "#" or maze[gx][gy] == "#":
                    continue
                A = bfs(sx, gx, sy, gy)
                ans = max(A, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque 
from copy import deepcopy
# 初期入力
import sys
input = sys.stdin.readline
H,W = (int(i) for i in input().split())
map_initial =[["#"]*(W+2) for i in range(H+2)] #周囲を壁にするため＋２
for h in range(1,H+1):
    map_initial[h] =["#"] +list(input().strip()) +["#"]

def BSF(x,y):
    dist =0
    map =deepcopy(map_initial)
    if map[x][y] =="#":
        return dist 
    dq =deque()
    dq.append((x,y))
    dq_sarch =deque()
    while len(dq) >0:
        h,w =dq.popleft()
        map[h][w] ="#" #通り済を壁にする
        if map[h+1][w]==".":
            dq_sarch.append((h+1,w))
        if map[h-1][w]==".":
            dq_sarch.append((h-1,w))
        if map[h][w+1]==".":
            dq_sarch.append((h,w+1))
        if map[h][w-1]==".":
            dq_sarch.append((h,w-1))
        if len(dq)==0:
            dq =deepcopy(dq_sarch)
            dq_sarch.clear()
            dist +=1
        #print(h,w,dist,end="\t")
    return dist-1

#スタート位置を全探索し、最長距離を探す
dist_all =[]
for i in range(1,H+1):
    for j in range(1,W+1):
        dist_all.append(BSF(i,j) )
print(max(dist_all))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product

def solve():
    H, W = map(int, input().split())

    l = []
    for _ in range(H):
        l.append([0 if s=="." else 1 for s in input()])

    ans = 0

    for sh,sw,gh,gw in product(range(H),range(W),range(H),range(W)):
        if gw==sw and gh==sh:
            continue
        if l[gh][gw] or l[sh][sw]:
            continue

        q = deque([(sh, sw)])
        dist = [[10**12]*W for _ in range(H)]
        dist[sh][sw] = 0
        while q:
            h, w = q.popleft()
            for h1, w1 in [(h+1, w), (h, w+1), (h-1, w), (h, w-1)]:
                if not (0<=h1<H and 0<=w1<W):continue
                if l[h1][w1]:continue
                if dist[h1][w1] > dist[h][w] + 1:
                    dist[h1][w1] = dist[h][w] + 1
                    q.append((h1, w1))
        ans = max(ans, dist[gh][gw])
        
    print(ans)

solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def solve():
    H, W = map(int, input().split())

    l = []
    for _ in range(H):
        l.append([0 if s=="." else 1 for s in input()])

    ans = 0
    for sh in range(H):
        for sw in range(W):
            for gh in range(H):
                for gw in range(W):
                    if gw==sw and gh==sh:
                        continue
                    if l[gh][gw] or l[sh][sw]:
                        continue

                    q = deque([(sh, sw)])
                    dist = [[10**12]*W for _ in range(H)]
                    dist[sh][sw] = 0
                    while q:
                        h, w = q.popleft()
                        for h1, w1 in [(h+1, w), (h, w+1), (h-1, w), (h, w-1)]:
                            if not (0<=h1<H and 0<=w1<W):continue
                            if l[h1][w1]:continue
                            if dist[h1][w1] > dist[h][w] + 1:
                                dist[h1][w1] = dist[h][w] + 1
                                q.append((h1, w1))
                    ans = max(ans, dist[gh][gw])
    print(ans)

solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def solve():
    H, W = map(int, input().split())

    l = []
    for _ in range(H):
        l.append([0 if s=="." else 1 for s in input()])

    def dfs(sh, sw, gh, gw):
        q = deque([(sh, sw)])
        dist = [[10**12]*W for _ in range(H)]
        dist[sh][sw] = 0
        while q:
            h, w = q.popleft()
            for h1, w1 in [(h+1, w), (h, w+1), (h-1, w), (h, w-1)]:
                if not (0<=h1<H and 0<=w1<W):continue
                if l[h1][w1]:continue
                if dist[h1][w1] > dist[h][w] + 1:
                    dist[h1][w1] = dist[h][w] + 1
                    q.append((h1, w1))
        return dist[gh][gw]

    ans = 0
    for sh in range(H):
        for sw in range(W):
            for gh in range(H):
                for gw in range(W):
                    if gw==sw and gh==sh:
                        continue
                    if l[gh][gw] or l[sh][sw]:
                        continue
                    ans = max(ans, dfs(sh, sw, gh, gw))
    print(ans)

solve()

Submission status: Time Limit Exceeded

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

l = []
for _ in range(H):
    l.append([0 if s=="." else 1 for s in input()])

def dfs(sh, sw, gh, gw):
    q = deque([(sh, sw)])
    dist = [[10**12]*W for _ in range(H)]
    dist[sh][sw] = 0
    while q:
        h, w = q.popleft()
        for h1, w1 in [(h+1, w), (h, w+1), (h-1, w), (h, w-1)]:
            if not (0<=h1<H and 0<=w1<W):continue
            if l[h1][w1]:continue
            if dist[h1][w1] > dist[h][w] + 1:
                dist[h1][w1] = dist[h][w] + 1
                q.append((h1, w1))
    return dist[gh][gw]

ans = 0
for sh in range(H):
    for sw in range(W):
        for gh in range(H):
            for gw in range(W):
                if gw==sw and gh==sh:
                    continue
                if l[gh][gw] or l[sh][sw]:
                    continue
                ans = max(ans, dfs(sh, sw, gh, gw))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
h, w = map(int, input().split())
m = []
for i in range(h):
  m.append(input())
#print(h, w)
#print(m)
q = queue.Queue()
a = []
def init():
  global a, q
  q = queue.Queue()
  a = []
  for i in range(h):
    a.append([-1] * w)

def bfs(cx, cy):
  nxs = [1, 0, -1, 0]
  nys = [0, -1, 0, 1]
  for i in range(4):
    nx = cx + nxs[i]
    ny = cy + nys[i]
    if 0 <= nx and nx < w and 0 <= ny and ny < h and m[ny][nx] == '.' and a[ny][nx] == -1:
      a[ny][nx] = a[cy][cx] + 1
      q.put([nx, ny])
  
def check(start_x, start_y, end_x, end_y):
  if m[start_y][start_x] == '#' or m[end_y][end_x] == '#':
    return 0
  if start_x == end_x and start_y == end_y:
    return 0
  
  global a, q
  init()
  q.put([start_x, start_y])
  a[start_y][start_x] = 0
  while not q.empty():
    cx, cy = q.get()
    bfs(cx, cy)
  return a[end_y][end_x]

ans = 0
#for start_y in range(h):
#  for start_x in range(w):
#    for end_y in range(h):
#      for end_x in range(w):
#        ans = max(ans, check(start_x, start_y, end_x, end_y))
for i in range(h * w - 1):
  for j in range(i+1, h * w):
    start_x = i % w
    start_y = i // w
    end_x = j % w
    end_y = j // w
    #print(start_x, start_y, end_x, end_y)
    ans = max(ans, check(start_x, start_y, end_x, end_y))
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
INF = float('inf')

H, W = map(int, input().split())
Sss = ['#'*(W+2)] + ['#'+input()+'#' for _ in range(H)] + ['#'*(W+2)]

def convGrid2Graph(Sss):
    dxys = [(-1,0), (1,0), (0,-1), (0,1)]
    sizeX, sizeY = len(Sss)-2, len(Sss[0])-2

    numV = sizeX * sizeY
    adjL = [[] for _ in range(numV)]
    for x in range(1, sizeX+1):
        for y in range(1, sizeY+1):
            if Sss[x][y] != '.': continue
            z = (x-1)*sizeY + (y-1)
            for dx, dy in dxys:
                x2, y2 = x+dx, y+dy
                if Sss[x2][y2] != '.': continue
                z2 = (x2-1)*sizeY + (y2-1)
                adjL[z].append(z2)
    return adjL

def WarshallFloyd(adjList, INF):
    numV = len(adjList)
    D = [[INF]*numV for _ in range(numV)]
    for u, adj in enumerate(adjList):
        for v in adj:
            D[u][v] = 1
        D[u][u] = 0
    for k in range(numV):
        Dk = D[k]
        for i in range(numV):
            Di = D[i]
            Dik = Di[k]
            for j in range(numV):
                D2 = Dik + Dk[j]
                if D2 < Di[j]:
                    D[i][j] = D2
    return D

adjL = convGrid2Graph(Sss)

distss = WarshallFloyd(adjL, INF)

ans = 0
for i in range(H*W):
    for j in range(H*W):
        if distss[i][j] != INF:
            ans = max(ans, distss[i][j])

print(ans)