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


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

    # 移動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 < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == 10 ** 12:
                # 移動できるならキューに入れ、その点の距離を p からの距離 +1 で確定する
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


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

ans = 0
for sx in range(h):
    for sy in range(w):
        if maze[sx][sy] == ".":
            for gx in range(h):
                for gy in range(w):
                    if sx == gx and sy == gy:
                        continue
                    if maze[gx][gy] == ".":
                        ans = max(ans, bfs())

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
cmax = 0
for i in range(H):
    for j in range(W):
            for k in range(H):
                for l in range(W):
                    if S[i][j]=="." and S[k][l]==".":
                        que = deque([(i,j,0)])
                        hist = {(n,m):0 for n in range(H) for m in range(W)}
                        hist[(i,j)] = 1
                        while que:
                            x = que.popleft()
                            n,m,c = x[0],x[1],x[2]
                            if n==k and m==l:
                                cmax = max(cmax,c)
                                break
                            if m+1<W and S[n][m+1]=="." and hist[(n,m+1)]==0:
                                que.append((n,m+1,c+1))
                                hist[(n,m+1)] = 1
                            if m-1>-1 and S[n][m-1]=="." and hist[(n,m-1)]==0:
                                que.append((n,m-1,c+1))
                                hist[(n,m-1)] = 1
                            if n+1<H and S[n+1][m]=="." and hist[(n+1,m)]==0:
                                que.append((n+1,m,c+1))
                                hist[(n+1,m)] = 1
                            if n-1>-1 and S[n-1][m]=="." and hist[(n-1,m)]==0:
                                que.append((n-1,m,c+1))
                                hist[(n-1,m)] = 1
print(cmax)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
raw = []
for _ in range(h):
  tmp = input()
  add = []
  for j in range(w):
    if tmp[j] == '.':
      add.append(0)
    else:
      add.append(2)
  raw.append(add)
nex = [[0,1],[0,-1],[1,0],[-1,0]]
can = []
from copy import deepcopy as dc
for a in range(h):
  for b in range(w):
    if raw[a][b] == 2:
      continue
    last = dc(raw)
    last[a][b] = 1
    ans = 0
    while True:
      now = dc(last)
      ans += 1
      for i in range(h):
        for j in range(w):
          if last[i][j] == 1:
            for x in nex:
              if 0 <= i+x[0] < h and 0 <= j+x[1] < w:
                if now[i+x[0]][j+x[1]] == 0:
                  now[i+x[0]][j+x[1]] = 1
      check = 1
      for i in range(h):
        for j in range(w):
          check *= now[i][j]
      if check > 0:
        can.append(ans)
        #print(a,b)
        #for y in now:
          #print(y)
        break
      #if (a,b) == (0,4):
        #print(ans)
        #for y in now:
          #print(y)
      last = dc(now)
print(max(can))
#print(can)
#print(raw)

Submission status: Time Limit Exceeded

Solution code:
from fractions import gcd
# from datetime import date, timedelta
# from heapq import *
import heapq
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
import sys
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline

def make_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)

    divisors.sort()
    return divisors





