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:
import sys
import itertools
import collections


def search(H, W, S, start, end):
    wall_i = ord(b'#')
    used = [[-1 for h in range(W)] for w in range(H)]

    qu = collections.deque()
    qu.append(start)
    used[start[0]][start[1]] = 0

    while qu:
        h, w = qu.popleft()
        cost = used[h][w]
        for h0, w0 in ((h - 1, w), (h + 1, w), (h, w - 1), (h, w + 1)):
            if not (0 <= h0 < H and 0 <= w0 < W):
                continue
            if used[h0][w0] != -1:
                continue
            if S[h0][w0] == wall_i:
                continue

            if (h0, w0) == end:
                return cost + 1
            used[h0][w0] = cost + 1
            qu.append((h0, w0))
        cost += 1

    return -1


def resolve(in_):
    H, W = map(int, next(in_).split())
    S = tuple(s.strip() for s in itertools.islice(in_, H))

    road_i = ord(b'.')

    roads = []
    for h in range(H):
        for w in range(W):
            if S[h][w] == road_i:
                roads.append((h, w))
    
    ans = max(search(H, W, S, start, end) for start, end in itertools.permutations(roads, 2))
    
    return ans


def main():
    answer = resolve(sys.stdin.buffer)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
import collections


def search(H, W, S, start, end):
    wall_i = ord(b'#')
    used = [[-1 for h in range(W)] for w in range(H)]

    qu = collections.deque()
    qu.append(start)
    used[start[0]][start[1]] = 0

    while qu:
        h, w = qu.popleft()
        cost = used[h][w]
        for h0, w0 in ((h - 1, w), (h + 1, w), (h, w - 1), (h, w + 1)):
            if not (0 <= h0 < H and 0 <= w0 < W):
                continue
            if used[h0][w0] != -1:
                continue
            if S[h0][w0] == wall_i:
                continue

            if (h0, w0) == end:
                return cost + 1
            used[h0][w0] = cost + 1
            qu.append((h0, w0))
        cost += 1

    return -1


def resolve(in_):
    H, W = map(int, next(in_).split())
    S = tuple(s.strip() for s in itertools.islice(in_, H))

    road_i = ord(b'.')

    roads = []
    for h in range(H):
        for w in range(W):
            if S[h][w] == road_i:
                roads.append((h, w))
    
    ans = max(search(H, W, S, start, end) for start, end in itertools.combinations(roads, 2))
    
    return ans


def main():
    answer = resolve(sys.stdin.buffer)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
maze = [0] * H
for i in range(H):
  maze[i] = str(input())

ans = 0  
for i in range(H):#20
  for j in range(W):#20
    if maze[i][j] != "#":
      visited = [[float("inf")] * W for _ in range(H)]
      visited[i][j] = 0
      queue = [[i, j]]
      while queue:#400
        x, y = queue.pop()
        for p, q in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
          if (0 <= x + p < H) and (0 <= y + q < W):
            if (maze[x+p][y+q] !="#"):       
              if visited[x+p][y+q] > visited[x][y] + 1:
                queue.append([x+p, y+q])
                visited[x+p][y+q] = visited[x][y] + 1
      #print(visited)        
      now = 0
      for k in range(H):
        for k2 in range(W):
          if visited[k][k2] < 10 ** 10:
            now = max(now, visited[k][k2])
      ans = max(ans, now)
      
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from copy import deepcopy

h,w = map(int,input().split())
s = [list(input()) for i in range(h)]
t = ((0,1),(1,0),(-1,0),(0,-1))
m = 0
for sy in range(h):
    for sx in range(w):
        if s[sy][sx] == "#":
            continue
        ss = deepcopy(s)
        q = deque([(0,sy,sx)])
        max_cost = 0
        my,mx = 0,0
        while(q):
            cost,y,x = q.popleft()
            max_cost = max(max_cost,cost)
            ss[y][x] = "#"
            cost += 1
            for i,j in t:
                ny = y+i
                nx = x+j
                if 0 <= ny < h and 0 <= nx < w:
                    if ss[ny][nx] == ".":
                        q.append((cost,ny,nx))
        m = max(m,max_cost)
