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:
h, w = map(int, input().split())
maze = []
for i in range(h):
    maze.append(list(input()))

import collections
# print(dat)
def clear_maze(sx, sy, gx, gy):
    INF = 100000000
    field_x_length = len(maze)
    field_y_length = len(maze[0])
    distance = [[INF for i in range(40)] for j in range(40)]

    def bfs():
        queue = collections.deque([])
        queue.appendleft((sx, sy))
        distance[sx][sy] = 0
        while len(queue):
            x, y = queue.pop()
            if x == gx and y == gy:
                break
            # print("seek {0} {1}".format(x, y))
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                if (0 <= nx and nx < field_x_length and 0 <= ny and ny < field_y_length and maze[nx][ny] != '#' and
                        distance[nx][ny] == INF):
                    queue.appendleft((nx, ny))
                    distance[nx][ny] = distance[x][y] + 1
        return distance[gx][gy]

    return bfs()

res = -1
for yy in range(0, h):
    for xx in range(0, w):
        if maze[yy][xx] == "#":
            continue
        for yyy in range(0, h):
            for xxx in range(xx, w):
                if maze[yyy][xxx] == "#":
                    continue
                step = clear_maze(yy, xx, yyy, xxx)
                # print("s={0},{1} g={2},{3} cost = {4}".format(xx,yy,xxx,yyy,step))
                if step == 100000000:
                    continue
                res = max(res, step)
print(res)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

def main():
	global Y
	global X
	global q
	global maps
	global maze

	H,W = inputMap()
	Y = H
	X = W
	mapmap = []
	ser = []
	for i in range(H):
		tmp = input()
		tmp = tmp[:-1]
		mapmap.append(tmp)

		for j,val in enumerate(tmp):
			if val == ".":
				ser.append((i,j))

	maps = [[-1 for _ in range(X)] for _ in range(Y)]
	maze = mapmap
	q = Queue()

	ans = 0
	for i,val in enumerate(ser):
		s,e = val
		for j,vol in enumerate(ser):
			sg,eg = vol
			tmp = serchs(s,e,sg,eg)
			maps = [[-1 for _ in range(X)] for _ in range(Y)]
			if tmp > ans:
				ans = tmp

	print(ans)

def serchs(start_y,start_x, goal_y,goal_x):
	q.enqueue((start_y, start_x))
	maps[start_y][start_x] = 0
	run()

	return(maps[goal_y][goal_x])

def run():
	while True:
		tmp = q.dequeue()
		if tmp == None:
			return

		y, x = tmp

		counts = maps[y][x] + 1
		if not y <= 0 and maps[y-1][x] == -1 and maze[y-1][x] == ".":
			q.enqueue((y-1, x))
			maps[y-1][x] = counts
		if not x <= 0 and maps[y][x-1] == -1 and maze[y][x-1] == ".":
			q.enqueue((y, x-1))
			maps[y][x-1] = counts
		if not y >= Y-1 and maps[y+1][x] == -1 and maze[y+1][x] == ".":
			q.enqueue((y+1, x))
			maps[y+1][x] = counts
		if not x >= X-1 and maps[y][x+1] == -1 and maze[y][x+1] == ".":
			q.enqueue((y, x+1))
			maps[y][x+1] = counts

class Queue:
    def __init__(self, queue = None):
        if type(queue) is type([]):
            self.queue = queue
        else:
            self.queue = []

    def enqueue(self, e):
        self.queue.append(e)
        return self.queue

    def dequeue(self):
        try:
            qEl = self.queue[0]
            del self.queue[0]
            return qEl
        except IndexError:
            return None


if __name__ == "__main__":
	main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import itertools
import copy
import numpy as np

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

def solve(S, s, g):
    M = copy.deepcopy(S)
    d = [[1, 0], [-1, 0], [0, -1], [0, 1]]
    queue = deque([s])
    steps = [[np.max for _ in range(W)] for _ in range(H)]
    steps[s[0]][s[1]] = 0

    while len(queue) > 0:
        current = queue.popleft()
        cy = current[0]
        cx = current[1]
        if cy == g[0] and cx == g[1]:
            return steps[cy][cx]
        else:
            M[cy][cx] = '#'
            for i in d:
                next = [cy+i[0], cx+i[1]]
                # はみ出さないかつ通ってない
                if (0<=next[0]<H and 0<=next[1]<W) and M[next[0]][next[1]]!='#':
                    queue.append(next)
                    steps[next[0]][next[1]] = steps[cy][cx] + 1
        
