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())
# sx, sy = map(int, input().split())
# gx, gy = map(int, input().split())
# sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1
c = [input() for i in range(H)]

def bfs():
    dist = [[float('inf') for i in range(W)] for j in range(H)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    q = deque()
    q.append([sx, sy])
    dist[sx][sy] = 0
    while q:
        p = q.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 and nx < H and 0 <= ny and ny < W:
                if c[nx][ny] != '#' and dist[nx][ny] == float('inf'):
                    q.append([nx, ny])
                    dist[nx][ny] = dist[p[0]][p[1]] + 1
    return dist[gx][gy]

ans = []
for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                sx, sy = i, j
                gx, gy = k, l
                if c[sx][sy] == '#' or c[gx][gy] == '#':
                    continue
                ans.append(bfs())
                
ans = [i for i in ans if i != float('inf')]
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
import queue


def up(y, x, d):
    return y-1, x, d


def down(y, x, d):
    return y+1, x, d


def left(y, x, d):
    return y, x-1, d


def right(y, x, d):
    return y, x+1, d


def put_all(q, y, x, d):
    q.put((up(y, x, d)))
    q.put((down(y, x, d)))
    q.put((left(y, x, d)))
    q.put((right(y, x, d)))
    return


def put_not_all(q, y, x, d, distances):
    if distances[y-1][x] != -1:
        q.put((y-1, x, d))
    if distances[y+1][x] != -1:
        q.put((y+1, x, d))
    if distances[y][x-1] != -1:
        q.put((y, x-1, d))
    if distances[y][x+1] != -1:
        q.put((y, x+1, d))


def solve(maze, init_y, init_x, distances, H, W):
    if maze[init_y][init_x] == "#":
        return 0

    distances[init_y][init_x] = 0

    q = queue.Queue()
    put_all(q, init_y, init_x, 1)

    farthest = 0
    while not q.empty():
        y, x, d = q.get()
        # print(x, y)
        if x < 0 or x >= W or y < 0 or y >= H:
            # print("continue")
            continue
        if maze[y][x] == "#":
            distances[y][x] = 0
            continue
        distance = distances[y][x]
        if distance == -1:
            distances[y][x] = d
            put_all(q, y, x, d+1)
            farthest = max(farthest, d)

    return farthest


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

    max_distance = 0
    for i in range(H):
        for j in range(W):
            initial_map = [[-1 for _ in range(W)] for _ in range(H)]
            distance = solve(maze, i, j, initial_map, H, W)
            max_distance = max(distance, max_distance)
    print(max_distance)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

        for k in range(h):
            for l in range(w):
                if s[k][l] == '#' or i == k and j == l:
                    continue
                start = (i, j)
                goal = (k, l)
                d = [[1<<10 for x in range(w)] for y in range(h)]

                stack = []
                stack.append((start[0], start[1]))
                d[start[0]][start[1]] = 0
                while stack:
                    y, x = stack.pop()
                    if y == goal[0] and x == goal[1]:
                        continue
                    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))
                ans.append(d[goal[0]][goal[1]])