print(m)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [input() for i in range(h)]
t = ((0,1),(1,0),(-1,0),(0,-1))
m = 0
for sy in range(h):
    for sx in range(w):
        if s[sy][sx] == "#":
            continue
        q = deque([(0,sy,sx)])
        max_cost = 0
        my,mx = 0,0
        f = [[True]*w for i in range(h)]
        f[sy][sx] = False
        while(q):
            cost,y,x = q.popleft()
            max_cost = max(max_cost,cost)
            f[y][x] = False
            cost += 1
            for i,j in t:
                ny = y+i
                nx = x+j
                if 0 <= ny < h and 0 <= nx < w:
                    if s[ny][nx] == "." and f[ny][nx]:
                        q.append((cost,ny,nx))
        m = max(m,max_cost)
print(m)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [input() for i in range(h)]
sy,sx = 0,0
f = False
for i,si in enumerate(s):
    if f:
        break
    for j,sij in enumerate(si):
        if sij == ".":
            sysx = i,j
            f = True
            break

t = ((0,1),(1,0),(-1,0),(0,-1))
c = 0
se = set()
m = 0
for sy in range(h):
    for sx in range(w):
        if s[sy][sx] == "#":
            continue
        q = deque([(0,sy,sx)])
        max_cost = 0
        my,mx = 0,0
        f = [[True]*w for i in range(h)]
        f[sy][sx] = False
        while(q):
            cost,y,x = q.popleft()
            if max_cost < cost:
                max_cost = cost
                my,mx = y,x
            f[y][x] = False
            cost += 1
            for i,j in t:
                ny = y+i
                nx = x+j
                if 0 <= ny < h and 0 <= nx < w:
                    if s[ny][nx] == "." and f[ny][nx]:
                        q.append((cost,ny,nx))
        m = max(m,max_cost)
print(m)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

dx=[1,-1,0,0]
dy=[0,0,1,-1]


for i in range(h):
  for j in range(w):
    for ii in range(h):
      for jj in range(w):
        Q=deque()
        Q.append((i,j,0))
        
        if maze[i][j]=='#' or maze[ii][jj]=='#':
          continue

        dp=[[-1]*w for i in range(h)]

        while Q:
          p=Q.popleft()
          if p[0]==ii and p[1]==jj:
            ans=max(ans,p[2])
            break
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==-1:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=p[2]+1


print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w=map(int,input().split())

maze=[list(input()) for i in range(h)]

ans=0

dx=[1,-1,0,0]
dy=[0,0,1,-1]


for i in range(h):
  for j in range(w):
    for ii in range(h):
      for jj in range(w):
        Q=deque()
        Q.append((i,j,0))
        
        if maze[i][j]=='#' or maze[ii][jj]=='#':
          continue

        dp=[[False]*w for b in range(h)]

        while Q:
          p=Q.popleft()
          if p[0]==ii and p[1]==jj:
            ans=max(ans,p[2])
            break
          for k in range(4):
            nx=p[0]+dx[k]
            ny=p[1]+dy[k]

            if 0<=nx<h and 0<=ny<w and maze[nx][ny]=='.' and dp[nx][ny]==False:
              Q.append((nx,ny,p[2]+1))
              dp[nx][ny]=True


print(ans)

Submission status: Time Limit Exceeded

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

mv = {(1, 0), (-1, 0), (0, 1), (0, -1)}


def BFS(St):
    stk = deque([[St[0],St[1],0]])
    seen = [[False]*W for _ in range(H)]
    while len(stk) > 0:
        l = stk.pop()
        i = l[0]
        j = l[1]
        ct = l[2]
        seen[i][j] = True
        for k in mv:
            x = i+k[0]
            y = j+k[1]
            if 0 <= x < H and 0 <= y < W:
                if S[x][y] == '.' and seen[x][y] == False:
                    stk.appendleft([x, y, ct+1])
    return(ct)