def main():
    
    # n, m = map(int, input().split())
    # ps = [list(input().split()) for i in range(m)]

    # c = 1
    # ac, wa = 0, 0
    # d = defaultdict(int)
    # for i in range(m):
    #     if ps[i][1] == "AC" and d[int(ps[i][0])] == 0:
    #         ac += 1
    #         d[int(ps[i][0])] = 1
    #     elif ps[i][1] == "WA" and d[int(ps[i][0])] == 0:
    #         wa += 1
    # print(ac,wa)
            
    
    h, w = map(int, input().split())
    s = [input() for i in range(h)]



    l = []
    for i in range(h):
        for j in range(w):
            l.append((i, j))

    maze = s
    def Dijkstra_search(sx, sy, gx, gy, c):
        H = h
        W = w
        visited = [[False for i in range(W)] for j in range(H)]
        d = [[float("inf") for i in range(W)] for j in range(H)]  # now cost
        d[sx][sy] = 0

        queue = []
        heapq.heappush(queue, (0, (sx, sy)))
        while len(queue):
            cost, (x, y) = heapq.heappop(queue)
            if x == gx and y == gy:
                break
                return cost

            if visited[x][y]:
                continue
            visited[x][y] = True

            for dx, dy in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
                nx = x + dx
                ny = y + dy
                if nx >= 0 and ny >= 0 and nx < H and ny < W:
                    if visited[nx][ny] or maze[nx][ny] == "#":
                        continue

                    vd = 1 + cost
                    if d[nx][ny] > vd:
                        d[nx][ny] = vd
                        heapq.heappush(queue, (vd, (nx, ny)))

        return d[gx][gy]
    
    # ans = 0
    # for ll in itertools.combinations(l, 2):
    #     d = deque()
    #     d.append(ll[0])
    #     visited = [[0 for i in range(w)] for j in range(h)]
    #     while len(d) != 0:
    #         x, y = d.pop()
    #         if x == ll[1][0] and y == ll[1][1]:
    #             break
    #         for i, j in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
    #             nx = x + i
    #             ny = y + j
    #             if nx < 0 or ny < 0 or nx > h - 1 or ny > w - 1:
    #                 continue
    #             if s[nx][ny] == "#":
    #                 continue
    #             if visited[nx][ny] != 0:
    #                 continue
    #             d.append((nx, ny))
    #             visited[nx][ny] =visited[x][y] + 1
        

    #     print(ll, visited, visited[ll[1][0]][ll[1][1]])
    #     ans = max(visited[ll[1][0]][ll[1][1]], ans)
    ans = 0
    for v in itertools.combinations(l, 2):
        if s[v[0][0]][v[0][1]] == "#" or s[v[1][0]][v[1][1]] == "#":
            continue
        #print(Dijkstra_search(v[0][0], v[0][1], v[1][0], v[1][1], 1))
        ans = max(ans , Dijkstra_search(v[0][0],v[0][1],v[1][0],v[1][1],1))
    print(ans)
                


                
        




    


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product
from copy import deepcopy

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

sls = list(product(range(h),range(w)))
gls = list(product(range(h),range(w)))
ans = 0
move = [[0,1], [1,0],[0,-1], [-1,0]]
for s in sls:
    for g in gls:
        if s==g or ls[s[0]][s[1]] == '#' or ls[g[0]][g[1]] == '#' :
            continue
        else:
            lss = deepcopy(ls)
            d=deque()
            d.append(s)
            lss[s[0]][s[1]] = 0
            while d:
                x,y = d.popleft()
                c = lss[x][y]
                for dx,dy in move:
                    if 0<=x+dx<h and 0<=y+dy<w and lss[x+dx][y+dy] == '.' :
                        lss[x+dx][y+dy] = c+1
                        d.append([x+dx, y+dy])
            ans = max(ans, lss[g[0]][g[1]])

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys

def solve(h, w, a):
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]
    def bfs(x1, y1, x2, y2):
        visited = [[False] * w for _ in range(h)]
        cur = []
        visited[y1][x1] = True
        cur.append((x1, y1))
        cnt = 1
        while True:
            nex = []
            for x, y in cur:
                for i in range(4):
                    tx = x + dx[i]
                    ty = y + dy[i]
                    if 0 <= tx < w and 0 <= ty < h and a[ty][tx] != '#' and not visited[ty][tx]:
                        visited[ty][tx] = True
                        if tx == x2 and ty == y2:
                            return cnt
                        nex.append((tx, ty))
            if len(nex) > 0:
                cur = nex
            else:
                break
            cnt += 1
        return -1
    ret = -1
    for i in range(h):
        for j in range(w):
            for i2 in range(h):
                for j2 in range(w):
                    if (not (i == i2 and j == j2)) and a[i][j] == '.' and a[i2][j2] == '.':
                        tmp = bfs(j, i, j2, i2)
                        ret = max(ret, tmp)
    print(ret)
    return

def main():
    h, w = map(int, input().split())
    a = []
    for i in range(h):
        a.append(input())
    solve(h, w, a)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