# print(solve(S, [0, 0], [0, 1]))
# print(solve(S, [2, 0], [0, 4]))

# print(S)
maxStep = 0
for s in itertools.product(range(H), range(W)):
    for g in itertools.product(range(H), range(W)):
        if S[s[0]][s[1]] == '.' and S[g[0]][g[1]] == '.':
            # print(s, g)
            # print(solve(S, [s[0], s[1]], [g[0], g[1]]))
            maxStep = max(solve(S, [s[0], s[1]], [g[0], g[1]]), maxStep)

print(maxStep)

Submission status: Time Limit Exceeded

Solution code:
def num():
    return int(input())
def nums():
    return list(map(int,input().split()))

import itertools as iter
import math
import fractions
from functools import reduce

def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

H,W = nums()
meiro = [[1] + [int(n == "#") for n in list(input())] + [1] for _ in range(H)]
meiro.insert(0,[1 for _ in range(W+2)])
meiro.insert(len(meiro),[1 for _ in range(W+2)])



import math

class MazeNode:
    def __init__(self,x,y,st,cond):
        self.x = x
        self.y = y
        self.state = st
        self.cond = cond
        self.parent = None
        self.fs = 0
        self.hs = 0
        self.gs = 0

    def calc_hs(self,gx,gy):
        dx = self.x - gx
        dy = self.y - gy
        self.hs = math.sqrt(dx ** 2 + dy ** 2)
    
    def update_gs(self):
        self.gs = self.fs - self.hs

    def set_gs(self,val):
        self.gs = val

    def set_cond(self,cond):
        if cond == "open" or cond == "close":
            self.cond = cond
        else:
            ##print("cond set error")
            pass
    
    # debug
    def show_pos(self):
        pass
        ##print("(%d:%d) %d %s" % (self.x,self.y,self.state,self.cond))

def get_min_fs_node(maze_nodes):
    # open_nodeのうちmin_fsのものを1つreturn
    res_node = None
    for row in maze_nodes:
        for node in row:
            if node.cond != "open":
                continue
            if not res_node:
                res_node = node
            elif node.fs < res_node.fs:
                res_node = node
    return res_node

def check_next_node(target_node,maze_nodes):
    # get next nods
    tx = target_node.x
    ty = target_node.y
    next_nodes = [
            maze_nodes[ty-1][tx  ],
            maze_nodes[ty  ][tx+1],
            maze_nodes[ty+1][tx  ],
            maze_nodes[ty  ][tx-1]
            ]

    # process next nodes
    target_node.update_gs()
    for node in next_nodes:
        if node.state == 1:
            continue
        f_dash = target_node.gs + node.hs + 1
        if node.cond == "none":
            node.set_cond("open")
            node.fs = f_dash
            node.parent = target_node
        elif node.cond == "open" and f_dash < node.fs:
            node.fs = f_dash
            node.parent = target_node
        elif node.cond == "close" and f_dash < node.fs:
            node.set_cond("open")
            node.fs = f_dash
            node.parent = target_node

def print_route(maze,fin_node):
    # make map data
    print()
    map = []
    for y in range(len(maze)):
        row = []
        for x in range(len(maze[0])):
            row.append("-" if maze[y][x] == 1 else " ")
        map.append(row)

    # make route data
    node = fin_node
    while node:
        map[node.y][node.x] = "x"
        node = node.parent

    # print route data
    for y in range(len(map)):
        for x in range(len(map[0])):
            print(map[y][x], end="")
        print("")

def make_route(fin_node):
    
    r = 0
    node = fin_node

    while node.parent:
        r += 1
        node = node.parent

    return r



def checkio(data,start,goal):
    maze = data
    maze_nodes = []

    goal_pos_x,goal_pos_y = goal

    for y in range(len(maze)):
        row = []
        for x in range(len(maze[0])):
            node = MazeNode(x,y,maze[y][x],"none")
            node.calc_hs(goal_pos_x,goal_pos_y)
            row.append(node)
        maze_nodes.append(row)

    start_node = maze_nodes[start[0]][start[1]]
    start_node.set_cond("open")
    start_node.set_gs(0)
    start_node.fs = start_node.hs

    while True: # step12:repeat
        # step3,4
        target_node = get_min_fs_node(maze_nodes)
        if not target_node:
            # step3
            #print("search fail")
            return "fail"
        elif target_node.x == goal_pos_x and target_node.y == goal_pos_y:
            #step5_finish
            #print("search finish")
            #print_route(maze,target_node)
            return make_route(target_node) #step13
        else:
            # step5_continue
            target_node.set_cond("close")
            check_next_node(target_node,maze_nodes) #step6-11



    