ans = 0
# 各スタート地点に対して最大距離を出力すればいいですねって話

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        ans=max(ans,BFS([i,j]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF=10**20
def main():
    H,W=mi()
    N = H*W

    def pos(h,w):
        return h*W+w

    G = []
    for h in range(H):
        G.append(list(input()))

    dp = [[INF] * N for _ in range(N)]
    for i in range(N):
        dp[i][i] = 0

    for h in range(H):
        for w in range(W):
            if G[h][w] == "#": continue

            for i in range(4):
                dh = [0,1,0,-1][i]
                dw = [1,0,-1,0][i]
                if 0<=h+dh<H and 0<=w+dw<W:
                    if G[h+dh][w+dw] == "#": continue
                    dp[pos(h,w)][pos(h+dh,w+dw)] = 1
                    dp[pos(h+dh,w+dw)][pos(h,w)] = 1


    ans = 0
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j])


    for i in range(N):
        for j in range(N):
            if dp[i][j] != INF:
                ans = max(ans,dp[i][j])
    

    print(ans)




if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF=10**20
def main():
    H,W=mi()
    N = H*W+W

    def pos(h,w):
        return h*W+w

    G = []
    for h in range(H):
        G.append(list(input()))

    dp = [[INF] * N for _ in range(N)]
    for i in range(N):
        dp[i][i] = 0

    for h in range(H):
        for w in range(W):
            if G[h][w] == "#": continue

            for i in range(4):
                dh = [0,1,0,-1][i]
                dw = [1,0,-1,0][i]
                if 0<=h+dh<H and 0<=w+dw<W:
                    if G[h+dh][w+dw] == "#": continue
                    dp[pos(h,w)][pos(h+dh,w+dw)] = 1
                    dp[pos(h+dh,w+dw)][pos(h,w)] = 1


    ans = 0
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j])


    for i in range(N):
        for j in range(N):
            if dp[i][j] != INF:
                ans = max(ans,dp[i][j])
    

    print(ans)





if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

from collections import deque
import math


def bfs(h,w,sy,sx,gy,gx,S):
    maze=[[10**9]*(W)for _ in range(H)]

    maze[sy-1][sx-1]=0
    que=deque([[sy-1,sx-1]])
    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 0<=nexty<h and 0<=nextx<w:
                dist1=S[nexty][nextx]
                dist2=maze[nexty][nextx]
            else:
                continue
            if dist1!='#':
                if dist2>maze[y][x]+1:
                    maze[nexty][nextx]=maze[y][x]+1
                    que.append([nexty,nextx])
    return maze[gy-1][gx-1]

ans=0
for sy in range(H):
    for sx in range(W):
        for gy in range(H):
            for gx in range(W):
                if S[sy][sx]=='.' and S[gy][gx]=='.':
                    now=bfs(H,W,sy+1,sx+1,gy+1,gx+1,S)
                    ans=max(ans,now)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue

def bfs(maze,h,w,sy,sx,gy,gx):
    dist=[[-1 for _ in range(w)] for _ in range(h)]
    q=queue.deque([[sy,sx]])
    dist[sy][sx]=0
    while q:
        y,x=q.popleft()
        for dy,dx in d:
            ny,nx=y+dy,x+dx
            if 0<=ny<h and 0<=nx<w and dist[ny][nx]==-1 and maze[ny][nx]!='#':
                dist[ny][nx]=dist[y][x]+1
                q.append([ny,nx])
    return dist[gy][gx]

h,w=map(int,input().split())
a=[input() for _ in range(h)]
d=[[1,0],[0,1],[-1,0],[0,-1]]
ans=0
for sy in range(h):
    for sx in range(w):
        for gy in range(h):
            for gx in range(w):
                if a[sy][sx]!='#' and a[gy][gx]!='#':
                    ans=max(ans,bfs(a,h,w,sy,sx,gy,gx))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import math

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

cost_max = 0
for s_y in range(H):
    for s_x in range(W):
            if S[s_y][s_x] == '.':
                dist_max = 0
                dist_max_pos = (s_y, s_x)
                dist = [[math.inf] * W for i in range(H)]
                queue = deque([(s_y, s_x)])
                dist[s_y][s_x] = 0
                while queue:
                    y, x = queue.popleft()
                    for i, j in [(1,0),(0,1),(-1,0),(0,-1)]:
                        n_x, n_y = x + i, y + j
                        if n_x >= 0 and n_y >= 0 and n_x < W and n_y < H:
                            if dist[n_y][n_x] > dist[y][x]:
                                if S[n_y][n_x] == '.':
                                    dist[n_y][n_x] = dist[y][x] + 1
                                    queue.append((n_y, n_x))
                                    dist_max = max(dist_max, dist[y][x] + 1)
                                    dist_max_pos = (n_y, n_x)
                cost_max = max(cost_max, dist[dist_max_pos[0]][dist_max_pos[1]])

