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.

Solution (Python):
from collections import deque
from itertools import product

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

points = [(y, x) for y, x in product(range(H), range(W)) if maze[y][x] == '.']

ans = 0
for sy, sx in points:
    costs = {}
    queue = deque()
    queue.append((sy, sx, 0))
    while queue:
        y, x, cost = queue.popleft()
        if (y, x) in costs:
            continue
        else:
            costs[(y, x)] = cost

        for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
            if not 0 <= ny < H:
                continue
            if not 0 <= nx < W:
                continue
            if (ny, nx) in costs:
                continue
            if maze[ny][nx] == '
                continue
            queue.append((ny, nx, cost + 1))

    ans = max(ans, max(costs.values()))

print(ans)

Solution (Python):
from collections import Counter, defaultdict
import sys

sys.setrecursionlimit(10 ** 5 + 10)
input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
from copy import deepcopy
import queue
from collections import deque


def maxload(data_copy, i, j, high, width):
    data = deepcopy(data_copy)
    count = 0
    now_point = set()
    now_point.add((i, j))
    next_point = set()

    move = [[1, 0], [0, 1], [-1, 0], [0, -1]]

    while len(now_point):
        for now_i, now_j in now_point:
            data[now_i][now_j] = count
            for move_i, move_j in move:
                next_i, next_j = now_i + move_i, now_j + move_j
                if next_i < 0 or next_i >= high or next_j < 0 or next_j >= width:
                    continue
                if data[next_i][next_j] != ".":
                    continue
                next_point.add((next_i, next_j))

        now_point = next_point
        next_point = set()
        count += 1

    return count - 1



def main():
    high, width = map(int, input().split())
    data = [list(input()) for i in range(high)]

    ans = 0

    for i in range(high):
        for j in range(width):
            if data[i][j] == "
                continue
            ans = max(ans, maxload(data, i, j, high, width))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from math import ceil,floor,comb,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

def bfs():
    d = [[inf]*w for i in range(h)]

    dy = [0, 1, 0, -1]
    dx = [1, 0, -1, 0]
 
    que = deque([])
    que.append((sy, sx))
    d[sy][sx] = 0
    ret = 0
 
    while que:
        p = que.popleft()
        for i in range(4):
            ny = p[0] + dy[i]
            nx = p[1] + dx[i]
 
            if 0 <= ny < h and 0 <= nx < w and maze[ny][nx] != '
                que.append((ny,nx))
                d[ny][nx] = d[p[0]][p[1]] + 1
                ret = max(ret, d[ny][nx])
 
    return ret

h, w = MAP()
maze = [input() for i in range(h)]
ans = 0

for sy in range(h):
    for sx in range(w):
        if maze[sy][sx] == '
            continue
        else:
            ans = max(ans, bfs())

print(ans)

Solution (Python):
import collections