A = [[0 for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            A[i][j] = 0
        else:
            A[i][j] = 1
cmax = 0
for i in range(H):
    for j in range(W):
            for k in range(H):
                for l in range(W):
                    if A[i][j]==0 and A[k][l]==0:
                        que = deque([(i,j,0)])
                        hist = {(n,m):0 for n in range(H) for m in range(W)}
                        hist[(i,j)] = 1
                        while que:
                            x = que.popleft()
                            n,m,c = x[0],x[1],x[2]
                            if n==k and m==l:
                                cmax = max(cmax,c)
                                break
                            if m+1<W and A[n][m+1]==0 and hist[(n,m+1)]==0:
                                que.append((n,m+1,c+1))
                                hist[(n,m+1)] = 1
                            if m-1>-1 and A[n][m-1]==0 and hist[(n,m-1)]==0:
                                que.append((n,m-1,c+1))
                                hist[(n,m-1)] = 1
                            if n+1<H and A[n+1][m]==0 and hist[(n+1,m)]==0:
                                que.append((n+1,m,c+1))
                                hist[(n+1,m)] = 1
                            if n-1>-1 and A[n-1][m]==0 and hist[(n-1,m)]==0:
                                que.append((n-1,m,c+1))
                                hist[(n-1,m)] = 1
print(cmax)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n, m = map(int, input().split())
maps = [list(input()) for _ in range(n)]

def bfs(sx, sy, gx, gy):
    distance = [[float("inf")] * m for _ in range(n)]
    dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]

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

    while que:
        p = que.popleft()
        if p[0] == gx and  p[1] == gy:
            break

        for i in range(4):
            nx, ny = p[0] + dx[i], p[1] + dy[i]
            if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] != "#" and distance[nx][ny] == float("inf"):
                que.append((nx, ny))
                distance[nx][ny] = distance[p[0]][p[1]] + 1

    return distance[gx][gy]

s, g = [], []
ans = 0
for i in range(n):
    for j in range(m):
        s.append([i, j]), g.append([i, j])

for i in range(n * m):
    for j in range(n * m):
        if maps[s[i][0]][s[i][1]] == "." and maps[g[j][0]][g[j][1]] == ".":
            ans = max(ans, bfs(s[i][0], s[i][1], g[j][0], g[j][1]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

n, m = map(int, input().split())
maps = [list(input()) for _ in range(n)]

def bfs(sx, sy, gx, gy):
    distance = [[float("inf")] * m for _ in range(n)]
    dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]

    for i in range(n):
        for k in range(m):
            if maps[i][k] == "S":
                sx, sy = i, k

            if maps[i][k] == "G":
                gx, gy = i, k

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

    while que:
        p = que.popleft()
        if p[0] == gx and  p[1] == gy:
            break

        for i in range(4):
            nx, ny = p[0] + dx[i], p[1] + dy[i]
            if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] != "#" and distance[nx][ny] == float("inf"):
                que.append((nx, ny))
                distance[nx][ny] = distance[p[0]][p[1]] + 1

    return distance[gx][gy]

s, g = [], []
ans = 0
for i in range(n):
    for j in range(m):
        s.append([i, j]), g.append([i, j])

for i in range(n * m):
    for j in range(n * m):
        if maps[s[i][0]][s[i][1]] == "." and maps[g[j][0]][g[j][1]] == ".":
            ans = max(ans, bfs(s[i][0], s[i][1], g[j][0], g[j][1]))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int,input().split())
#alist = list(map(int, input().split()))

road=[]

for i in range(h):
    row=input()
    road.append(row)

ikel=0

for i in range(h):
    for j in range(w):
        if road[i][j]=='.':
            ikel+=1

maxrecord=0

for i in range(h):
    for j in range(w):
        turn=1
        ima=1
        now=[[i, j]]
        rlist=[]
        for hh in range(h):
            rlist.append([999]*w)
        rlist[i][j]=0
        while ima<ikel:
            #while turn<10:
            koho=[]
            for nw in now:
                koho.append([nw[0]-1, nw[1]])
                koho.append([nw[0]+1, nw[1]])
                koho.append([nw[0], nw[1]-1])
                koho.append([nw[0], nw[1]+1])
            #print(rlist)
            now=[]
            for kh in koho:
                if kh[0]>=0 and kh[1]>=0 and kh[0]<h and kh[1]<w:
                    #print(kh)
                    if road[kh[0]][kh[1]]=='.':
                        #print(kh, rlist[kh[0]][kh[1]])
                        if rlist[kh[0]][kh[1]]>turn:
                            #print(kh)
                            rlist[kh[0]][kh[1]]=turn
                            now.append([kh[0], kh[1]])
                            ima+=1
                            record=turn
            turn+=1
        #print('result', rlist)
        if record>maxrecord:
            maxrecord=record