print(cost_max)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import math

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

cost_max = 0
for s_y in range(H):
    for s_x in range(W):
        for g_y in range(H):
            for g_x in range(W):
                if s_y != g_y or s_x != g_x:
                    if S[s_y][s_x] == '.' and S[g_y][g_x] == '.':
                        dist = [[math.inf] * W for i in range(H)]
                        queue = deque([(s_y, s_x)])
                        dist[s_y][s_x] = 0
                        while queue:
                            y, x = queue.popleft()
                            for i, j in [(1,0),(0,1),(-1,0),(0,-1)]:
                                n_x, n_y = x + i, y + j
                                if n_x >= 0 and n_y >= 0 and n_x < W and n_y < H:
                                    if dist[n_y][n_x] > dist[y][x]:
                                        if S[n_y][n_x] == '.':
                                            dist[n_y][n_x] = dist[y][x] + 1
                                            queue.append((n_y, n_x))
                        cost_max = max(cost_max, dist[g_y][g_x])

print(cost_max)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w=map(int,input().split())
S=[]
for _ in range(h):
  s=input()
  sl=[]
  for i in range(w):
    sl.append(s[i])
  S.append(sl)
ans=-1
check=[]
for i in range(h):
  for j in range(w):
    for k in range(h):
      for l in range(w):
        if [k,l,i,j] in check:
          continue
        if S[i][j]=='.' and S[k][l]=='.':
          sy,sx,gy,gx=i,j,k,l
          W=[[-1 for i in range(w)] for j in range(h)]
          Q=deque()
          Q.append([sy,sx])
          W[sy][sx]=0
          while Q:
            py,px=Q.popleft()
            for p,q in [[-1,0],[0,-1],[1,0],[0,1]]:
              ny,nx=py+p,px+q
              if 0<=ny<=h-1 and 0<=nx<=w-1 and S[ny][nx]=='.':
                if W[ny][nx]==-1:
                  W[ny][nx]=W[py][px]+1
                  Q.append([ny,nx])
          check.append([i,j,k,l])
          ans=max(ans,W[gy][gx])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy

h,w=map(int,input().split())
Inf=float('inf')
maze1=[]
for _ in range(h):
  s=list(input())
  for u in range(w):
    if s[u]=='.':
      s[u]=Inf
  maze1.append(s)
  
def maze_solve(maze,sy,sx,gy,gx):
  qu=deque([[sy,sx]])
  maze[sy][sx]=0
  
  while qu:
    y,x=qu.popleft()
    
    T=maze[y][x]
    for i in ([1,0],[-1,0],[0,1],[0,-1]):
      ny=y+i[0]
      nx=x+i[1]
      if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!='#':
        
        if maze[ny][nx]>T+1:
          maze[ny][nx]=T+1
          qu.append([ny,nx])
          
 
  return maze[gy][gx]
  

ans=-Inf
for i in range(h):
  for j in range(w):
    if maze1[i][j]!='#':
      for x in range(h):
        for y in range(w):
          if maze1[x][y]!='#':
            maze2=copy.deepcopy(maze1)
            
            ans=max(ans,maze_solve(maze2,i,j,x,y))
            
            
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy

h,w=map(int,input().split())
maze1=[]
for _ in range(h):
  s=list(input())
  maze1.append(s)
  
def maze_solve(maze,sy,sx,gy,gx):
  Inf=float(inf)
  qu=deque([[sy,sx]])
  maze[sy][sx]=0
  
  while qu:
    y,x=qu.popleft()
    
    T=maze[y][x]
    for i in ([1,0],[-1,0],[0,1],[0,-1]):
      ny=y+i[0]
      nx=x+i[1]
      if 0<=ny<=h-1 and 0<=nx<=w-1 and maze[ny][nx]!='#':
        if maze[ny][nx]=='.':
          maze[ny][nx]=T+1
          qu.append([ny,nx])
        elif maze[ny][nx]>T+1:
          maze[ny][nx]=T+1
          qu.append([ny,nx])
          
  if maze[gy][gx]!='.':
    return maze[gy][gx]
  else:
    return -Inf
  