h,w = map(int,input().split())
field = [["

field.append(["
field.insert(0,["

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

def f():
    global ans
    s = q.popleft()
    y,x = s[0],s[1]
    for i in range(4):
        newy = y+dy[i]
        newx = x+dx[i]
        if field[newy][newx] == "." and memo[newy][newx] == "
            q.append((newy,newx))
            memo[newy][newx] = memo[y][x] + 1
            ans = max(ans,memo[y][x] + 1)

ans = 0
for i in range(1,h+1):
    for j in range(1,w+1):
        if field[i][j] == "
            continue
        q = collections.deque()
        q.append((i,j))
        memo = [["
        memo[i][j] = 0
        while q:
            f()

print(ans)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
field = ''
for i in range(H):
    field += input()

def bfs(start):
    dist = [0] * (H * W)
    q = deque([start])
    while q:
        p = q.popleft()
        c = dist[p] + 1
        if p - W != start and p - W >= 0 and field[p - W] == '.' and dist[p - W] == 0:
            dist[p - W] = c
            q.append(p - W)
        if p + W != start and p + W < H * W and field[p + W] == '.' and dist[p + W] == 0:
            dist[p + W] = c
            q.append(p + W)
        if p - 1 != start and p - 1 >= 0 and field[p - 1] == '.' and dist[p - 1] == 0 and p % W != 0:
            dist[p - 1] = c
            q.append(p - 1)
        if p + 1 != start and p + 1 < H * W and field[p + 1] == '.' and dist[p + 1] == 0 and p % W != W - 1:
            dist[p + 1] = c
            q.append(p + 1)
    return dist[p]

ans = 0
for s in range(H * W):
    if field[s] == '.':
        ans = max(ans, bfs(s))
print(ans)

Solution (Python):
import numpy as np
H, W = map(int, input().split())
map_lis = [input() for i in range(H)]
ans = 0

def prob(x,y,h,w):
  if 0<=x<h and 0<=y<w:
    return True
  else:
    return False

def count(x,y,lis):
  if not lis[x][y]:
    return True
  else:
    return False

def maze(x,y,lis):
  if lis[x][y] == ".":
    return True
  else:
    return False

for i in range(H):
  for j in range(W):
    k = 0
    count_lis = np.zeros((H,W))
    num_lis = [[] for i in range(1000)]
    if maze(i,j,map_lis):
      count_lis[i][j] = 1
      num_lis[0].append([i,j])
    while True:
      for l in num_lis[k]:
        if prob(l[0]-1,l[1],H,W) and count(l[0]-1,l[1],count_lis) and maze(l[0]-1,l[1],map_lis):
          num_lis[k+1].append([l[0]-1,l[1]])
          count_lis[l[0]-1][l[1]] = 1
        if prob(l[0],l[1]-1,H,W) and count(l[0],l[1]-1,count_lis) and maze(l[0],l[1]-1,map_lis):
          num_lis[k+1].append([l[0],l[1]-1])
          count_lis[l[0]][l[1]-1] = 1
        if prob(l[0]+1,l[1],H,W) and count(l[0]+1,l[1],count_lis) and maze(l[0]+1,l[1],map_lis):
          num_lis[k+1].append([l[0]+1,l[1]])
          count_lis[l[0]+1][l[1]] = 1
        if prob(l[0],l[1]+1,H,W) and count(l[0],l[1]+1,count_lis) and maze(l[0],l[1]+1,map_lis):
          num_lis[k+1].append([l[0],l[1]+1])
          count_lis[l[0]][l[1]+1] = 1
      new_ans = 0
      for m in num_lis[1:]:
        if m != []:
          new_ans += 1
        if m == []:
          break
      ans = max(ans, new_ans)
      k += 1
      if num_lis[k] == []:
        break
                                     
print(ans)

Solution (Python):
from collections import deque
import numpy as np
H,W = map(int,input().split())
maze = [input() for _ in range(H)]
ans = 0
for x in range(H):
  for y in range(W):
    if maze[x][y]=='
      continue
    dist = [[0]*W for i in range(H)]
    Q = deque([[x,y]])
    while Q:
      h,w = Q.popleft()
      for i,j in [[1,0],[-1,0],[0,1],[0,-1]]:
        h2,w2 = h+i,w+j
        if 0<=h2<H and 0<=w2<W and dist[h2][w2]==0 and maze[h2][w2]!='
          dist[h2][w2] = dist[h][w]+1
          Q.append([h2,w2])
    dist[x][y] = 0
    ans = max(ans, np.max(dist))
print(ans)

Solution (Python):
import numpy as np
from collections import deque
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
ans = 0
for i in range(len(s)):
    for j in range(len(s[0])):
        if s[i][j] == '
            continue
        pre = 0
        p = np.full((h, w), -1)
        p[i][j] = 0
        check = deque([((i, j), 0)])
        while check:
            now, d = check.popleft()
            pre = max(pre, d)
            for k, l in [(1,0), (-1,0),(0,1), (0,-1)]:
                b = now[0] + k
                c = now[1] + l
                if b < 0 or c < 0 or b >= h or c >= w:
                    continue 
                elif p[b][c] == -1 and s[b][c] != '
                    check.append(((b, c), d + 1))
                    p[b][c] = d + 1
        ans = max(ans, pre)

print(ans)

Solution (Python):
from collections import deque

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

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

dist = [[-1] * W for _ in range(H)]

def BFS(y, x):
  """(y, x)からはじめて、道のマスをBFSで最短距離を探す"""
  que = deque()
  que.append((y, x))
  dist[y][x] = 0
  max_dist = 0
  while que:
    sy, sx = que.popleft()  
    for dy, dx in dir:
      ny = sy + dy
      nx = sx + dx
      if 0 <= ny < H and 0 <= nx < W and S[ny][nx] != "
        que.append((ny, nx))
        dist[ny][nx] = dist[sy][sx] + 1
        max_dist = max(max_dist, dist[ny][nx])
  
  return max_dist

max_dist = 0
for sy in range(H):
  for sx in range(W):
    if S[sy][sx] != "
      dist = [[-1] * W for _ in range(H)]
      max_dist = max(max_dist, BFS(sy, sx))

print(max_dist)

Solution (Python):
from collections import deque

H,W=map(int,input().split())
S=[]
for i in range(H):
  S.append(input())
  
def bfs(s):
  seen = [[0 for i in range(W)] for j in range(H)]
  total = [[0 for i in range(W)] for j in range(H)]
  todo = deque([])
  now = s
  if S[now[0]][now[1]]=='
  seen[now[0]][now[1]],total[now[0]][now[1]] = 1,0
  todo.append(now)
  while 1:
    if len(todo)==0:break
    now = todo.popleft()
    for d in [(1,0),(-1,0),(0,1),(0,-1)]:
      new = (now[0]+d[0], now[1]+d[1])
      if new[0]<0 or new[0]>=H:continue
      if new[1]<0 or new[1]>=W:continue
      if seen[new[0]][new[1]]==1:continue
      if S[new[0]][new[1]]=='
      seen[new[0]][new[1]] = 1
      todo.append(new)
      total[new[0]][new[1]] = total[now[0]][now[1]] + 1
  return max(map(max, total))

MAX=0
for i in range(H):
  for j in range(W):
    s = (i,j)
    max_ = bfs(s)
    if MAX < max_:MAX=max_

print(MAX)

Solution (Python):
from collections import deque
h, w = map(int, input().split())
chiz = [[] for _ in range(w)]
for _ in range(h):
    tmp_list = input()
    for i in range(w):
        chiz[i].append(tmp_list[i])
def bfs(i,j):
    ds = [[-1]*h for _ in range(w)]
    dq = deque([(i,j)])
    ds[i][j] = 0
    res = -1
    while dq:
        i,j = dq.popleft()
        for move in [(1,0),(-1,0),(0,-1),(0,1)]:
            if i+move[0] >= 0 and i+move[0] < w and j+move[1] >= 0 and j+move[1] < h:
                if chiz[i+move[0]][j+move[1]]=='.' and ds[i+move[0]][j+move[1]] == -1:
                    ds[i + move[0]][j + move[1]] = ds[i][j] + 1
                    res = max(res,ds[i + move[0]][j + move[1]])
                    dq.append((i + move[0],j + move[1]))
    return res
res = -1
for j in range(h):
    for i in range(w):
        if chiz[i][j]=='.':
            res = max(res, bfs(i,j))
print(res)

Solution (Python):
from collections import deque
m=[[1,0],[-1,0],[0,1],[0,-1]]
h,w=map(int,input().split())
l=list()
l.append('
for i in range(h):
    j=input()
    l.append('
l.append('
def bfs(a,b):
  s=[[-1 for j in i] for i in l]
  s[a][b]=0
  q=deque([[a,b]])
  while len(q)>0:
    x,y=q.popleft()
    for i,j in m:
      if l[x+i][y+j]=='.' and s[x+i][y+j]==-1:
        q.append([x+i,y+j])
        s[x+i][y+j]=s[x][y]+1
        num = s[x+i][y+j]
  return num
ans = []
for i in range(h+2):
  for j in range(w+2):
    if l[i][j] == '.':
      ans.append(bfs(i,j))
print(max(ans))

Solution (Python):


"""
https://atcoder.jp/contests/abc151/tasks/abc151_d
Maze Master.
"""

from collections import deque
from copy import deepcopy

def bfs(chw, i, j):
    dq = deque()

    dq.append([i, j])
    chw[i][j] = '

    dist = [[-1 for _ in range(w)] for _ in range(h)]
    dist[i][j] = 0

    

    while dq:
        y, x = dq.popleft()
        for dy, dx in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
            ny = y+dy
            nx = x+dx
            if 0 <= nx < w and 0 <= ny < h and chw[ny][nx] == '.':
                dq.append([ny, nx])
                chw[ny][nx] = '
                dist[ny][nx] = dist[y][x]+1

    
    temp_ans = 0
    for each in dist:
        temp_ans = max(temp_ans, max(each))

    return temp_ans



def solve(h, w, hw):
    ans = 0
    for i in range(h):
        for j in range(w):
            if hw[i][j] == '.':
                chw = deepcopy(hw)
                dist = bfs(chw, i, j)
                ans = max(dist, ans)
    return ans

if __name__ == "__main__":
    h, w = list(map(int, input().split(" ")))
    hw = [list(input()) for _ in range(h)]
    print(solve(h, w, hw))

Solution (Python):
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    H, W = NMI()
    grid = [SI() for _ in range(H)]
    DH = [-1, 1, 0, 0]
    DW = [0, 0, -1, 1]

    def bfs(sh, sw):
        queue = deque()
        seen = make_grid(H, W, -1)
        queue.append([sh, sw])
        seen[sh][sw] = 0
        while queue:
            now_h, now_w = queue.popleft()
            for dh, dw in zip(DH, DW):
                next_h = now_h + dh
                next_w = now_w + dw
                if not(0 <= next_h < H and 0 <= next_w < W):
                    continue
                if seen[next_h][next_w] != -1 or grid[next_h][next_w] == "
                    continue
                queue.append([next_h, next_w])
                seen[next_h][next_w] = seen[now_h][now_w] + 1

        return max([max(l) for l in seen])

    ans = 0
    for h in range(H):
        for w in range(W):
            if grid[h][w] == ".":
                ans = max(ans, bfs(h, w))
    print(ans)




if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
h, w = map(int, input().split())
G = [list(input()) for _ in range(h)]
go = [[0,1], [1,0], [0,-1], [-1,0]]

ans = 0

for hi in range(h):
    for wi in range(w):
        
        if G[hi][wi] =='
            continue
        
        
        dist = [[-1]*w for _ in range(h)]
        
        dist[hi][wi] = 0
        
        que = deque([[hi,wi]])
        
        
        while que:
            
            nowhi, nowwi = que.pop()
            
            for dh, dw in go:
                
                if not ((0<=nowhi+dh<=h-1) and (0<=nowwi+dw<=w-1)):
                    continue
                
                if G[nowhi+dh][nowwi+dw]=='
                    continue
                
                if dist[nowhi+dh][nowwi+dw]!=-1:
                    continue
                
                dist[nowhi+dh][nowwi+dw] = dist[nowhi][nowwi]+1
                
                que.appendleft([nowhi+dh, nowwi+dw])
        
        ans = max(ans, max([max(d) for d in dist]))
print(ans)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from copy import deepcopy
from collections import deque

h,w=nii()
s=[list(input()) for i in range(h)]

def dfs(cs,i,j):
  que=deque()
  que.append([i,j])

  cs[i][j]='

  dist=[[-1 for a in range(w)] for b in range(h)]
  dist[i][j]=0

  while que:
    y,x=que.popleft()
    for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
      ny=y+dy
      nx=x+dx
      if 0<=ny<h and 0<=nx<w and cs[ny][nx]=='.':
        que.append([ny,nx])
        cs[ny][nx]='
        dist[ny][nx]=dist[y][x]+1

  t_ans=0
  for a in dist:
    t_ans=max(t_ans,max(a))

  return t_ans

ans=0
for i in range(h):
  for j in range(w):
    if s[i][j]=='.':
      cs=deepcopy(s)
      dist=dfs(cs,i,j)
      ans=max(ans,dist)

print(ans)

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

Solution (Python):
from collections import deque
import copy
H,W= map(int, input().split())
c=[list(input()) for i in range(H)]

max_num=0
move=[[0,1],[0,-1],[1,0],[-1,0]]
for h in range(H):
    for w in range(W):
        if c[h][w]=='.':
            
            L=copy.deepcopy(c)
            d=deque([[h,w]])
            L[h][w]='S'

            num=0
            while d:
                num+=1
                for i in range(len(d)):
                    q=d.popleft()
                    for m in move:
                        if 0<=q[0]+m[0]<=H-1 and 0<=q[1]+m[1]<=W-1 and L[q[0]+m[0]][q[1]+m[1]]=='.':
                            L[q[0]+m[0]][q[1]+m[1]]=num

                            d.append([q[0]+m[0],q[1]+m[1]])

           
            if num-1>=max_num:
                max_num=num-1
print(max_num)

Solution (Python):
from copy import deepcopy
from collections import deque
h,w=map(int,input().split())
ss=[]
u=[(-1,0),(1,0),(0,1),(0,-1)]
ans=0
for i in range(h):
    ss.append(list(input()))
for i in range(h):
    for j in range(w):
        s=deepcopy(ss)
        if s[i][j]=="
            continue
        if s[i][j]==".":
            tmp=0
            x,y=i,j
            s[x][y]=0
            que=deque()
            que.append([x,y])
            while que:
                x,y=que.popleft()
                for xx,yy in u:
                    nx,ny=x+xx,y+yy
                    if 0<=nx<h and 0<=ny<w:
                        if s[nx][ny]==".":
                            s[nx][ny]=s[x][y]+1
                            if tmp<s[nx][ny]:
                                tmp=s[nx][ny]
                            que.append([nx,ny])
        if tmp>ans:
            ans=tmp
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
INF = 1001001001
from collections import deque

def linput(ty=int, cvt=list):
	return cvt(map(ty,input().split()))

def pad(mxy, wall="
	w = len(mxy[0])
	gp = wall*(w+2)
	re = [gp,]
	re_app = re.append
	for vx in mxy:
		re_app(wall+vx+wall)
	re_app(gp)
	return re

vD = [(0,1),(1,0),(0,-1),(-1,0)]
vQ = deque([])
vQ_app, vQ_popl = vQ.append, vQ.popleft

def main():
	H,W = linput()
	mM = [input().rstrip() for _ in [0,]*H]
	mM = pad(mM)
	
	res = 0
	cnt = 0
	
	for sr in range(1,H+1):
		for sc in range(1,W+1):
			if mM[sr][sc]=="
				continue
			mV = [[INF,]*(W+2) for _ in [INF,]*(H+2)]
			mV[sr][sc] = 0
			vQ_app((sr,sc))
			while vQ:
				r,c = vQ_popl()
				now_cost = mV[r][c]
				for dr,dc in vD:
					nr,nc = r+dr, c+dc
					if mM[nr][nc]=="
						continue
					if now_cost + 1 < mV[nr][nc]:
						vQ_app((nr,nc))
						mV[nr][nc] = now_cost + 1
						res = max(now_cost+1, res)
		
				cnt += 1
				
				if cnt>999999: break
	
	print(res)

if __name__ == "__main__":
	main()

Solution (Python):

from collections import defaultdict, deque, Counter, OrderedDict
from functools import reduce, lru_cache
import collections, heapq, itertools, bisect
import math, fractions
import sys, copy

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline().rstrip())
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def S(): return list(sys.stdin.readline().rstrip())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
MOD = 1000000007

def main():
    H, W = LI()
    maze = SR(H)

    ans = 0
    for h in range(H):
        for w in range(W):
            if maze[h][w] == '
                continue

            q = deque()
            q.append((0, h, w))

            visited = [[False] * W for _ in range(H)]
            visited[h][w] = True

            while q:
                dist, y, x = q.popleft()

                for dy, dx in dire:
                    if y + dy >= 0 and y + dy < H and x + dx >= 0 and x + dx < W:
                        if maze[y + dy][x + dx] == '.' and not visited[y + dy][x + dx]:
                            q.append((dist + 1, y + dy, x + dx))
                            visited[y + dy][x + dx] = True

            ans = max(ans, dist)

    print(ans)

if __name__ == '__main__':
    main()

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

import queue, itertools

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

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

print(ans)

Solution (Python):
h, w = map(int, input().split())
ma = [ list(input()) for _ in range(h) ]
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
ans = 0

def bfs(sy, sx):
    if ma[sy][sx] == "
        return 0
    q = [[sy, sx, 0]]
    flag = [[0] * w for _ in range(h)]
    flag[sy][sx] = 1
    ans = 0
    while True:
        if len(q) == 0:
            break
        y, x, dist = q.pop(0)
        for dy, dx in d:
            if 0 <= y + dy < h and 0 <= x + dx < w and flag[y + dy][x + dx] == 0 and ma[y + dy][x + dx] == ".":
                flag[y + dy][x + dx] = 1
                q.append([y + dy, x + dx, dist + 1])
                ans = max(ans, dist + 1)

    return ans


for j in range(h):
    for i in range(w):
        ans = max(ans, bfs(j, i))

print(ans)

Solution (Python):
import math
from collections import deque

H, W = [int(_) for _ in input().split()]

S = [list(input()) for _ in range(H)]


def f(h, w):
    memo = [[-1] * W for _ in range(H)]
    lst = deque()
    lst.append((h, w, 0))
    res = 0
    while lst:
        h, w, c = lst.popleft()
        if memo[h][w] >= c: continue
        memo[h][w] = c
        res = max(c, res)
        for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            nh = x + h
            nw = y + w
            if nh < 0 or nh >= H: continue
            if nw < 0 or nw >= W: continue
            if memo[nh][nw] > -1: continue
            if S[nh][nw] == '
            lst.append((nh, nw, c + 1))

    return res

def main():
    ans = 0
    for h in range(H):
        for w in range(W):
            if S[h][w] == '
            ans = max(ans,f(h,w))
    return ans
print(main())

Solution (Python):
import sys
from io import StringIO
import unittest
import os
from collections import deque


sys.setrecursionlimit(999999999)



def resolve(test_def_name=""):
    
    
    
    
    
    

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

    start_list = []
    for i_len, i in enumerate(range(h)):
        for j_len, j in enumerate(range(w)):
            route = 4
            
            if maze[i][j] == "
                continue

            
            route -= 1 if i_len == 0 else 0
            route -= 1 if i_len + 1 == h else 0
            
            route -= 1 if not i_len == 0 and maze[i - 1][j] == "
            route -= 1 if not i_len + 1 == h and maze[i + 1][j] == "
            
            route -= 1 if j_len == 0 else 0
            route -= 1 if j_len + 1 == w else 0
            
            route -= 1 if not j_len == 0 and maze[i][j - 1] == "
            route -= 1 if not j_len + 1 == w and maze[i][j + 1] == "
            if route <= 2:
                start_list.append((i, j))

    ans = 0
    que = deque()
    for start in start_list:
        que.appendleft(start)
        ed_list = [[-1 for i in range(w)] for j in range(h)]
        ed_list[start[0]][start[1]] = 0

        
        while len(que) is not 0:
            now = que.pop()

            
            for i, j in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
                
                target = [now[0] + i, now[1] + j]

                
                
                if not 0 <= target[0] < h or not 0 <= target[1] < w:
                    continue

                
                if ed_list[target[0]][target[1]] != -1:
                    continue

                
                if maze[target[0]][target[1]] == "
                    continue

                
                
                que.appendleft(target)
                
                ed_list[target[0]][target[1]] = ed_list[now[0]][now[1]] + 1
                ans = max(ans, ed_list[target[0]][target[1]])

    print(ans)



class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3 3
...
...
..."""
        output = """4"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """3 5
...
.
.
        output = """10"""
        self.assertIO(test_input, output)

    
    def test_1original_1(self):
        test_input = """1 2
.."""
        output = """1"""
        self.assertIO(test_input, output)



if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        
        resolve()

    else:
        
        unittest.main()

Solution (Python):

from collections import deque
H, W = map(int, input().split())
dif = [(-1, 0), (1, 0), (0, 1), (0, -1)]
Map = [list(input()) for i in range(H)]
visited = [[False for i in range(W)] for j in range(H)]
deq = deque()


def bfs(node):
    nx, ny = node
    deq.append(node)

    visited[nx][ny] = True
    distance = [[float("inf") for i in range(W)] for j in range(H)]
    distance[nx][ny] = 0
    while deq:
        x, y = deq.popleft()
        for dx, dy in dif:
            if 0 <= x+dx < H and 0 <= y+dy < W and Map[x+dx][y+dy] == "." and visited[x+dx][y+dy] == False:
                visited[x+dx][y+dy] = True
                distance[x+dx][y+dy] = distance[x][y]+1
                deq.append((x+dx, y+dy))
    return distance


def s_bfs(node):
    nx, ny = node
    deq.append(node)
    Visited = [[False for i in range(W)] for j in range(H)]
    Visited[nx][ny] = True
    distance = [[float("inf") for i in range(W)] for j in range(H)]
    distance[nx][ny] = 0
    while deq:
        x, y = deq.popleft()
        for dx, dy in dif:
            if 0 <= x+dx < H and 0 <= y+dy < W and Map[x+dx][y+dy] == "." and Visited[x+dx][y+dy] == False:
                Visited[x+dx][y+dy] = True
                distance[x+dx][y+dy] = distance[x][y]+1
                deq.append((x+dx, y+dy))
    return distance


ans = 1
roads = deque()
for i in range(H):
    for j in range(W):
        if Map[i][j] == ".":
            roads.append((i, j))

while roads:
    x, y = roads.popleft()
    if visited[x][y] == False:
        B = s_bfs((x, y))
        s = -1
        choice=[]
        most_far_distance = 0
        for i in range(H):
            for j in range(W):
                if B[i][j] != float("inf") and B[i][j] > most_far_distance:
                    most_far_distance = B[i][j]
        for i in range(H):
            for j in range(W):
                if B[i][j] == most_far_distance:
                    choice.append((i, j))

        for s in choice:
            C = s_bfs(s)
            for i in range(H):
                for j in range(W):
                    if C[i][j] != float("inf"):
                        ans = max(ans, C[i][j])
print(ans)