print(maxrecord)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
sheet = [[0]*(W+2) for i in range(H+2)]
for i in range(H):
  s = input()
  for j in range(W):
    if s[j]=='.':
      sheet[i+1][j+1] = 1

m = -1
for i in range(1, H+1):
  for j in range(1, W+1):
    for a in range(1, H+1):
      for b in range(1, W+1):
        if sheet[i][j]==0 or sheet[a][b]==0:
          continue
        stuck = deque([(j, i, 0)])
        while stuck:
          x, y, c = stuck.popleft()
          if x==b and y==a:
            if m<c:
              m=c
            break
          for dx, dy in [(0,1), (0,-1), (1,0), (-1,0)]:
              if sheet[y+dy][x+dx]==1:
                stuck += [(x+dx, y+dy, c+1)]
print(m)

Submission status: Time Limit Exceeded

Solution code:
import copy
from collections import deque
h,w=map(int,input().split())
p=[list("#"*(w+2))]+[list("#"+input()+"#") for i in range(h)]+[list("#"*(w+2))]
b=copy.deepcopy(p)
ans=0
#s0,s1=map(lambda x:int(x)-1,input().split())
#g0,g1=map(lambda x:int(x)-1,input().split())
for i in range(1,h+1):
    for j in range(1,w+1):
        for k in range(1,h+1):
            for z in range(1,w+1):
                p=copy.deepcopy(b)
                if p[i][j]=='.' and p[k][z]=='.':
                    s0,s1=i,j
                    g0,g1=k,z
                    p[s0][s1]=0
                    d=[(1,0),(-1,0),(0,1),(0,-1)]
                    q=deque([[s0,s1]])
                    while q:
                        x,y=q.popleft()
                        for dx,dy in d:
                            if p[x+dx][y+dy]==".":
                                p[x+dx][y+dy]=p[x][y]+1
                                q.append([x+dx,y+dy])
                    if ans<=p[g0][g1]:
                        ans=p[g0][g1]
print(ans)

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)]
ans=0
Q=deque()
vec=[(1,0),(0,1),(-1,0),(0,-1)]
his=[[False for i in range(w)] for j in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j]=='#':
            continue
        Q.append([i,j,0])
        while Q:
            x,y,d=Q.popleft()
            for dx,dy in vec:
                tx=x+dx
                ty=y+dy
                if 0<=tx and tx<h and 0<=ty and ty<w and his[tx][ty]==False and s[tx][ty]=='.':
                    Q.append([tx,ty,d+1])
                    his[x][y]=True
                    ans=max(d+1,ans)
        his=[[False for i in range(w)] for j in range(h)]
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)]

    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] != "#":
                        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 collections

H,W=map(int,input().split())
S=[input() for i in range(H)]
cl=set()
for sy,sx in [[h,w] for h in range(H) for w in range(W)]:
    if S[sy][sx]!="#":
        for gy,gx in [[h,w] for h in range(H) for w in range(W)]:
            if S[gy][gx]!="#":
                stack=collections.deque([[sy,sx,0]])
                itta=set([sy*100+sx])
                #print(stack)
                while stack:
                    y,x,m=stack.popleft()
                    if y==gy and x==gx:
                        cl.add(m)
                        break
                    lst=[]

                    if y>0:lst.append([-1,0])
                    if y<H-1:lst.append([1,0])
                    if x>0:lst.append([0,-1])
                    if x<W-1:lst.append([0,1])

                    for a,b in lst:
                        Y=y+a
                        X=x+b
                        #print(Y,X)
                        if S[Y][X]=="." and not Y*100+X in itta:
                            stack.append([Y,X,m+1])
print(max(cl))

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,ei,ej):
    tb = [[False for i in range(len(bo[0]))] for j in range(len(bo))]
    q = queue.Queue()
    q.put([si,sj,0])
    while not q.empty():
        now = q.get()
        if now[0] == ei and now[1] == ej:
            return 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])
            
            

h,w = map(int,input().split())
board = [[True if x == '.' else False for x in input()] for i in range(h)]
ans = 0
for si in range(h):
    for sj in range(w):
        for ei in range(h):
            for ej in range(w):
                if (not board[si][sj]) or (not board[ei][ej]):
                    continue
                ans = max(ans,minido(board,si,sj,ei,ej))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