inf=float('inf')
ans=-inf
for i in range(h):
  for j in range(w):
    if maze1[i][j]=='.':
      for x in range(h):
        for y in range(w):
          if maze1[x][y]=='.':
            maze2=copy.deepcopy(maze1)
            
            ans=max(ans,maze_solve(maze2,i,j,x,y))
            
            
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
l_count=[[0]*W for i in range(H)]
from collections import deque
def answer(st_X,st_Y):#X,Y座標を指定してそこからの距離を考える
   tmp_X,tmp_Y=st_X,st_Y
   que=deque([[tmp_X,tmp_Y]])
   after=[]
   while que:#スタート地点からの距離を数えながら行ったことのない場所を探索する
      tmp_X,tmp_Y=que.popleft()
      nu=l_count[tmp_Y][tmp_X]
      after.append([tmp_X,tmp_Y])
      if tmp_X>0 and l[tmp_Y][tmp_X-1]=="." and [tmp_X-1,tmp_Y] not in after and [tmp_X-1,tmp_Y] not in que:
         l_count[tmp_Y][tmp_X-1]=nu+1
         que.append([tmp_X-1,tmp_Y])
      if tmp_Y>0 and l[tmp_Y-1][tmp_X]=="." and [tmp_X,tmp_Y-1] not in after and [tmp_X,tmp_Y-1] not in que:
         l_count[tmp_Y-1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y-1])
      if tmp_X<W-1 and l[tmp_Y][tmp_X+1]=="." and [tmp_X+1,tmp_Y] not in after and [tmp_X+1,tmp_Y] not in que:
         l_count[tmp_Y][tmp_X+1]=nu+1
         que.append([tmp_X+1,tmp_Y])
      if tmp_Y<H-1 and l[tmp_Y+1][tmp_X]=="." and [tmp_X,tmp_Y+1] not in after and [tmp_X,tmp_Y+1] not in que:
         l_count[tmp_Y+1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y+1])
ans=0
for i in range(H):
   for j in range(W):
      if l[i][j]==".":
         l_count=[[0]*W for i in range(H)]
         answer(j,i)
         tmp=max(sum(l_count,[]))
         ans=max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    H, W = list(map(int, input().split()))
    maps =[list(input()) for _ in range(H)]
    mv = {(1, 0), (-1, 0), (0, 1), (0, -1)}

    ans = 0
    for i in range(H):
        for j in range(W):
            if maps[i][j] == '#':
                continue
            stk = deque([[i,j,0]])
            seen = [[False]*W for _ in range(H)]
            while len(stk) > 0:
                l = stk.pop()
                i = l[0]
                j = l[1]
                ct = l[2]
                seen[i][j] = True
                for k in mv:
                    x = i+k[0]
                    y = j+k[1]
                    if 0 <= x < H and 0 <= y < W and \
                        maps[x][y] == '.' and seen[x][y] == False:
                            stk.appendleft([x, y, ct+1])
            ans = max(ans, ct)
    print(ans)

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
l_count=[[0]*W for i in range(H)]
from collections import deque
def answer(st_X,st_Y):#X,Y座標を指定してそこからの距離を考える
   tmp_X,tmp_Y=st_X,st_Y
   que=deque([[tmp_X,tmp_Y]])
   after=[]
   while que:#スタート地点からの距離を数えながら行ったことのない場所を探索する
      tmp_X,tmp_Y=que.popleft()
      nu=l_count[tmp_Y][tmp_X]
      after.append([tmp_X,tmp_Y])
      if tmp_X>0 and l[tmp_Y][tmp_X-1]=="." and [tmp_X-1,tmp_Y] not in after:
         l_count[tmp_Y][tmp_X-1]=nu+1
         que.append([tmp_X-1,tmp_Y])
      if tmp_Y>0 and l[tmp_Y-1][tmp_X]=="." and [tmp_X,tmp_Y-1] not in after:
         l_count[tmp_Y-1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y-1])
      if tmp_X<W-1 and l[tmp_Y][tmp_X+1]=="." and [tmp_X+1,tmp_Y] not in after:
         l_count[tmp_Y][tmp_X+1]=nu+1
         que.append([tmp_X+1,tmp_Y])
      if tmp_Y<H-1 and l[tmp_Y+1][tmp_X]=="." and [tmp_X,tmp_Y+1] not in after:
         l_count[tmp_Y+1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y+1])
   que=deque(set(que))
