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):
import sys
from collections import deque

input = sys.stdin.readline
H,W=map(int,input().rstrip().split())
maze=[list(input().rstrip()) for i in range(H)]
def resolve():
    seen=[[0 for i in range(W)] for j in range(H)]
    ans=0
    for i in range(H):
        for j in range(W):
            if maze[i][j]=="
                continue
            
            buf=bfs(maze,seen,i,j)
            ans=max(ans,buf)
            seen = [[0 for i in range(W)] for j in range(H)]
            
    print(ans)

def bfs(maze, seen, sh, sw): 
    stack = deque([[sh, sw]])
    seen[sh][sw] = 1
    expandcount=0
    expanded=-1
    popcount=0
    depth=0
    while stack:
        h, w = stack.popleft()
        popcount+=1
        
        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] != "
                seen[new_h][new_w] = 1
                stack.append([new_h, new_w])
                expandcount+=1

        if popcount==expanded or expanded==-1:
            expanded=expandcount
            popcount=0
            expandcount=0
            depth+=1

    return depth-1
"""
    for i in range(H):
        for j in range(W):
            if(S[i][j]=="
                for dir in range(4):
                    nx=j+dx[dir]
                    ny=i+dy[dir]

                    if(nx<0 or nx>=W):
                        continue
                    if(ny<0 or ny>=H):
                        continue

                    if(S[i][j]==S[ny][nx]):
                        break
                else:
                    print("No")
                    return
    print("Yes")
"""
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3 3
...
...
..."""
        output = """4"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """3 5
...
.
.
        output = """10"""
        self.assertIO(input, output)

if __name__ == "__main__":
    
    resolve()

Solution (Python):
import queue
import sys