ans = set()
goals = [(x,y) for y in range(H+2) for x in range(W + 2)]
starts = [(x,y) for y in range(H) for x in range(W)]
for s in starts:
    for g in goals:
        try:
            r = checkio(meiro,s,g)
            if not r == "fail":ans.add(r)
        except:pass
print(max(ans)-1)

Submission status: Time Limit Exceeded

Solution code:
#import sys
#input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def dfs(B,si,sj, H, W):
    R = [-1]*(H*W)
    R[si*W+sj] = 0
    d = deque([si*W+sj])
    while d:
        p = d.popleft()
        x = p//W
        y = p%W
        t = R[x*W+y]

        if x > 0:
            if B[(x-1)*W+y] == 0:
                if R[(x-1)*W+y] == -1:
                    R[(x-1)*W+y] = t+1
                    d.append((x-1)*W+y)
                elif R[(x-1)*W+y] > t+1:
                    R[(x-1)*W+y] = t+1
                    d.append((x-1)*W+y)
        if x < H-1:
            if B[(x+1)*W+y] == 0:
                if R[(x+1)*W+y] == -1:
                    R[(x+1)*W+y] = t+1
                    d.append((x+1)*W+y)
                elif R[(x+1)*W+y] > t+1:
                    R[(x+1)*W+y] = t+1
                d.append((x+1)*W+y)
        if y > 0:
            if B[x*W+y-1] == 0:
                if R[x*W+y-1] == -1:
                    R[x*W+y-1] = t+1
                    d.append(x*W+y-1)
                elif R[x*W+y-1] > t+1:
                    R[x*W+y-1] = t+1
                    d.append(x*W+y-1)
        if y < W-1:
            if B[x*W+y+1] == 0:
                if R[x*W+y+1] == -1:
                    R[x*W+y+1] = t+1
                    d.append(x*W+y+1)
                elif R[x*W+y+1] > t+1:
                    R[x*W+y+1] = t+1
                    d.append(x*W+y+1)

    return max(R)
    

def main():
    H, W = map( int, input().split())
    S = [ list( input()) for _ in range(H)]
    B = [0]*(H*W)
    for i in range(H):
        for j in range(W):
            if S[i][j] == '#':
                B[i*W+j] = 1
    ans = 0
#    print(dfs(B,i,j,H,W))

    for i in range(H):
        for j in range(W):
            if B[i*W+j] == 1:
                continue
            t = dfs(B, i, j, H, W)
            if t > ans:
                ans = t
    print(ans)
            
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# import sys, re, os
# from collections import deque, defaultdict, Counter
# from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
# from itertools import permutations, combinations, product, accumulate
# from operator import itemgetter, mul
# from copy import deepcopy
# from string import ascii_lowercase, ascii_uppercase, digits
# from fractions import gcd
 
# def input(): return sys.stdin.readline().strip()
# def INT(): return int(input())
# def MAP(): return map(int, input().split())
# def S_MAP(): return map(str, input().split())
# def LIST(): return list(map(int, input().split()))
# def S_LIST(): return list(map(str, input().split()))
 
# sys.setrecursionlimit(10 ** 9)
# INF = float('inf')
# mod = 10 ** 9 + 7

# # 最大公約数 
# def gcd(a, b):
#   if a < b:
#       a, b = b, a
#   while a % b != 0:
#       a, b = b, a % b
#   return b

# # 最小公倍数
# def lcm(a, b):
#   y = a*b / gcd(a, b)
#   return int(y)

# H, W = MAP()


# L = []
# for i in range(m):
#   l = list(input())
#   L.append(l)
# print(L)


from collections import deque
H, W = map(int, input().split())
maze = [list(input()) for i in range(H)]
# print(maze)
n = H
m = W

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

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

    # for i in range(n):
    #     for j in range(m):
    #         # スタートとゴールの座標を探す
    #         if maze[i][j] == "S":
    #             sx = i
    #             sy = j
    #         if maze[i][j] == "G":
    #             gx = i
    #             gy = j

    # スタート地点をキューに入れ、その点の距離を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]