ans=0
for i in range(H):
   for j in range(W):
      if l[i][j]==".":
         l_count=[[0]*W for i in range(H)]
         answer(j,i)
         tmp=max(sum(l_count,[]))
         ans=max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
l_count=[[0]*W for i in range(H)]
from collections import deque
def answer(st_X,st_Y):#X,Y座標を指定してそこからの距離を考える
   tmp_X,tmp_Y=st_X,st_Y
   que=deque([[tmp_X,tmp_Y,0]])
   after=deque([])
   while que:#スタート地点からの距離を数えながら行ったことのない場所を探索する
      tmp_X,tmp_Y,nu=que.popleft()
      after.append([tmp_X,tmp_Y])
      if tmp_X>0 and l[tmp_Y][tmp_X-1]=="." and [tmp_X-1,tmp_Y] not in after and [tmp_X-1,tmp_Y] not in que:
         l_count[tmp_Y][tmp_X-1]=nu+1
         que.append([tmp_X-1,tmp_Y,nu+1])
      if tmp_Y>0 and l[tmp_Y-1][tmp_X]=="." and [tmp_X,tmp_Y-1] not in after and [tmp_X-1,tmp_Y] not in que:
         l_count[tmp_Y-1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y-1,nu+1])
      if tmp_X<W-1 and l[tmp_Y][tmp_X+1]=="." and [tmp_X+1,tmp_Y] not in after and [tmp_X-1,tmp_Y] not in que:
         l_count[tmp_Y][tmp_X+1]=nu+1
         que.append([tmp_X+1,tmp_Y,nu+1])
      if tmp_Y<H-1 and l[tmp_Y+1][tmp_X]=="." and [tmp_X,tmp_Y+1] not in after and [tmp_X-1,tmp_Y] not in que:
         l_count[tmp_Y+1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y+1,nu+1])
ans=0
for i in range(H):
   for j in range(W):
      if l[i][j]==".":
         l_count=[[0]*W for i in range(H)]
         answer(j,i)
         tmp=max(sum(l_count,[]))
         ans=max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W=list(map(int,input().split()))
l=[list(input()) for i in range(H)]
l_count=[[0]*W for i in range(H)]
from collections import deque
def answer(st_X,st_Y):#X,Y座標を指定してそこからの距離を考える
   tmp_X,tmp_Y=st_X,st_Y
   que=deque([[tmp_X,tmp_Y,0]])
   after=deque([])
   while que:#スタート地点からの距離を数えながら行ったことのない場所を探索する
      tmp_X,tmp_Y,nu=que.popleft()
      after.append([tmp_X,tmp_Y])
      if tmp_X>0 and l[tmp_Y][tmp_X-1]=="." and [tmp_X-1,tmp_Y] not in after:
         l_count[tmp_Y][tmp_X-1]=nu+1
         que.append([tmp_X-1,tmp_Y,nu+1])
      if tmp_Y>0 and l[tmp_Y-1][tmp_X]=="." and [tmp_X,tmp_Y-1] not in after:
         l_count[tmp_Y-1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y-1,nu+1])
      if tmp_X<W-1 and l[tmp_Y][tmp_X+1]=="." and [tmp_X+1,tmp_Y] not in after:
         l_count[tmp_Y][tmp_X+1]=nu+1
         que.append([tmp_X+1,tmp_Y,nu+1])
      if tmp_Y<H-1 and l[tmp_Y+1][tmp_X]=="." and [tmp_X,tmp_Y+1] not in after:
         l_count[tmp_Y+1][tmp_X]=nu+1
         que.append([tmp_X,tmp_Y+1,nu+1])