h, w = map(int, input().split())
board = np.zeros((h, w), dtype=bool)

for i in range(h):
    line = input()
    for j, s in enumerate(line):
        board[i][j] = s == "."


def get_around(i, j):
    if i > 0:
        yield (i - 1, j)
    if i < h - 1:
        yield (i + 1, j)
    if j > 0:
        yield (i, j - 1)
    if j < w - 1:
        yield (i, j + 1)


from collections import deque


def length(start, end):
    q = deque()
    q.append((start, 0))
    seen = np.zeros((h, w), dtype=bool)
    seen[start] = True
    while q:
        cur, l = q.popleft()
        if cur == end:
            return l
        for ncur in get_around(*cur):
            if board[ncur] and not seen[ncur]:
                seen[ncur] = True
                q.append(((ncur), l + 1))


def yield_pos():
    for i in range(h):
        for j in range(w):
            if board[i, j]:
                yield (i, j)


res = 0
for start in yield_pos():
    for end in yield_pos():
        res = max(length(start, end), res)
print(res)

Submission status: Time Limit Exceeded

Solution code:
import queue

class BreadthFirstSearch:
    def __init__(self, h, w, start_xy, goal_xy, board):
        self.h, self.w = h, w
        (self.sx, self.sy) = start_xy
        (self.gx, self.gy) = goal_xy
        self.board = board
        self.hist = [[False] * w for i in range(h)]

    def get_step(self, wall="#"):
        '''
        区切り文字を指定する(デフォルトは#)
        ゴールに着くまでの最短距離を出力
        ゴールにたどり着かない場合は0を出力
        '''
        q = queue.Queue()
        q.put((self.sx, self.sy))
        step = 0
        count = 1
        next_count = 1
        ans = 0
        # キューが空になるまで
        while not q.empty():
            x, y = q.get()
            count -= 1
            if count == 0:
                step += 1
                count = next_count
                next_count = 0
            # ゴールにたどり着くまでのステップ
            if x == self.gx and y == self.gy:
                ans = step
                break
            for (i, j) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                # 範囲内か
                if not(0 <= x+i <= w - 1) or not(0 <= y+j <= h - 1):
                    continue
                # 壁では無いか
                if self.board[y+j][x+i] == wall:
                    continue
                # 既に通ったところか
                if self.hist[y+j][x+i]:
                    continue
                # 通った印をつける
                self.hist[y+j][x+i] = True
                q.put((x+i, y+j))
                next_count += 1
        return ans


# 図の形
h, w = map(int, input().split())
# ボードの読み込み
board = [[i for i in list(str(input()))] for i in range(h)]
# スタート地点
ans_ = []
for s_i in range(h):
    for s_j in range(w):
        if board[s_i][s_j] == "#":
            continue
        for g_i in range(h):
            for g_j in range(w):
                if board[g_i][g_j] == "#":
                    continue
                if s_i == g_i and s_j == g_j:
                    continue
                s_xy = (s_j, s_i)
                g_xy = (g_j, g_i)
                bfs = BreadthFirstSearch(h, w, s_xy, g_xy, board[:])
                ans = bfs.get_step()
                if ans != 0:
                    ans_.append(ans)

print(max(ans_) - 1)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import queue

row, col = map(int, input().split(' '))
maze = [list(input()) for _ in range(row)]

                
def BPS(si, sj, gi, gj):
    global done
    done = [[0 for _ in range(col)] for _ in range(row)]
    q = queue.Queue()
    q.put((si, sj, 0))
    around = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    while not q.empty():
        i, j, cnt = q.get()
        done[i][j] = 1
        for ar in around:
            di, dj = ar[0], ar[1]
            i_n, j_n = i + di, j + dj
            if (i_n >= 0 and i_n < row and j_n >= 0 and j_n < col) == False:
                continue
            if maze[i_n][j_n] == '#':
                continue
            if done[i_n][j_n] == 1:
                continue
            if done[i_n][j_n] == 2:
                continue
            q.put((i_n, j_n, cnt + 1))
            done[i_n][j_n] = 2
        if i == gi and j == gj:
            return cnt
    return 0
            
            