ans.sort()
print(ans[-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from itertools import product

INF = float('inf')

def floyd_warshall(V, E):
    dist = {u: {v: INF for v in V} for u in V}
    for v in V:
        dist[v][v] = 0
        for (i, j) in E[v]: dist[v][(i, j)] = 1
    for k in V:
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    for v in V:
        if dist[v][v] < 0: return None
    return dist


H, W = map(int, input().split())
maze = [input() for _ in range(H)]
V = []
E = defaultdict(list)
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[(i, j)].append((x, y)); E[(x, y)].append((i, j))
dist = floyd_warshall(V, E)
ans = 0
for D in dist.values():
    for d in D.values():
        if d != INF:
            ans = max(d, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations, product
import copy
H, W = map(int, input().split())


def search_steps(maze, cy, cx, gy, gx, step):
    if (cy, cx) == (gy, gx):
        return step
    ss = []
    for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
        ny, nx = cy + dy, cx + dx
        new_maze = copy.deepcopy(maze)
        new_maze[cy][cx] = "#"
        if 0 <= ny <= H - 1 and 0 <= nx <= W - 1 and maze[ny][nx] == ".":
            s = search_steps(new_maze, ny, nx, gy, gx, step + 1)
            if s >= 0:
                ss.append(s)

    if len(ss) == 0:
        return -1
    else:
        mss = min(ss)
        return min(ss) if mss >= 0 else -1


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

max_steps = 0
for s, g in combinations(range(H * W), 2):
    sy, sx = s // W, s % W
    gy, gx = g // W, g % W
    if S[sy][sx] == "#" or S[gy][gx] == "#":
        continue

    steps = search_steps(copy.deepcopy(S), sy, sx, gy, gx, 0)
    if steps > max_steps:
        max_steps = steps
    if steps == H * W - 1:
        break

print(max_steps)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


# このグラフ構造の中で一番遠い連結成分では？
H, W = read_ints()
S = read_map(H)

# おとなしく深さ優先探索

mvx = (1, 0, -1, 0)
mvy = (0, 1, 0, -1)

from itertools import product, combinations
from collections import deque


def ret_shortest(si, sj, gi, gj):
    visited = [[False] * W for _ in range(H)]
    que = deque([(si, sj, 0)])
    visited[si][sj] = True
    while que:
        i, j, cost = que.popleft()
        if i == gi and j == gj:
            ans = cost
            break

        for di, dj in zip(mvy, mvx):
            ni, nj = i + di, j + dj
            if not (-1 < ni < H) or not (-1 < nj < W) or visited[ni][nj] or S[ni][nj] == '#':
                continue
            que.append((ni, nj, cost + 1))
            visited[ni][nj] = True
    return ans


ans = 0


candi = []
for i, j in product(range(H), range(W)):
    if S[i][j] == '.':
        candi.append((i, j))
ans = 0
for a, b in combinations(candi, 2):
    ans = max(ans, ret_shortest(a[0], a[1], b[0], b[1]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import copy

sys.setrecursionlimit(200000)

def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

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



H,W=two_int()
maps = [[0 for i in range(W)] for j in range(H)]
not_wall_dicts = []

for i in range(H):
    S = one_str()
    for index,j in enumerate(S):
        if j =="#":
            maps[i][index] = 1
        else:
            not_wall_dicts.append([index,i])

def dfs2(pos, root, goal):
    # 停止条件
    # 深さに限らず，任意の停止条件を書く
    x,y = pos[0],pos[1]
    pos_str = str(pos[0])+"_"+str(pos[1])

    if pos_str in root or maps[y][x]==1:
        return 1000
    if pos_str==goal_str:
        return len(root)
        
    root[pos_str] = 1

    ret1,ret2,ret3,ret4 = 1000,1000,1000,1000
    if x >= 1:
        ret1 = dfs2([x-1, y], copy.deepcopy(root),goal_str)
    
    if x < W-1:
        ret2 = dfs2([x+1, y], copy.deepcopy(root),goal_str)

    if y >= 1:
        ret3 = dfs2([x, y-1], copy.deepcopy(root),goal_str)

    if y < H-1:
        ret4 = dfs2([x, y+1], copy.deepcopy(root),goal_str)

    return min(ret1, ret2, ret3, ret4)



length = len(not_wall_dicts)
maxs = 0
for i in range(length-1):
    goal = not_wall_dicts[i]
    goal_str = str(goal[0])+"_"+str(goal[1])
    for j in range(i,length):
        temp = dfs2(not_wall_dicts[j], {}, goal_str)
        
        if temp > maxs:
#             print(temp, not_wall_dicts[j], not_wall_dicts[i])
            maxs = temp

print(maxs)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = map(int, input().split())
s = [list(input()) for i in range(h)]

d_max = 0


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

    if d[gx][gy] == float("inf"):
        return 0
    else:
        return d[gx][gy]

for i in range(h):
    for j in range(w):
        for k in range(h):
            for l in range(w):
                if s[i-1][j-1] == '.' and s[k-1][l-1] == '.':
                    d_min = bfs(i,j,k,l)
                    if d_max < d_min:
                        d_max = d_min
print(d_max)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def bfs():
    h,w = map(int, input().split())
    maze = [list(input()) for i in range(h)]
    S, G = [], []
    for y in range(h):
        for x in range(w):
            if maze[y][x]=='.':
                S.append([y,x])
                G.append([y,x])
                maze[y][x]=float("inf")
    l = []
    for sy, sx in S:
      for gy, gx in G:
        if sy == gy and sx == gx:
          continue
        maze1 = copy.deepcopy(maze)
        maze1[sy][sx]=0
        que=deque([[sy,sx]])
        while que:
          y,x=que.popleft()
          for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if nexty < 0 or nexty >= h or nextx < 0 or nextx >= w:
                continue
            dist=maze1[nexty][nextx]
            if dist!='#':
              if dist>maze1[y][x]+1:
                maze1[nexty][nextx]=maze1[y][x]+1
                if nexty == gy and nextx == gx:
                  break
                que.append([nexty,nextx])
        l.append(maze1[gy][gx])
    print(max(l))
bfs()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from collections import deque
h,w = map(int, input().split())
s = [input() for _ in range(h)]

if h==1 and w==1:
    print(0)
    exit()

maxr = 0
for hi in range(h):
    for wi in range(w):
        if s[hi][wi]==".":
            maxr += 1

def solve(sh,sw,gh,gw):
    if s[sh][sw]=="#" or s[gh][gw]=="#":
        return -1

    visited = [[False for _ in range(w)] for _ in range(h)]
    visited[sh][sw] = True
    q = deque([(sh,sw,0)])
    while len(q)>0:
        hi,wi,r = q.popleft()
        for dh,dw in [[1,0],[0,1],[-1,0],[0,-1]]:
            if hi+dh>=0 and hi+dh<h and wi+dw>=0 and wi+dw<w and s[hi+dh][wi+dw]==".":
                if hi+dh==gh and wi+dw==gw:
                    return r+1
                elif not visited[hi+dh][wi+dw]:
                    visited[hi+dh][wi+dw] = True
                    q.append((hi+dh,wi+dw,r+1))

    return -1

res = -1
for shi in range(h):
    for swi in range(w):
        if s[shi][swi]=="#":
            continue
        for ghi in range(h-1,-1,-1):
            for gwi in range(w-1,-1,-1):
                if shi>=ghi and swi>=gwi:
                    break
                r = solve(shi,swi,ghi,gwi)
                if maxr==r:
                    print(r)
                    exit()
                res = max(res, r)

print(res)

Submission status: Time Limit Exceeded

Solution code:
import queue
import sys

input = sys.stdin.readline


class Solution:
    def main(self):
        H, W = map(int, input().split())
        S = [list(input().rstrip()) for _ in range(H)]

        for i in range(H):
            S[i] = ["#"] + S[i] + ["#"]
        S = [["#"] * (W + 2)] + S + [["#"] * (W + 2)]

        already = set()
        ans = 0
        for i in range(1, H + 1):
            for j in range(1, W + 1):
                if S[i][j] == "#":
                    continue
                for n in range(1, H + 1):
                    for m in range(1, W + 1):
                        if S[n][m] == "#" or (i, j) == (n, m) or (i, j, n, m) in already:
                            continue
                        v = self.min_move(S, (i, j), (n, m))
                        already.add((i, j, n, m))
                        already.add((n, m, i, j))
                        ans = max(ans, v)
        print(ans)

    def min_move(self, map, start, goal):
        moving_range = ((1, 0), (-1, 0), (0, 1), (0, -1))

        q = queue.Queue()
        q.put((start, 0))

        while q:
            pos, cnt = q.get()
            for move in moving_range:
                i, j = pos[0] + move[0], pos[1] + move[1]
                if (i, j) == goal:
                    return cnt + 1
                if map[i][j] == ".":
                    q.put(((i, j), cnt + 1))


# Run main
if __name__ == '__main__':
    Solution().main()

Submission status: Time Limit Exceeded

Solution code:
from itertools import combinations, product
import copy
H, W = map(int, input().split())


def search_steps(maze, cy, cx, gy, gx, step):
    if (cy, cx) == (gy, gx):
        return step
    ss = []
    for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
        ny, nx = cy + dy, cx + dx
        new_maze = copy.deepcopy(maze)
        new_maze[cy][cx] = "#"
        if 0 <= ny <= H - 1 and 0 <= nx <= W - 1 and maze[ny][nx] == ".":
            s = search_steps(new_maze, ny, nx, gy, gx, step + 1)
            if s >= 0:
                ss.append(s)

    if len(ss) == 0:
        return -1
    else:
        mss = min(ss)
        return min(ss) if mss >= 0 else -1


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

max_steps = 0
for s, g in combinations(range(H * W), 2):
    sy, sx = s // W, s % W
    gy, gx = g // W, g % W
    if S[sy][sx] == "#" or S[gy][gx] == "#":
        continue

    steps = search_steps(copy.deepcopy(S), sy, sx, gy, gx, 0)
    if steps > max_steps:
        max_steps = steps

print(max_steps)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
from collections import defaultdict
input = sys.stdin.readline
H, W = map(int, input().split())
C = [list(input()) for i in range(H)]

INF = 10 ** 9
n = H * W
d =[[float("inf") for _ in range(n)] for _ in range(n)]
go = [[1, 0], [0, 1], [-1, 0], [0, -1]]
for x in range(W):
    for y in range(H):
        for temp in go:
            gx,gy = temp
            nx = x + gx
            ny = y + gy
            if 0<= nx < W and 0<= ny < H and C[ny][nx] != "#":
                d[ny * W + nx][y * W + x] = 1
                d[y * W + x] [ny * W + nx]= 1
for i in range(n):
    d[i][i] = 0
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if C[i//W][i%W] != "#" and C[j//W][j%W] != "#" and C[k//W][k%W] != "#":
                    d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d
ans = warshall_floyd(d)
# print(ans)
x  = 0
for temp in ans:
    for k in temp:
        if k != float("inf"):
            x = max(k,x)
print(x)

Submission status: Time Limit Exceeded

Solution code:
def main():

    from collections import deque
    h, w = map(int, input().split())
    s = [list(input()) for _ in range(h)]
    cost = [[600] * w for _ in range(h)]
    nb = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    ans = 0

    def bfs(sx, sy, gx, gy):
        q = deque([(sx, sy)])
        cost[sy][sx] = 0

        while q != deque([]):
            x, y = q.popleft()
            for dx, dy in nb:
                nx = x + dx
                ny = y + dy
                if 0 <= nx and nx < w and 0 <= ny and ny < h and s[ny][nx] == "." and cost[ny][nx] == 600:
                    q.append((nx, ny))
                    cost[ny][nx] = cost[y][x] + 1
                    if nx == gx and ny == gy:
                        return cost[gy][gx]
        return 0

    ans = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == "#":
                continue
            for k in range(h):
                for l in range(w):
                    if s[i][j] == "#":
                        continue
                    cost = [[600] * w for _ in range(h)]
                    tmp = bfs(j, i, l, k)
                    ans = max(tmp, ans)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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
memo=[[0] * w for i in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j]=='.':
            for k in range(i,h):
                if i != k:
                    for l in range(w):
                        if s[k][l]=='.':
                            ans = max(ans,bfs(i,j,k,l))
                else:
                    for l in range(j,w):
                        if s[k][l]=='.':
                            ans = max(ans,bfs(i,j,k,l))
print(ans)

Submission status: Time Limit Exceeded

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

from collections import deque
INF = 100000000
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs(sx, sy, gx, gy):
    d = []
    for i in range(H):
        d.append([INF] * W)
    
    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    while len(que):
        p = que.popleft()
        if p == (gx, gy):
            break
        for i in range(4):
            nx = p[0] + dx[i]; ny = p[1] + dy[i]
            if 0 <= nx and nx < H and 0 <= ny and ny < W and S[nx][ny] != '#' and d[nx][ny] == INF:
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
    return d[gx][gy]

ans = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        for k in range(H):
            for l in range(W):
                if S[k][l] == '#':
                    continue
                if i == k and j == l:
                    continue
                ans = max(bfs(i, j, k, l), ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def search(h, w, pre_h, pre_w):
    can = []
    if h > 0:
        can.append((h-1, w))
    if h < H-1:
        can.append((h+1, w))
    if w > 0:
        can.append((h, w-1))
    if w < W-1:
        can.append((h, w+1))
    res = []
    for h, w in can:
        if S[h][w]=='.' and (h, w) != (pre_h, pre_w):
            res.append((h, w))
    return res

def bfs(h, w):
    d = [[float('inf') for _ in range(W)] for _ in range(H)]
    d[h][w] = 0
    pre_h, pre_w = h, w
    adj_list = search(h, w, pre_h, pre_w)
    open_list = deque([])
    closed_list = []
    for adj in adj_list:
        open_list.append((adj[0], adj[1], pre_h, pre_w))
    cnt = 0
    while True:
        cnt += 1
        if len(open_list) == 0:
            break
        h, w, pre_h, pre_w = open_list.popleft()
        closed_list.append((h, w, pre_h, pre_w))
        d[h][w] = min(d[h][w], d[pre_h][pre_w] + 1)
        adj_list = search(h, w, pre_h, pre_w)
        for adj in adj_list:
            if (adj[0], adj[1], h, w) in closed_list:
                continue
            open_list.append((adj[0], adj[1], h, w))

    res = 0
    for h in range(H):
        for w in range(W):
            if not d[h][w] == float('inf'):
                res = max(res, d[h][w])
    return res

def bounday():
    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                return False
    return True

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

if __name__ == "__main__":

    if bounday():
        print(H+W-2)
        exit(0)

    ans = 0
    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                continue
            maxd = bfs(h, w)
            ans = max(maxd, ans)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
"""
-1 -> not visited
else -> step count
"""
def bfs(maze, visited, sh, sw, gh, gw):
    stack = deque([[sh, sw]])
    visited[sh][sw] = 1
    while stack:
        h, w = stack.popleft()
        # ゴールの条件
        if h == gh and w == gw:
            break
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_h, new_w = h+j, w+k
            if new_h < 0 or new_h >= H or \
                new_w < 0 or new_w >= W:
                   continue
            elif maze[new_h][new_w] != "#" and \
                visited[new_h][new_w] == -1:
                    visited[new_h][new_w] = visited[h][w] + 1
                    stack.append([new_h, new_w])
    
    return visited[gh][gw]

if __name__ == "__main__":
    H, W = map(int, input().split())
    maze = [input() for _ in range(H)]

    vd = [[[[0 for _ in range(W)] for _ in range(H)] for _ in range(W)] for _ in range(H)]
    ans = 0
    for sh in range(H):
        for sw in range(W):
            for gh in range(H):
                for gw in range(W):
                    if maze[sh][sw] != "#" and maze[gh][gw] != "#" and vd[sh][sw][gh][gw] == 0 and vd[gh][gw][sh][sw] == 0 and not (gh == sh and gw == sw):
                        if ans > 1 and (abs(sh - gh) + abs(sw - gw) <= 1):
                            vd[sh][sw][gh][gw] = 1
                            vd[gh][gw][sh][sw] = 1
                        else:
                            vd[sh][sw][gh][gw] = 1
                            vd[gh][gw][sh][sw] = 1
                            visited = [[-1] * W for _ in range(H)]
                            step_cnt = bfs(maze, visited, sh, sw, gh, gw)
                            ans = max(ans, step_cnt)
    print(ans - 1)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import queue
H, W = map(int, input().split())
S = [input() for _ in range(H)]
reach = [[False] * W for i in range(H)]
step = np.ones((H, W)) * (-1)
m = 0


def dfs(x, y, s):
    if x < 0 or W <= x or y < 0 or H <= y:
        return None
    if reach[y][x]:
        return None
    if S[y][x] == '#':
        return None

    reach[y][x] = True
    step[y, x] = min(s, step[y, x])

    dfs(x+1, y, s+1)
    dfs(x-1, y, s+1)
    dfs(x, y-1, s+1)
    dfs(x, y+1, s+1)


q = queue.Queue()

for sh in range(H):
    for sw in range(W):
        reach = [[False] * W for i in range(H)]
        step = np.ones((H, W)) * (-1)
        #dfs(sw, sh, 0)
        q.put((sw, sh, 0))
        while not q.empty():
            x, y, s = q.get()
            if x < 0 or W <= x or y < 0 or H <= y:
                pass
            elif reach[y][x]:
                pass
            elif S[y][x] == '#':
                pass
            else:
                reach[y][x] = True
                step[y, x] = min(s, step[y, x]) if step[y, x] != -1 else s

                q.put((x+1, y, s+1))
                q.put((x-1, y, s+1))
                q.put((x, y-1, s+1))
                q.put((x, y+1, s+1))

        m = max(m, np.max(step))

print(int(m))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs(maze, visited, sy, sx, gy, gx):
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        if [y, x] == [gy, gx]:
            return visited[y][x]
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y+j, x+k
            if maze[new_y][new_x] == "." and \
                visited[new_y][new_x] == -1:
                visited[new_y][new_x] = visited[y][x] + 1
                queue.append([new_y, new_x])


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

sy, sx, gy, gx = 3, 1, 1, 5

maze = ["#"*(W+2)]
for i in range(H):
    tmp = "#"
    tmp += input()
    tmp += "#"
    maze.append(tmp)
maze.append("#"*(W+2))
    
#for i in range(H+2):
#    print(maze[i])

max_bfs = 0
for sy in range(1, H+2):
    for sx in range(1, W+2):
        for gy in range(1, H+2):
            for gx in range(1, W+2):
                if maze[sy][sx] == "." and maze[gy][gx] == ".":
                    visited = [[-1]*(W+2) for j in range(H+2)]
                    tmp_bfs = bfs(maze, visited, sy, sx, gy, gx)
                    if tmp_bfs > max_bfs:
                        max_bfs = tmp_bfs
                
print(max_bfs)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy
import numpy as np

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

maze = []
maze.append(["#" for i in range(W+2)])
for i in range(H):
    maze.append(list(input()))
    maze[i+1].insert(0,"#")
    maze[i+1].append("#")
maze.append(["#" for i in range(W+2)])

distance_template = [[-1 for i in range(W+2)] for i in range(H+2)]

ans = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if maze[i][j] != "#":
            startx,starty = i,j
            distance = np.array(distance_template)
            distance[startx][starty] = 0
            Q = queue.Queue()
            Q.put((startx, starty))
            while not Q.empty():
                x,y = Q.get()
                for k in range(0, 4):
                    nx, ny = x + [1, 0, -1, 0][k], y + [0, 1, 0, -1][k]
                    if (maze[nx][ny] != "#" and distance[nx][ny] == -1):
                        Q.put((nx, ny))
                        distance[nx][ny] = distance[x][y] + 1
            maxdistance = np.unravel_index(np.argmax(distance), distance.shape)
            if ans < distance[maxdistance[0]][maxdistance[1]]:
                ans = distance[maxdistance[0]][maxdistance[1]]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


# このグラフ構造の中で一番遠い連結成分では？
H, W = read_ints()
S = read_map(H)

# おとなしく深さ優先探索

mvx = (1, 0, -1, 0)
mvy = (0, 1, 0, -1)

from itertools import product, combinations
from collections import deque


def ret_shortest(si, sj, gi, gj):
    visited = [[False] * W for _ in range(H)]
    for i, j in product(range(H), range(W)):
        if S[i][j] == '#':
            visited[i][j] = True
    que = deque([(si, sj, 0)])
    visited[si][sj] = True
    while que:
        i, j, cost = que.popleft()
        if i == gi and j == gj:
            ans = cost
            break

        for di, dj in zip(mvy, mvx):
            ni, nj = i + di, j + dj
            if not (-1 < ni < H) or not (-1 < nj < W) or visited[ni][nj]:
                continue
            que.append((ni, nj, cost + 1))
            visited[ni][nj] = True
    return ans


ans = 0


candi = []
for i, j in product(range(H), range(W)):
    if S[i][j] == '.':
        candi.append((i, j))
ans = 0
for a, b in combinations(candi, 2):
    ans = max(ans, ret_shortest(a[0], a[1], b[0], b[1]))
print(ans)