ans = 0
l = []
for h in range(H):
    for w in range(W):
        for h1 in range(H):
            for w1 in range(W):
                # ans = max(ans, bfs(w, h, w1, h1))
                if bfs(w, h, w1, h1) != float("inf"):
                    l.append(bfs(w, h, w1, h1))
print(max(l))

# print(ans)
# print(bfs())

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
import sys
input = sys.stdin.readline

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

ans = 0


def bfs(x, y):
    global ans
    m = np.full((H, W), -1, dtype=np.int)

    q = deque()
    q.append([y, x, 0])

    while q:
        j, i, v = q.popleft()
        m[j][i] = v
        dj = j + 1
        if dj < H and m[dj][i] == -1 and S[dj][i] == ".":
            q.append([dj, i, v+1])
            if ans < v+1:
                ans = v+1
        dj = j - 1
        if 0 <= dj and m[dj][i] == -1 and S[dj][i] == ".":
            q.append([dj, i, v+1])
            if ans < v+1:
                ans = v+1
        di = i + 1
        if di < W and m[j][di] == -1 and S[j][di] == ".":
            q.append([j, di, v+1])
            if ans < v+1:
                ans = v+1
        di = i - 1
        if 0 <= di and m[j][di] == -1 and S[j][di] == ".":
            q.append([j, di, v+1])
            if ans < v+1:
                ans = v+1


for j in range(H):
    for i in range(W):
        if S[j][i] != ".":
            continue
        bfs(i, j)
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 = 1000000
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
checked = []
for _ in range(H * W):
    checked.append([0] * (H * W))
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 checked[i * W + j][k * W + l] == 1:
                    continue
                if i == k and j == l:
                    continue
                ans = max(bfs(i, j, k, l), ans)
                checked[i * W + j][k * W + l] = 1
                checked[k * W + l][i * W + j] = 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from itertools import combinations
import copy
from collections import deque

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

S = np.zeros((H,W))
for i in range(H):
    scan =  input()
    # print(scan)
    for j,s in enumerate(scan):
        if s == ".":
            S[i][j] = 0
        else:
            S[i][j] = 1
# print(S)
positions = []
for i in range(H):
    for j in range(W):
        positions.append((i,j))