ans=0
for i in range(H):
   for j in range(W):
      if l[i][j]==".":
         l_count=[[0]*W for i in range(H)]
         answer(j,i)
         tmp=max(sum(l_count,[]))
         ans=max(ans,tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
maze = [input() for i in range(H)]
start_candidate = []
'''
. , #
'''

from collections import deque

direction = [
    (-1, 0),
    (0, -1),
    (1, 0),
    (0, 1)
]


def bfs(si, sj, gi, gj):
    reached = [[-1] * W for i in range(H)]
    reached[si][sj] = 0
    que = deque([[si, sj]])
    while que:
        i, j = que.popleft()
        for vi, vj in direction:
            ti, tj = i + vi, j + vj
            if ti < 0 or tj < 0 or ti > H - 1 or tj > W - 1:
                continue
            if maze[ti][tj] == '#' or reached[ti][tj] != -1:
                continue
            reached[ti][tj] = reached[i][j] + 1
            que.append([ti, tj])
        if reached[gi][gj] != -1:
            break
    return reached[gi][gj]


for i in range(H):
    for j in range(W):
        if maze[i][j] != '#':
            start_candidate.append([i, j])

from itertools import combinations

ans = 0
for c in combinations(start_candidate, 2):
    ans = max(ans, bfs(c[0][0], c[0][1], c[1][0], c[1][1]))
print(ans)

Submission status: Time Limit Exceeded

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

mv = {(1, 0), (-1, 0), (0, 1), (0, -1)}


def BFS(St):
    stk = deque([St+[0]])
    seen = [[False]*W for _ in range(H)]
    while len(stk) > 0:
        l = stk.pop()
        i = l[0]
        j = l[1]
        ct = l[2]
        seen[i][j] = True
        for k in mv:
            x = i+k[0]
            y = j+k[1]
            if 0 <= x < H and 0 <= y < W:
                if S[x][y] == '.' and seen[x][y] == False:
                    stk.appendleft([x, y, ct+1])
    else:
        return(ct)


# print(BFS([2, 0], [0, 4]))


ans = 0
# 各スタート地点に対して最大距離を出力すればいいですねって話

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        ans=max(ans,BFS([i,j]))
print(ans)

Submission status: Time Limit Exceeded

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

mv = {(1, 0), (-1, 0), (0, 1), (0, -1)}


def BFS(St, G):
    stk = deque([St+[0]])
    seen = [[False]*W for _ in range(H)]
    while len(stk) > 0:
        l = stk.pop()
        i = l[0]
        j = l[1]
        ct = l[2]
        seen[i][j] = True
        if i == G[0] and j == G[1]:
            return ct
        for k in mv:
            x = i+k[0]
            y = j+k[1]
            if 0 <= x < H and 0 <= y < W:
                if S[x][y] == '.' and seen[x][y] == False:
                    stk.appendleft([x, y, ct+1])


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, j) == (k, l):
                    continue
                ans = max(ans, BFS([i, j], [k, l]))
                # print(ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50

def bfs(MAZE, start, seen):
    queue = deque([start + (0 ,)])
    max_count = 0
    while queue:
        y,x,count = queue.popleft()
        max_count = max(max_count, count)
        seen.add((y, x))
        for i,j in ((0,1), (0,-1), (1,0), (-1, 0)):
            next_y, next_x = y + i, x + j
            #print(next_y, next_x)
            if not (next_y, next_x) in seen and MAZE[next_y][next_x] == '.':
                queue.append((next_y, next_x, count+1))
                #seen.add((next_y, next_x))
    return max_count


def run():
    H, W = map(int, input().split())
    MAZE = ['#' * (W+2)]
    for _ in range(H):
        s = input()
        s = '#' + s + '#'
        MAZE.append(s)
    MAZE.append('#' * (W+2))

    #for m in MAZE:
    #    print(m)

    ways = []
    for i in range(1, H+1):
        for j in range(1, W+1):
            if MAZE[i][j] == '.':
                ways.append((i, j))

    max_count = 0
    for s_i, s_j in ways:
        seen = set((s_i, s_j))
        min_count = bfs(MAZE, (s_i, s_j), seen)
        #print((s_i, s_j), '->', (g_i, g_j))
        #print(min_count)
        max_count = max(max_count, min_count)

    print(max_count)

if __name__ == "__main__":
    run()