def main():        
    maxv = 0
    for i in range(row):
        for j in range(col):
            for k in range(row):
                for l in range(col):
                    if i == k and j == l:
                        continue
                    maxv = max(maxv, BPS(i,j,k,l))
    print(maxv)
                    
                
                    
    
main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
#import numpy as np

stdin = sys.stdin

ri = lambda: int(rs())
rl = lambda: list(map(int, stdin.readline().split())) # applies to numbers only
rs = lambda: stdin.readline().rstrip()  # ignore trailing spaces

H, W = rl()
grid = [list(rs()) for _ in range(H)]
INF = 1000

def bfs(sx, sy, gx, gy):
    d = [[INF] * W for _ in range(H)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    que = deque()
    que.append((sx, sy))
    d[sy][sx] = 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 <= ny and ny <= H-1 and 0 <= nx and nx <= W-1 and \
                    grid[ny][nx] != '#' and d[ny][nx] == INF:
                d[ny][nx] = d[p[1]][p[0]] + 1
                que.append((nx, ny))
    return d[gy][gx]

answer = 0
for s in range(H):
    for t in range(W):
        for u in range(s, H):
            for v in range(W):
                if grid[s][t] == '#' or grid[u][v] == '#':
                    continue
                if s == u and t == v:
                    continue
                dis = bfs(t, s, v, u)
                if dis < 400 and dis > answer:
                    answer = dis

print(answer)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
M = [[-1]*(W+2) for _ in range(H+2)]
X = []
for h in range(H):
    for w, c in enumerate(input()):
        if c=='.':
            M[h+1][w+1] = 0
            X.append((h+1, w+1))

mark = 0
ans = 0
for ist, st in enumerate(X):
    for gl in X[ist+1:]:
        mark += 1
        turn = 0
        f = False
        queue = [st]
        while queue and not f:
            queue_new = []
            for qx, qy in queue:
                if (qx, qy)==gl:
                    f = True
                    break
                    
                for dx, dy in ((+1,0),(-1,0),(0,+1),(0,-1)):
                    x = qx+dx
                    y = qy+dy
                    m = M[x][y] 
                    if m!=-1 and m!=mark:
                        M[x][y] = mark
                        queue_new.append((x,y))
                        
            
            queue = queue_new
            turn += 1

        ans = max(ans, turn-1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#ライブラリインポート
from collections import defaultdict
import queue

#入力受け取り
def getlist():
	return list(map(int, input().split()))

INF = float("inf")

def BFS(H, W, L, start):
	dist = [[INF for i in range(W)] for j in range(H)]
	sy, sx = start
	dist[sy][sx] = 0
	Q = queue.Queue()
	Q.put([sy, sx])
	while not Q.empty():
		y, x = Q.get()
		if y - 1 >= 0:
			if L[y - 1][x] == "." and dist[y - 1][x] > dist[y][x] + 1:
				dist[y - 1][x] = dist[y][x] + 1
				Q.put([y - 1, x])
		if y + 1 <= H - 1:
			if L[y + 1][x] == "." and dist[y + 1][x] > dist[y][x] + 1:
				dist[y + 1][x] = dist[y][x] + 1
				Q.put([y + 1, x])
		if x - 1 >= 0:
			if L[y][x - 1] == "." and dist[y][x - 1] > dist[y][x] + 1:
				dist[y][x - 1] = dist[y][x] + 1
				Q.put([y, x - 1])
		if x + 1 <= W - 1:
			if L[y][x + 1] == "." and dist[y][x + 1] > dist[y][x] + 1:
				dist[y][x + 1] = dist[y][x] + 1
				Q.put([y, x + 1])

	return dist

#処理内容
def main():
	H, W = getlist()
	L = []
	for i in range(H):
		l = list(input())
		L.append(l)
	SGy = []
	SGx = []
	for i in range(H):
		for j in range(W):
			if L[i][j] == ".":
				SGy.append(i)
				SGx.append(j)

	N = len(SGx)
	ans = 0
	for i in range(N):
		for j in range(i + 1, N):
			start = [SGy[i] , SGx[i]]
			goal = [SGy[j] , SGx[j]]
			BF = BFS(H, W, L, start)
			val = BF[goal[0]][goal[1]]
			ans = max(ans, val)
	print(ans)


if __name__ == '__main__':
	main()