# print(positions)
c = combinations(positions,2)
result = 0
for pat in c:
    start = pat[0]
    stop = pat[1]
    distance = 0
    S1 = copy.deepcopy(S)
    q = deque()
    d = np.full((H,W),np.inf)
    q.append(start)
    d[start[0]][start[1]] = 0
    while len(q) > 0:
        p = q.popleft()
        # print(p)
        i,j = p[0],p[1]
        four = [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
        if p == stop:
            break
        for f in four:
            i1,j1 = f[0],f[1]
            if 0 <= i1 < H and 0<= j1 < W and S1[i1][j1] == 0 and d[i1][j1] == np.inf:
                q.append((i1,j1))
                d[i1][j1] = d[i][j] +1
    distance = d[stop[0]][stop[1]]
    # print(distance)
    if distance != np.inf and distance > result:
        result = int(distance)

print(result)

Submission status: Time Limit Exceeded

Solution code:
H, W = [int(x) for x in input().split(" ")]


class Node:
    def __init__(self, text, pos):
        self.text = text
        self.pos = pos
        self.next_nodes = []

    def add_next(self, node):
        self.next_nodes.append(node)


nodes = dict()
for i in range(H):
    for j, text in enumerate(input()):
        nodes[(i, j)] = Node(text, (i, j))


for i in range(H):
    for j in range(W):
        node = nodes[(i, j)]
        if node.text == "#":
            continue
        for pos in [(i-1, j), (i, j-1), (i+1, j), (i, j+1)]:
            if 0 <= pos[0] <= H-1 and 0 <= pos[1] <= W-1 and nodes[pos].text == ".":
                node.add_next(nodes[pos])


def all_pats():
    pat = []
    for i in range(H):
        for j in range(W):
            pat.append((i, j))
    return pat


def search(start, end):
    queue = []
    queue.append(start)
    count = dict()
    count[start.pos] = 0

    while True:
        if not queue:
            break
        node = queue[0]
        if node.pos == end:
            break
        queue = queue[1:]

        for next_node in node.next_nodes:
            if next_node.pos in count:
                continue
            count[next_node.pos] = count[node.pos] + 1
            queue.append(next_node)
    return count[end.pos]


total = []
searched = []
for start in all_pats():
    for end in all_pats():
        if (start, end) in searched:
            continue
        start_node = nodes[start]
        end_node = nodes[end]
        if start_node.text == "." and end_node.text == ".":
            res = search(start_node, end_node)
            total.append(res)
        searched.append((start, end))

print(max(total))

Submission status: Time Limit Exceeded

Solution code:
# 2020/01/12

from copy import deepcopy
import sys
from collections import deque

sys.setrecursionlimit(10**7)

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

# visited=[list([1]*(w+2))]
# for _ in range(h):
#     visited+=[[1]+list([0]*w)+[1]]
# visited+=[list([1]*(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
            maze[nx][ny]=maze[x][y]+1
            que.append((nx,ny))
            res=max(res,maze[nx][ny])
    return res


def find(mz):
    maze=deepcopy(mz)
    ret=0
    for i in range(1,h+1):
        for j in range(1,w+1):
            if maze[i][j]!='@':continue
            res=bfs(i,j,maze)
            ret=max(res,ret)
            maze=deepcopy(mz)

    return ret


def mk_maze(sx,sy,maze):
    x,y=sx,sy
    maze[x][y]='@'
    que=deque()
    que.append((x,y))

    while que:
        x,y=que.popleft()
        g[x][y]='#'
        for dx,dy in dr:
            nx=dx+x
            ny=dy+y
            if g[nx][ny]=='#':continue
            maze[nx][ny]='@'
            que.append((nx,ny))
    return maze

maze=[[0]*(w+2) for _ in range(h+2)]
ans=0
for i in range(1,h+1):
    for j in range(1,w+1):
        if g[i][j]=='#':continue
        mz=mk_maze(i,j,maze)
        res=find(mz)
        ans=max(res,ans)
print(res)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
inp = input()
H,W = inp.split()
H,W = int(H), int(W)

HW = H* W
adj = np.zeros((HW,HW), dtype = np.int8)
mapp = np.zeros((H,W), dtype = np.int8)

dr = [-1, +1,  0,  0]
dc = [ 0,  0, +1, -1]


for r in range(H):
    inp = input()
    for c in range(len(inp)):
        if inp[c] == '.':
            mapp[r,c] = 0
        else:
            mapp[r,c] = 1

            
#             adj[rr,cc] = 1
def minimum_steps(sr, sc, er, ec):    
    rq, cq = [], []
    visited = np.zeros((H,W), dtype = np.int8)
    move_count = 0
    nodes_left_in_layer = 1
    nodes_in_next_layer = 0
    
    reached = False
    
    
    rq.append(sr)
    cq.append(sc)
    visited[sr,sc] = 1
    
    while len(rq)>0:
        #print(rq, cq)
        r,c = rq[0], cq[0]
        rq.pop(0)
        cq.pop(0)
        
        if (r,c) == (er,ec):
            reached = True
            break

        #explore negiht
        for i in range(4):
            rr = r+dr[i]
            cc = c+dc[i]
            if rr < 0 or cc <0:
                continue
            elif rr >= H or cc >=W:
                continue

            if visited[rr][cc]:
                continue
            if mapp[r,c] == 1:
                continue
            rq.append(rr) 
            cq.append(cc)
            visited[rr][cc] = 1
            nodes_in_next_layer +=1
        #explore neihgbors
        
        nodes_left_in_layer-=1
        if nodes_left_in_layer == 0:
            nodes_left_in_layer = nodes_in_next_layer
            nodes_in_next_layer = 0
            move_count+=1
    if reached:
        return move_count
    return -1

maxValue = 0
for sr in np.arange(H, dtype= np.int8):
    for sc in np.arange(W, dtype= np.int8):
        for er in np.arange(H, dtype= np.int8):
            for ec in np.arange(W, dtype= np.int8):
                if maxValue < minimum_steps(sr, sc, er, ec):
                    maxValue = minimum_steps(sr, sc, er, ec)
print(maxValue)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy
 
def ngoin(bo,now):
    return 0 <= now[0] and now[0] < len(bo) and 0 <= now[1] and now[1] < len(bo[0])
 
def minido(bo,si,sj):
    tb = [[False for i in range(len(bo[0]))] for j in range(len(bo))]
    q = queue.Queue()
    q.put([si,sj,0])
    ret = 0
    while not q.empty():
        now = q.get()
        ret = now[2]
        if tb[now[0]][now[1]]:
            continue
        tb[now[0]][now[1]] = True
        if ngoin(bo,[now[0]-1,now[1]]):
            if bo[now[0]-1][now[1]]:
                q.put([now[0]-1,now[1],now[2]+1])
        if ngoin(bo,[now[0],now[1]+1]):
            if bo[now[0]][now[1]+1]:
                q.put([now[0],now[1]+1,now[2]+1])
        if ngoin(bo,[now[0]+1,now[1]]):
            if bo[now[0]+1][now[1]]:
                q.put([now[0]+1,now[1],now[2]+1])
        if ngoin(bo,[now[0],now[1]-1]):
            if bo[now[0]][now[1]-1]:
                q.put([now[0],now[1]-1,now[2]+1])
    return ret
            
 
h,w = map(int,input().split())
bo = [[True if x == '.' else False for x in input()] for i in range(h)]
grap = [[float('inf') for i in range(h*w)] for j in range(h*w)]
ans = 0
for i in range(h*w):
    grap[i][i] = 0
for si in range(h):
    for sj in range(w):
        if not bo[si][sj]:
            continue
        ans = max(ans,minido(bo,si,sj)-1)
                
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
import fractions
import bisect
import collections
import itertools
import heapq
import string
import sys
import copy
sys.setrecursionlimit(10**9)
def gcd(a,b):return fractions.gcd(a,b) #最大公約数
def lcm(a,b):return (a*b) // fractions.gcd(a,b) #最小公倍数
def iin(): return int(input()) #整数読み込み
def isn(): return input().split() #文字列読み込み
def imn(): return map(int, input().split()) #整数map取得
def iln(): return list(map(int, input().split())) #整数リスト取得
def iln_s(): return sorted(iln()) # 昇順の整数リスト取得
def iln_r(): return sorted(iln(), reverse=True) # 降順の整数リスト取得
def join(l, s=''): return s.join(l) #リストを文字列に変換
def perm(l, n): return itertools.permutations(l, n) # 順列取得
def perm_count(n, r): return math.factorial(n) // math.factorial(n-r) # 順列の総数
def comb(l, n): return itertools.combinations(l, n) # 組み合わせ取得
def comb_count(n, r): return math.factorial(n) // (math.factorial(n-r) * math.factorial(r)) #組み合わせの総数
def divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i: divisors.append(n//i)
    return divisors
def is_prime(n):
    if n == 1: return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0: return False 
    return True
def primes(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n + 1, i): is_prime[j] = False
    return [i for i in range(n+1) if is_prime[i]]
def sieve_of_e(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n+1, i): is_prime[j] = False
    return is_prime
def run_length_encode(s):
    count = 1
    code = []
    target = s[0]
    for i in range(1, len(s)):
        if target == s[i]: count += 1
        else:
            code.append((target, count))
            target = s[i]
            count = 1
    code.append((target, count))
    return code

H,W = imn()
S = [input() for _ in range(H)]
an = 10**10
def m(a, b, c, d, cnt, done):
    if a < 0 or a >= H or b < 0 or b >= W: return False
    if S[a][b] == '#': return False 
    do = copy.deepcopy(done)
    global an
    if a == c and b == d:
        an = min(an, cnt)
        return True
    else:
        do[a][b] = True
        cnt += 1
        if a-1 >= 0 and not done[a-1][b]: m(a-1,b,c,d,cnt,do)
        if b-1 >= 0 and not done[a][b-1]: m(a,b-1,c,d,cnt,do)
        if b+1 < W  and not done[a][b+1]: m(a,b+1,c,d,cnt,do)
        if a+1 < H  and not done[a+1][b]: m(a+1,b,c,d,cnt,do)
        return 
ans = -1
for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                if i == k and j == l: continue
                done = [[False for _ in range(W)]for _ in range(H)]
                m(i,j,k,l,0, copy.deepcopy(done))
                if an != 10**10:
                    ans = max(ans, an)
                an = 10**10 
print(ans)