input = sys.stdin.readline


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

        for i in range(H):
            S[i] = ["
        S = [["

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

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

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

        already = {start}
        ret = 0
        while not q.empty():
            pos, cnt = q.get()
            ret = max(ret, cnt)
            for move in moving_range:
                i, j = pos[0] + move[0], pos[1] + move[1]
                if (i, j) not in already and map[i][j] == ".":
                    q.put(((i, j), cnt + 1))
                    already.add((i, j))

        return ret



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

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

ans = 0
for sy in range(h):
    for sx in range(w):
        dist = [[INF] * w for _ in range(h)]
        dist[sy][sx] = 0
        if S[sy][sx] == '
            continue
        q = deque()
        q.append((sy, sx))
        while len(q):
            y, x = q.popleft()
            for dy, dx in way:
                ny, nx = y + dy, x + dx
                if not (0 <= ny <= h - 1 and 0 <= nx <= w - 1):
                    continue
                if S[ny][nx] == '
                    continue
                dist[ny][nx] = dist[y][x] + 1
                q.append((ny, nx))
        for yy in range(h):
            for xx in range(w):
                if dist[yy][xx] == INF:
                    continue
                else:
                    ans = max(ans, dist[yy][xx])
print(ans)

Solution (Python):
from collections import deque
import copy

def BFS(sy,sx,xy_list):
 dist=[[-1]*w for i in range(h)]
 dist[sy][sx]=0
 xy_list[sy][sx]='

 dq=deque()
 dq.append((sy,sx))

 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<=ny<h and 0<=nx<w and xy_list[ny][nx]!='
    dq.append((ny,nx))
    xy_list[ny][nx]='
    dist[ny][nx]=dist[y][x]+1

 return dist

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

ans=0
for hh in range(h):
 for ww in range(w):
  if s[hh][ww]=='
   continue
  xy_list=copy.deepcopy(s)
  dist=BFS(hh,ww,xy_list)
  for d in dist:
   ans=max(ans,max(d))

print(ans)

Solution (Python):
from collections import deque

max = 0

tmp = []
tmp = list(map(int, input().split()))

w = tmp.pop()
h = tmp.pop()

maze = [["." for i in range(w)] for j in range(h)]

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

xq = deque()
yq = deque()
lq = deque()
    
for i in range(w):
    for j in range(h):

        flag = [[False for i in range(w)] for j in range(h)]
        
        
        if maze[j][i]==".":
            xq.appendleft(i)
            yq.appendleft(j)
            lq.appendleft(0)
            flag[j][i]=True

        while not len(xq)==0:
            x = xq.pop() 
            y = yq.pop() 
            l = lq.pop() 

            if max < l:
                max = l
            
            
            
            

            
            if ((x-1) >= 0 ):
                if (flag[y][x-1]==False) and (maze[y][x-1])==".":
                    xq.appendleft(x-1)
                    yq.appendleft(y)
                    lq.appendleft(l+1)
                    flag[y][x-1]=True
                
            if ((x+1) < w ):


                if flag[y][x+1]==False and maze[y][x+1]==".":
                    xq.appendleft(x+1)
                    yq.appendleft(y)
                    lq.appendleft(l+1)
                    flag[y][x+1]=True
                
            if ((y-1) >= 0):
                if flag[y-1][x]==False and maze[y-1][x]==".":
                    xq.appendleft(x)
                    yq.appendleft(y-1)
                    lq.appendleft(l+1)
                    flag[y-1][x]=True

            if ((y+1) < h):


                if flag[y+1][x]==False and maze[y+1][x]==".":
                    xq.appendleft(x)
                    yq.appendleft(y+1)
                    lq.appendleft(l+1)
                    flag[y+1][x]=True
                

print(max)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(H, W, S):
    def edges(v):
        i, j = v
        r = []
        if i > 0 and S[i-1][j] == '.':
            r.append((i-1, j))

        if i < H-1 and S[i+1][j] == '.':
            r.append((i+1, j))

        if j > 0 and S[i][j-1] == '.':
            r.append((i, j-1))

        if j < W-1 and S[i][j+1] == '.':
            r.append((i, j+1))

        return r

    def bfs(s):
        q = deque([s])
        d = {s: 0}
        while q:
            u = q.popleft()
            for v in edges(u):
                if v not in d:
                    d[v] = d[u] + 1
                    q.append(v)
        return max(d.values())

    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == '.':
                l = bfs((i, j))
                ans = max(ans, l)
    return ans


def main():
    H, W = read_int_n()
    S = [read_str() for _ in range(H)]
    print(slv(H, W, S))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import deque
def input(): return sys.stdin.readline().rstrip()

def main():
    H, W = map(int, input().split())
    S = [['
    direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]

    ans = 0
    for i in range(1, H + 1):
        for j in range(1, W + 1):
            if S[i][j] == '
                continue
            init = (i, j)
            que = deque()
            que.append(init)
            dist = [[-1 for _ in range(W+2)] for _ in range(H+2)]
            dist[i][j] = 0

            while que:
                qh, qw = que.popleft()
                for dh, dw in direction:
                    h = qh + dh
                    w = qw + dw
                    if S[h][w] == '
                        continue
                    dist[h][w] = dist[qh][qw] + 1
                    que.append((h, w))
            ans = max(ans, max([max(i) for i in dist]))
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

h, w = map(int, input().split())
maze = []
for _ in range(h):
    maze.append(input())


def bfs(sy, sx):
    num_table = [[-1]*w for _ in range(h)]
    
    num_table[sy][sx] = 0
    
    queue = deque([[sy, sx]])
    
    while queue:
        
        y, x = queue.popleft()
        for dy, dx in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            ny, nx = y + dy, x + dx
            if 0 <= ny < h and 0 <= nx < w and maze[ny][nx] == '.' and num_table[ny][nx] == -1:
                
                num_table[ny][nx] = num_table[y][x] + 1
                m = num_table[ny][nx]
                
                queue.append([ny, nx])
    return m


ans = 0

for y in range(h):
    for x in range(w):
        if maze[y][x] == ".":
            ans = max(ans, bfs(y, x))
print(ans)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
b = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
b = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = [input() for _ in range(h)]
b = ['
b[1: - 1] = [['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j - 1] == '.':
      for x, y in zip(a, b[1:]):
        y[1: -1] = x
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
import queue
import copy
D = ((0, -1), (0, 1), (-1, 0), (1, 0))

def bfs(S, s):
    M = copy.deepcopy(S)
    M[s[1]][s[0]] = '
    q = queue.Queue()
    q.put((s[0], s[1], 0))
    dis = 0

    while not q.empty():
        cur = q.get()

        for d in D:
            x = cur[0] + d[0]
            y = cur[1] + d[1]
            if M[y][x] != '
                M[y][x] = '
                q.put((x, y, cur[2]+1))
                dis = max(dis, cur[2]+1)

    return dis


H, W = map(int, input().split())
S = [None]*(H+2)

S[0] = ['
for h in range(1, H+1):
    S[h] = ['
S[-1] = ['

ans = 0
for sy in range(1, H+1):
    for sx in range(1, W+1):
        if S[sy][sx] != '
            ans = max(ans, bfs(S, (sx, sy)))

print(ans)

Solution (Python):
from collections import deque
 
h, w = map(int, input().split())
a = ['
b = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque
 
h, w = map(int, input().split())
a = ['
a[1: 1] = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
b = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
b = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

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

INF = 10**9 + 7


def to_graph(maze):
    H, W = len(maze), len(maze[0])

    g = [[INF] * (H * W) for _ in range(H * W)]

    for i, line in enumerate(maze):
        for j, s in enumerate(line):
            if i == j:
                g[i * W + j][i * W + j] = 0
            if s == '.':
                for neigh in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                    px, py = i + neigh[0], j + neigh[1]
                    if maze[px][py] == '.':
                        g[i * W + j][px * W + py] = 1

    return g


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

    g = to_graph(maze)

    n = len(g)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                g[i][j] = min(g[i][j], g[i][k] + g[k][j])

    current_max = 0
    for i, line in enumerate(g):
        for j, v in enumerate(line):
            if i != j and v < INF and v > current_max:
                current_max = v

    print(current_max)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

INF = 1001001001
di = (-1, 0, 1, 0)
dj = (0, -1, 0, 1)

h, w = map(int, input().split())
s = [input() for _ in range(h)]
ans = 0

for si in range(h):
  for sj in range(w):
    if s[si][sj] == '
      continue
    dist = [[INF] * w for _ in range(h)]
    dist[si][sj] = 0
    q = deque([(si, sj)])
    while q:
      i, j = q.popleft()
      for dir in range(4):
        ni = i + di[dir]
        nj = j + dj[dir]
        if (ni<0 or ni>=h or nj<0 or nj>=w):
          continue
        if s[ni][nj] == '
          continue
        if dist[ni][nj] != INF:
          continue
        q.append((ni, nj))
        dist[ni][nj] = dist[i][j]+1
    for i in range(h):
      for j in range(w):
        if dist[i][j] == INF:
          continue
        ans = max(ans, dist[i][j])
print(ans)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
S=[input() for i in range(H)]
ans=0
for i in range(H):
    for j in range(W):
        if S[i][j]=="
            continue
        st=(i,j)
        q=deque([st])
        dx=[1,-1,0,0]
        dy=[0,0,1,-1]
        dist=[[-1 for j in range(W)] for i in range(H)]
        dist[st[0]][st[1]]=0
        while(len(q)>0):
            r=q.popleft()
            x,y=r
            for k in range(4):
                nx=x+dx[k]
                ny=y+dy[k]
                if 0<=nx<H and 0<=ny<W:
                    if dist[nx][ny]==-1 and S[nx][ny]==".":
                        dist[nx][ny]=dist[x][y]+1
                        q.append((nx,ny))
        tmp=max([max(i) for i in dist])
        ans=max(tmp,ans)
print(ans)

Solution (Python):

import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]


    H,W = LMIIS()
    MOD = H*W
    S = [input() for _ in range(H)]

    from collections import deque
    def tansaku(S,V,length,q):
        if len(q) == 0:
            return length-1
        q2 = []
        for y,x in q:
            if  x >= 1 and S[y][x-1] == '.' and V[y][x-1]:
                V[y][x-1] = False
                q2.append((y,x-1))

            if x < W-1 and S[y][x+1] == '.' and V[y][x+1]:
                V[y][x+1] = False
                q2.append((y,x+1))

            if y >= 1 and S[y-1][x] == '.' and V[y-1][x]:
                V[y-1][x] = False
                q2.append((y-1,x))

            if y < H-1 and S[y+1][x] == '.' and V[y+1][x]:
                V[y+1][x] = False
                q2.append((y+1,x))

        return tansaku(S,V,length+1,q2)
    
    def getmax():
        max_length = 0
        for h in range(H):
            for w in range(W):
                V = [[True] * W for _ in range(H)]
                if S[h][w] == '.':
                    V[h][w] = False
                    max_length = max(tansaku(S,V,0,[(h,w)]),max_length)
        return max_length
    
    print(getmax())
   
    






if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
b = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -2] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
a[1: 1] = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
a[1: 1] = ('
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
a[1: 1] = ('
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = ['
a[1: 1] = ['
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
def main():
    h,w=map(int,input().split())
    s=[]
    for i in range(h):
        ss=input()
        s.extend(ss)
    mat = [[float("INF")] * (h*w) for i in range(h*w)]
    for i,a in enumerate(s):
        if a == '.':
            mat[i][i] = 0
            makemat(i,mat,h,w,s)
    
    
    
    for i,a in enumerate(s):
        if a == '.':

            caldist(mat,w*h)
            break
    ans = 0
    
    
    
    
    print(calans(mat))
def calans(m):
    temp = 0
    for i,w in enumerate(m):
        for j, s in enumerate(w):
            if s != float("INF"):
                temp = max(temp,s)
    return temp

def makemat(i,m,h,w,s):

    if (i % w) + 1 != w:
        if s[i+1] == '.':
            j = i+1
            m[i][j] = 1
            m[j][i] = 1
        
        
        
        
    if (i % w)  != 0:
        if s[i-1] == '.':
            j = i-1
            m[i][j] = 1
            m[j][i] = 1
        
        
        
        
    if i > w:
        if s[i-w] == '.':
            j=i-w
            m[i][j] = 1
            m[j][i] = 1
        
        
        
        
    if i < h*w - w:
        if s[i+w] == '.':
            j=i+w
            m[i][j] = 1
            m[j][i] = 1
        
        
        
        

def caldist(m,l):
    for i in range(l):
        for j in range(l):
            for k in range(l):
                m[j][k] = min(m[j][k],m[j][i]+m[i][k])


if __name__=='__main__':
    main()

Solution (Python):
from collections import deque

def bfs(h, w):
    q = deque([[h, w]])
    dist[h][w] = 0

    while len(q) != 0:
        y, x = q.popleft()

        for step in steps:
            nx = x + step[0]
            ny = y + step[1]
            if nx < 0 or nx >= W or ny < 0 or ny >= H:
                continue
            if maze[ny][nx] == "
                continue
            if dist[ny][nx] != -1:
                continue
            dist[ny][nx] = dist[y][x] + 1
            q.append([ny, nx])


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

steps = [[1, 0], [0, 1], [-1, 0], [0, -1]]
max_dist = [[0]*W for _ in range(H)]

for h in range(H):
    for w in range(W):
        if maze[h][w] == "
            continue
        dist = [[-1]*W for _ in range(H)]
        bfs(h, w)
        for row in dist:
            for d in row:
                max_dist[h][w] = max(max_dist[h][w], d)

ans = 0
for row in max_dist:
    for d in row:
        ans = max(ans, d)

print(ans)

Solution (Python):
from collections import deque

H,W=map(int, input().split())
S=[list(input()) for i in range(H)]
INF=10**6
M=[[10**6]*W for i in range(H)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs(y,x):
  q=deque()
  q.append((y,x))
  
  while len(q):
    y,x=q.popleft()
    
    for i in range(4):
      ny=y+dy[i]
      nx=x+dx[i]
      if (0<=ny<H and 0<=nx<W and M[ny][nx]==INF and S[ny][nx]!='
        q.append((ny, nx))
        M[ny][nx] = M[y][x]+1      
    
ans=0
for y in range(H):
  for x in range(W):
    if S[y][x]!='
      M=[[10**6]*W for i in range(H)]
      M[y][x]=0
      bfs(y,x)
      for i in range(H):
        for j in range(W):
          if M[i][j]!=INF:
            ans=max(ans,M[i][j])
print(ans)

Solution (Python):
from collections import deque

h, w = map(int, input().split())
a = [input() for _ in range(h)]
r = 0
for i in range(h):
  for j in range(w):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          if 0 <= i1 < h:
            for j1 in range(j - d, j + 2, 2):                
              if 0 <= j1 < w and b[i1][j1] == '.':
                b[i1][j1] = b[i][j] + 1
                q.append((i1, j1))
          d ^= 1
print(r)

Solution (Python):
def main():
	from collections import deque
	H, W = map(int, input().split())
	S = []
	for i in range(H):
		tmp = list(input())
		S.append(tmp[:])

	max_step = 0	 
	for i in range(H * W):
		
		sy, sx = i // W, i % W
		
		if S[sy][sx] == "
			continue
		
		
		steps = [[-1] * W for _ in range(H)]

		
		steps[sy][sx] = 0
		
		queue = [(sy, sx)]
		
		while len(queue) >= 1:
			
            
			cy, cx = queue.pop(0)
			
			for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):
				ny, nx = cy + dy, cx + dx
				
				if not (0 <= ny <= H - 1 and 0 <= nx <= W - 1):
					continue
				
				if S[ny][nx] == "
					continue
				
				queue.append((ny, nx))
				
				steps[ny][nx] = steps[cy][cx] + 1
		
	 
		
		ms = max(max(r) for r in steps)
		
		max_step = max(ms, max_step)
	print(max_step)

if __name__ == '__main__':
	main()

Solution (Python):

import numpy as np
from collections import deque


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

def calc_max_dist(start_x, start_y):
    dist = [[-1] * W for _ in range(H)]
    que = deque()

    dist[start_x][start_y] = 0
    que.append((start_x, start_y))

    while len(que):
        current_x, current_y = que.popleft()
        for i in ((0, 1), (0, -1), (1, 0), (-1, 0)):
            near_x, near_y = current_x + i[0], current_y + i[1]

            if not (0 <= near_x < H and 0 <= near_y < W):
                continue

            if S[near_x][near_y] == '.' and dist[near_x][near_y] == -1:
                dist[near_x][near_y] = dist[current_x][current_y] + 1
                que.append((near_x, near_y))

    return max([max(_) for _ in dist])


print(max([calc_max_dist(x, y) for x in range(H) for y in range(W) if S[x][y] == '.']))

Solution (Python):
from collections import deque

def bfs(sx, sy):
    dist = [[-1]*W for _ in range(H)]
    dist[sx][sy] = 0
    q = deque([(sx, sy)])
    res = 0
    
    while q:
        cx, cy = q.popleft()
        
        for nx, ny in [(cx-1, cy), (cx+1, cy), (cx, cy-1), (cx, cy+1)]:
            if not (0<=nx<H and 0<=ny<W):
                continue
            
            if S[nx][ny]=='.' and dist[nx][ny]==-1:
                dist[nx][ny] = dist[cx][cy]+1
                q.append((nx, ny))
                res = max(res, dist[nx][ny])
    
    return res

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

for i in range(H):
    for j in range(W):
        if S[i][j]=='.':
            ans = max(ans, bfs(i, j))

print(ans)

Solution (Python):
h,w = map(int,input().split())
inf = 10**8
dist = [[inf for i in range(h*w)] for j in range(h*w)]

G = [input() for _ in range(h)]

for i in range(h):
    for j in range(w):
        if G[i][j] == '.':
            dist[i * w + j][i * w + j] = 0
            for dx,dy in [[-1,0],[1,0],[0,1],[0,-1]]:
                if 0<=i+dx<h and 0<=j+dy<w and G[i+dx][j+dy] == '.':
                    dist[i * w + j][(i + dx) * w + j + dy] = 1
                    dist[(i + dx) * w + j + dy][i * w + j] = 1

for i in range(h*w):
    for j in range(h*w):
        for k in range(h*w):
            dist[j][k] = min(dist[j][k],dist[j][i]+dist[i][k])

ans = 0
for i in range(h*w):
    for j in range(h*w):
        if dist[i][j] < inf:
            ans = max(ans,dist[i][j])

print(ans)