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 copy
from collections import deque


def bfs(s, f):
    f[s[0]][s[1]] = 0
    moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

    q = deque([s])
    while q:
        c = q.popleft()
        for m in moves:
            my, mx = c[0] + m[0], c[1] + m[1]

            if f[my][mx] == ".":
                f[my][mx] = f[c[0]][c[1]] + 1
                q.append([my, mx])
            else:
                continue

    f = sum(f, [])
    return max([x for x in f if type(x) == int])


def main():
    H, W = map(int, input().split())
    field_s = []

    for h in range(H + 2):
        field_s.append(["
        if 1 <= h <= (H):
            field_s[h][1:-1] = list(map(str, input().rstrip()))

    start = []
    for y in range(1, H + 1):
        for x in range(1, W + 1):
            if field_s[y][x] == ".":
                start.append([y, x])

    ans = 0
    for s in start:
        field = copy.deepcopy(field_s)
        ans = max(ans, bfs(s, field))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import copy
from collections import deque

H, W = map(int, input().split())
field_s = []


for h in range(H + 2):
    field_s.append(["
    if 1 <= h <= (H):
        field_s[h][1:-1] = list(map(str, input().rstrip()))


moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]


start = []
for y in range(1, H + 1):
    for x in range(1, W + 1):
        if field_s[y][x] == ".":
            start.append([y, x])


ans = 0

for s in start:

    
    field = copy.deepcopy(field_s)

    
    que = deque([s])

    
    field[s[0]][s[1]] = 0

    
    while que:
        c = que.popleft()

        
        dist = field[c[0]][c[1]]

        
        for m in moves:
            my = c[0] + m[0]
            mx = c[1] + m[1]

            if field[my][mx] == ".":
                field[my][mx] = dist + 1
                que.append([my, mx])
            else:
                continue

    
    field = sum(field, [])
    ans = max(ans, max([x for x in field if type(x) == int]))

print(ans)

Solution (Python):
import copy
from collections import deque

H, W = map(int, input().split())
field_s = []


for h in range(H + 2):
    field_s.append(["
    if 1 <= h <= (H):
        field_s[h][1:-1] = list(map(str, input().rstrip()))


moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]


start = []
for y in range(1, H + 1):
    for x in range(1, W + 1):
        if field_s[y][x] == ".":
            start.append([y, x])


ans = 0

for s in start:

    
    field = copy.deepcopy(field_s)

    
    que = deque([s])

    
    field[s[0]][s[1]] = 0

    
    while que:
        c = que.popleft()

        
        dist = field[c[0]][c[1]]

        
        for m in moves:
            my = c[0] + m[0]
            mx = c[1] + m[1]

            if field[my][mx] == ".":
                field[my][mx] = dist + 1
                que.append([my, mx])
            else:
                continue
    
    
    field = sum(field, [])
    ans = max(ans, max([x for x in field if type(x)==int]))

print(ans)

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

h, m = map(int, input().split())
s = [0] * h
for i in range(h):
    s[i] = list(input())

def bfs(st_h, st_w):
    alr = [[-1] * m for _ in range(h)]
    alr[st_h][st_w] = 0
    que = deque([[st_h, st_w]])
    while len(que) > 0:
        now = que.popleft()
        
        if alr[max(0, now[0]-1)][now[1]] == -1 and s[max(0, now[0]-1)][now[1]] == '.':
            que.append([now[0]-1, now[1]])
            alr[now[0]-1][now[1]] = alr[now[0]][now[1]] + 1
        
        if alr[min(h-1, now[0]+1)][now[1]] == -1 and s[min(h-1, now[0]+1)][now[1]] == '.':
            que.append([now[0]+1, now[1]])
            alr[now[0]+1][now[1]] = alr[now[0]][now[1]] + 1
        
        if alr[now[0]][max(0, now[1]-1)] == -1 and s[now[0]][max(0, now[1]-1)] == '.':
            que.append([now[0], now[1]-1])
            alr[now[0]][now[1]-1] = alr[now[0]][now[1]] + 1
        
        if alr[now[0]][min(m-1, now[1]+1)] == -1 and s[now[0]][min(m-1, now[1]+1)] == '.':
            que.append([now[0], now[1]+1])
            alr[now[0]][now[1]+1] = alr[now[0]][now[1]] + 1
    res = 0
    for x in alr:
        for y in x:
            res = max(res, y)
    return res

ans = 0

for a in range(h):
    for b in range(m):
        if s[a][b] == '.':
            ans = max(ans, bfs(a, b))

print(ans)

Solution (Python):
from collections import deque
import numpy as np


def bfs(i, j):
    queue = deque()
    queue.append((i, j))
    visited = [[0] * (w + 2) for _ in range(h + 2)]
    visited[i][j] = 1
    moves = [[0] * (w + 2) for _ in range(h + 2)]
    while queue:
        i, j = queue.popleft()
    
        next_points = (
            (i, j + 1),
            (i + 1, j),
            (i, j - 1),
            (i - 1, j)
        )
        
        for next_i, next_j in next_points:
            if not visited[next_i][next_j] and maze[next_i][next_j] == '.':
                queue.append((next_i, next_j))
                visited[next_i][next_j] = 1
                moves[next_i][next_j] = moves[i][j] + 1
    
    return moves


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

max_move = 0
for i in range(1, h+1):
    for j in range(1, w+1):
        if maze[i][j] == '
            continue
        moves = np.array(bfs(i, j))
        max_move = max(max_move, np.max(moves))
        
print(max_move)

Solution (Python):
from collections import deque
H,W=map(int,input().split())
S=[list(input()) for _ in range(H)]
ma = 0
for i in range(H):
    for j in range(W):
        d=deque()
        if S[i][j]==".":
            dp=[[float("inf") for _ in range(W)] for _ in range(H)]
            dp[i][j]=0
            d.append([i,j])
            while len(d)>0:
                x,y=d.popleft()
                if x!=0:
                    if S[x-1][y]==".":
                        if dp[x-1][y]>(dp[x][y]+1):
                            dp[x-1][y]=dp[x][y]+1
                            d.append([x-1,y])
                if x!=H-1:
                    if S[x+1][y]==".":
                        if dp[x+1][y]>(dp[x][y]+1):
                            dp[x+1][y]=dp[x][y]+1
                            d.append([x+1,y])
                if y!=0:
                    if S[x][y-1]==".":
                        if dp[x][y-1]>(dp[x][y]+1):
                            dp[x][y-1]=dp[x][y]+1
                            d.append([x,y-1])
                if y!=W-1:
                    if S[x][y+1]==".":
                        if dp[x][y+1]>(dp[x][y]+1):
                            dp[x][y+1]=dp[x][y]+1
                            d.append([x,y+1])
                
            for k in range(H):
                for l in range(W):
                    if dp[k][l]!=float("inf"):
                        ma=max(ma,dp[k][l])
print(ma)

Solution (Python):
from collections import deque

h,w = map(int,input().split())
s = [list(input()) for j in range(h)]
path = [[[]for i in range(w)]for j in range(h)]
sg = []
for i in range(h):
    for j in range(w):
        if s[i][j] == '
            continue
        else:
            sg.append((i,j))
        if j != w-1 and s[i][j+1] == '.':
            path[i][j].append((i,j+1))
        if i != h-1 and s[i+1][j] == '.':
            path[i][j].append((i+1,j))
        if j != 0 and s[i][j-1] == '.':
            path[i][j].append((i,j-1))
        if i != 0 and s[i-1][j] == '.':
            path[i][j].append((i-1,j))
que = deque([])
ans = 0
for x,y in sg:
    passed = [[0 for ii in range(w)] for jj in range(h)]
    que = deque([])
    que.append((x,y))
    depth = [[-1 for ii in range(w)] for jj in range(h)]
    depth[x][y] = 0
    while len(que) > 0:
        vx,vy = que.popleft()
        d = depth[vx][vy]
        for wx,wy in path[vx][vy]:
            if depth[wx][wy] > -1:
                continue
            depth[wx][wy] = d + 1
            que.append((wx,wy))
        ans = max(ans,d)
print(ans)

Solution (Python):

from collections import deque


def main():
    H, W = map(int, input().split())
    S = [None for _ in range(H)]
    for i in range(H):
        S[i] = input()

    adj = [[] for _ in range(H * W)]
    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]

    for i in range(H):
        for j in range(W):
            if S[i][j] == '.':
                for k in range(4):
                    y = i + dy[k]
                    x = j + dx[k]
                    if 0 <= y < H and 0 <= x < W:
                        if S[y][x] == '.':
                            adj[W*i + j].append(W*y + x)

    
    ans = 0
    for i in range(H*W):
        queue = deque([i])
        visit = [-1] * (H * W)
        visit[i] = 0

        while queue:
            now = queue.popleft()
            for u in adj[now]:
                if visit[u] < 0:
                    queue.append(u)
                    visit[u] = visit[now] + 1
        ans = max(ans, max(visit))
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
h,w = map(int,input().split())
s_input = [list(input()) for i in range(h)]

mx = [0,0,1,-1]
my = [1,-1,0,0]

ans = 0
for i in range(h):
    for j in range(w):
        if s_input[i][j]=='
            continue
        queue = deque()
        queue.append([j,i])

        visited = [[-1]*w for i in range(h)]
        visited[i][j]=0

        res = 0
        while queue:
            x,y = queue.popleft()
            for k in range(4):
                nx = x+mx[k]
                ny = y+my[k]
                if 0<=nx<w and 0<=ny<h:
                    if visited[ny][nx]!=-1:
                        continue
                    if s_input[ny][nx]=='
                        continue
                    visited[ny][nx]=visited[y][x]+1
                    queue.append([nx,ny])
                    res = max(res,visited[ny][nx])
        ans = max(ans,res)
print(ans)

Solution (Python):
from collections import deque
from copy import deepcopy
h, w = map(int, input().split())
table = [[] for _ in range(h)]
for i in range(h):
    table[i] = list(input())

steps = [0, 1, 0, -1, 0]
ans = 0
for y in range(h):
    for x in range(w):
        if table[y][x] == "
            continue
        t = deepcopy(table)
        t[y][x] = 0
        queue = deque()
        queue.append((y, x))
        while len(queue) > 0:
            cur = queue.popleft()
            for i in range(4):
                ny, nx = cur[0] + steps[i], cur[1] + steps[i + 1]
                if 0 <= ny and ny < h and 0 <= nx and nx < w and t[ny][
                        nx] == ".":
                    t[ny][nx] = t[cur[0]][cur[1]] + 1
                    queue.append((ny, nx))
        tmp = 0
        for i in range(h):
            for j in range(w):
                if str(t[i][j]).isnumeric():
                    tmp = max(tmp, t[i][j])
        ans = max(ans, tmp)
print(ans)

Solution (Python):
from collections import deque
from copy import deepcopy


def bfs(maze, s):
    que = deque()
    que.append(s)
    nx = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    while que:
        x, y, c = que.popleft()
        if maze[x][y] != ".":
            continue
        maze[x][y] = c
        for u, v in nx:
            que.append((x + u, y + v, c + 1))
    ll = sum(maze, [])
    s = set(ll) - {"

    return max(s)


def main():
    h, w = map(int, input().split())
    wall = ["
    maze = [wall]
    road = []
    for i in range(1, h + 1):
        line = ["
        maze.append(line)
        for j, k in enumerate(line):
            if k == ".":
                road.append((i, j, 0))
    maze.append(wall)

    ans = 0
    for p in road:
        m = deepcopy(maze)
        ans = max(ans, bfs(m, p))
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from copy import deepcopy
from collections import deque


def bfs(maze, x, y):
    res = 0
    que = deque([])
    que.append((x, y, 0))

    while que:
        i, j, c = que.popleft()
        if maze[i][j] == "
            continue
        maze[i][j] = "
        res = max(res, c)
        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            que.append((i + dx, j + dy, c + 1))

    return res


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

    ans = 0
    for i in range(1, h + 1):
        for j in range(1, w + 1):
            if maze[i][j] == "
                continue
            m = deepcopy(maze)
            ans = max(ans, bfs(m, i, j))

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

def matrix(H,W, fill = False):
    return [[fill for x in range(W)] for j in range(H)]

def get_n(v):
    i,j = v

    li, lj = [i,j-1] if j>0 else [None,None]
    di, dj = [i+1,j] if i<H-1 else [None,None]
    ri, rj = [i,j+1] if j<W-1 else [None,None]
    ui, uj = [i-1,j] if i>0 else [None,None]

    pp = [(li,lj), (di,dj), (ri,rj), (ui,uj)]
    res = []

    for (i,j) in pp:
        if i!= None and maze[i][j] != "
            res.append((i,j))

    return res

H, W = map(int, input().split())
maze = []

prep = lambda x: 1 if x == "." else 0
for i in range(H):
    l  = input()
    maze.append(list(l))

max_d = 0

for i in range(H):
    for j in range(W):
        if maze[i][j] == "
            continue

        distance = matrix(H,W, 0)
        is_visited = matrix(H,W, 0)

        d = deque()
        d.append((i,j))
        is_visited[i][j] = 1

        while(d):
            v = d.popleft()
            for ni,nj in get_n(v):
                if is_visited[ni][nj]:
                    continue
                is_visited[ni][nj] = True
                distance[ni][nj] = distance[v[0]][v[1]] + 1
                max_d = max(distance[ni][nj], max_d)
                d.append((ni,nj))


print(max_d)

Solution (Python):
import queue
H, W = map(int, input().split())
S = []
for i in range(H):
  ss = input()
  S.append(ss)
rs = []
for n in range(H*W):
  sx, sy = n//W, n%W
  if S[sx][sy] == "
    continue
  M = [[-1]*W for i in range(H)]
  M[sx][sy] = 0
  q = queue.Queue()
  q.put((sx, sy, 0))
  while not q.empty():
    x, y, c = q.get()
    if x > 0 and S[x-1][y] == "." and M[x-1][y] < 0:
      M[x-1][y] = c+1
      q.put((x-1, y, c+1))
    if x+1 < H and S[x+1][y] == "." and M[x+1][y] < 0:
      M[x+1][y] = c+1
      q.put((x+1, y, c+1))
    if y > 0 and S[x][y-1] == "." and M[x][y-1] < 0:
      M[x][y-1] = c+1
      q.put((x, y-1, c+1))
    if y+1 < W and S[x][y+1] == "." and M[x][y+1] < 0:
      M[x][y+1] = c+1
      q.put((x, y+1, c+1))
  
  r = max(map(max, M))
  rs.append(r)
r = max(rs)
print(r)

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

        
        distance = [[0]*W for _ in range(H)]
        
        stack = deque([[x,y]])

        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] != "
                    distance[new_h][new_w] = distance[h][w]+1
                    stack.append([new_h, new_w])

        
        distance[x][y] = 0
        ans = max(ans, np.max(distance))

print(ans)

Solution (Python):
import sys
from heapq import *
stdin=sys.stdin
    
ns = lambda:stdin.readline().rstrip()
ni = lambda:int(stdin.readline().rstrip())
nm = lambda:map(int,stdin.readline().split())
nl = lambda:list(map(int,stdin.readline().split()))
    
H,W=nm()
    
INF=10**18
def dijkstra(start,edge):
    d=[[INF]*W for i in range(H)]
    d[start[0]][start[1]]=0
    q=[(0,start[0],start[1])]
    while(len(q)!=0):
        ci,i,j=heappop(q)
        
        
        for p in edge[i][j]:
            if(d[p[0]][p[1]]>d[i][j]+1):
                d[p[0]][p[1]]=d[i][j]+1
                heappush(q,(d[p[0]][p[1]],p[0],p[1]))
    return d
    
E=[[[] for _ in range(W)] for _ in range(H)] 
S=[] 
    
for i in range(H):
    tmp=ns()
    S.append(tmp)
    
    
for i in range(H):
    for j in range(W):
        if( j+1<=W-1 and S[i][j+1]=='.'):
            E[i][j].append((i,j+1))
        if( i+1<=H-1 and S[i+1][j]=='.'):
            E[i][j].append((i+1,j))
        if(S[i][j-1]=='.' and 0<=j-1):
            E[i][j].append((i,j-1))
        if(S[i-1][j]=='.' and 0<=i-1):
            E[i][j].append((i-1,j))
    
    
    
ans=0
    
d=[[0]*W for i in range(H)]
for i in range(H):
    for j in range(W):
        if(S[i][j]!='.'):
            continue
        d=dijkstra((i,j),E)
        for k in range(H):
            for l in  range(W):
                if(ans<d[k][l] and d[k][l]<10**18):
                    ans=d[k][l]
                    
print(ans)

Solution (Python):
h,w = map(int,input().split())

s = ["
setroad = set([])

for i in range(1, h+1):
	s[i] = "

for i in range(h+2):
	for j in range(w+2):
		if s[i][j]==".":
			setroad.add((i,j))



def isroad(n, m):
	if (n, m) in setroad:
		return True
	else:
		return False



ans = 0

for shokix, shokiy in setroad:
	kaisuu = 0
	settansaku = set([])
	listmada = [(shokix, shokiy)]
	setmada = set([(shokix,shokiy)])
	while len(setmada) != 0:
		for i, j in listmada[:]:
			settansaku.add((i,j))
			listmada.remove((i, j))
			setmada.remove((i, j))
			for k,l in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
				if isroad(k,l):
					if not (k,l) in setmada:
						if not (k,l) in settansaku:
							listmada.append((k,l))
							setmada.add((k,l))
		kaisuu += 1
	kaisuu -= 1
	if kaisuu >= ans:
		ans = kaisuu
print(ans)

Solution (Python):
h,w = map(int,input().split())

s = ["
road = []
setroad = set([])

for i in range(1, h+1):
	s[i] = "

for i in range(h+2):
	for j in range(w+2):
		if s[i][j]==".":
			road.append((i,j))
			setroad.add((i,j))



def isroad(n, m):
	if (n, m) in setroad:
		return True
	else:
		return False



ans = 0

for shokix, shokiy in road:
	kaisuu = 0
	listtansaku = []
	settansaku = set([])
	listmada = [(shokix, shokiy)]
	setmada = set([(shokix,shokiy)])
	while len(setmada) != 0:
		for i, j in listmada[:]:
			listtansaku.append((i,j))
			settansaku.add((i,j))
			listmada.remove((i, j))
			setmada.remove((i, j))
			for k,l in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
				if isroad(k,l):
					if not (k,l) in setmada:
						if not (k,l) in settansaku:
							listmada.append((k,l))
							setmada.add((k,l))
		kaisuu += 1
	kaisuu -= 1
	if kaisuu >= ans:
		ans = kaisuu
print(ans)

Solution (Python):
from collections import deque
INF = 10**18
h,w = map(int,input().split())
li = [list(input()) for i in range(h)]


def bfs(sy,sx):
    
    d = [[INF]*w for i in range(h)]
    
    
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]

    
    """
    for i in range(h):
        for j in range(w):
            if li[i][j]  == "s":
                sx = i
                sy = j
            if li[i][j] == "g":
                gx = i
                gy = j
    """
    if li[sy][sx] == "
        return 0
    
    que = deque([])
    que.append((sy,sx))
    d[sy][sx] = 0
    
    
    while que:
        
        p = que.popleft()
        
        """
        if p[0] == gx and p[1] == gy:
            break
        """
        
        for i in range(4):
            nx = p[1] + dx[i]
            ny = p[0] + dy[i]

            
            if 0<=nx and nx < w and 0 <= ny and ny < h:
                if li[ny][nx] != "
                    
                    que.append((ny,nx))
                    
                    d[ny][nx] = d[p[0]][p[1]] + 1
    dmax = 0
    for i in range(h):
        for j in range(w):
            if d[i][j] == INF:
                continue
            dmax = max(dmax,d[i][j])
    return dmax
ans = 0
for i in range(h):
    for j in range(w):
        c = bfs(i,j)
        ans = max(ans,c)
print(ans)

Solution (Python):
h,w=map(int,input().split())
n=h*w
inf=10**6
field=[]
for i in range(h):
    field.append(input())
dist=[[inf]*n for i in range(n)]
for i in range(h):
    for j in range(w):
        if field[i][j]=="
        if j+1<w and field[i][j+1]!="
            dist[i*w+j][i*w+j+1]=1
            dist[i*w+j+1][i*w+j]=1
        if i+1<h and field[i+1][j]!="
            dist[i*w+j][(i+1)*w+j]=1
            dist[(i+1)*w+j][i*w+j]=1
for i in range(n):
    for j in range(n):
        for k in range(n):
            dist[j][k]=min(dist[j][k],dist[j][i]+dist[i][k])
ans=0
for i in range(n):
    for j in range(n):
        if i==j:
            continue
        if dist[i][j]==inf:
            continue
        ans=max(ans,dist[i][j])
print(ans)

Solution (Python):
H, W = map(int, input().split())
Inf = 10**9

S = [input() for i in range(H)]
dis = [[Inf]*(H*W) for i in range(H*W)]

for i in range(H):
    for j in range(W):
        if S[i][j] == "
            continue
        if i - 1 >= 0 and S[i-1][j] == ".":
            dis[i*W+j][(i-1)*W+j] = 1
        if i + 1 < H and S[i+1][j] == ".":
            dis[i*W+j][(i+1)*W+j] = 1
        if j - 1 >= 0 and S[i][j-1] == ".":
            dis[i*W+j][i*W+j-1] = 1
        if j + 1 < W and S[i][j+1] == ".":
            dis[i*W+j][i*W+j+1] = 1

for i in range(H*W):
    for j in range(H*W):
        for k in range(H*W):
            dis[j][k] = min(dis[j][i] + dis[i][k], dis[j][k])

max_ans = 0
for i in range(H*W):
    for j in range(H*W):
        if i == j or dis[i][j] == Inf:
            continue        
        max_ans = max(dis[i][j], max_ans)

print(max_ans)

Solution (Python):
import queue

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

def nexts(h, w):
    l = []
    if h > 0   and S[h-1][w] == '.':
        l.append((h-1, w))
    if h < H-1 and S[h+1][w] == '.':
        l.append((h+1, w))
    if w > 0   and S[h][w-1] == '.':
        l.append((h, w-1))
    if w < W-1 and S[h][w+1] == '.':
        l.append((h, w+1))
    return l

def bfs(h, w):
    d = [[0]*W for _ in range(H)]
    q = queue.Queue()
    q.put((h,w))

    while not q.empty():
        v = q.get()
        vh, vw = v[0], v[1]

        for nxt in nexts(vh, vw):
            nh, nw = nxt[0], nxt[1]
            if d[nh][nw] > 0:
                continue
            d[nh][nw] = d[vh][vw] + 1
            q.put((nh, nw))
    d[h][w] = 0
    return d

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

        d = bfs(h,w)
        mx = 0
        for th in range(H):
            for tw in range(W):
                mx = max(mx, d[th][tw])
        ans = max(ans, mx)
print(ans)

Solution (Python):



def input_int():
    return int(input())



def int1(x):
    return int(x) - 1



def input_to_int_map():
    return map(int, input().split())



def input_to_int_tuple():
    return tuple(map(int, input().split()))



def input_to_int_tuple_minus1():
    return tuple(map(int1, input().split()))


def main():
    h, w = input_to_int_map()
    mz = [input() for i in range(h)]

    from collections import deque

    ret = 0
    for x in range(h):
        for y in range(w):
            
            if mz[x][y] == "
                continue

            
            distance = [[0] * w for _ in range(h)]
            
            dq = deque([[x, y]])

            while dq:
                now_h, now_w = dq.popleft()
                for i, j in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
                    new_h, new_w = now_h + i, now_w + j
                    if new_h < 0 or new_w < 0 or new_h >= h or new_w >= w:
                        continue

                    if mz[new_h][new_w] != "
                        distance[new_h][new_w] = distance[now_h][now_w] + 1
                        dq.append([new_h, new_w])

            distance[x][y] = 0
            ret = max(max(list(map(max, distance))), ret)

    return ret


if __name__ == "__main__":
    print(main())

Solution (Python):
import sys













import queue

sys.setrecursionlimit(10000001)
INF = 10 ** 10
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))





def main():
    h, w = ns()
    mat = [list(sys.stdin.readline()) for _ in range(h)]

    def bfs(x, y):
        arrived_mat = [[False for i in range(w)] for j in range(h)]

        que = queue.Queue()
        que.put((x, y, 1))
        arrived_mat[y][x] = True
        res = 0

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

        while que.qsize() > 0:
            xi, yi, cnt = que.get()

            for dx, dy in direc:
                next_x = xi + dx
                next_y = yi + dy
                if -1 < next_x < w and -1 < next_y < h:
                    if mat[next_y][next_x] == "." and arrived_mat[next_y][next_x] != True:
                        que.put((next_x, next_y, cnt + 1))
                        arrived_mat[next_y][next_x] = True                        
                        res = max(res, cnt + 1)

        return res

    ans = 0
    for y in range(h):
        for x in range(w):
            if mat[y][x] == ".":
                ans = max(ans, bfs(x, y) - 1)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys













import queue

sys.setrecursionlimit(10000001)
INF = 10 ** 10
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))





def main():
    h, w = ns()
    mat = [list(sys.stdin.readline()) for _ in range(h)]

    def bfs(x, y):
        arrived_mat = [[False for i in range(w)] for j in range(h)]

        que = queue.Queue()
        que.put((x, y, 1))
        arrived_mat[y][x] = True
        res = 0

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

        while que.qsize() > 0:
            xi, yi, cnt = que.get()

            for dx, dy in direc:
                next_x = xi + dx
                next_y = yi + dy
                if -1 < next_x < w and -1 < next_y < h:
                    if mat[next_y][next_x] == "." and arrived_mat[next_y][next_x] != True:
                        que.put((next_x, next_y, cnt + 1))
                        arrived_mat[next_y][next_x] = True                        
                        res = max(res, cnt + 1)

        return res

    ans = 0
    for y in range(h):
        for x in range(w):
            if mat[y][x] == ".":
                ans = max(ans, bfs(x, y) - 1)

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def resolve():
    '''
    code here
    '''
    from collections import deque
    H, W = [int(item) for item in input().split()]
    grid = [[item for item in input()] for _ in range(H)]

    res = 0
    for i in range(H):
        for j in range(W):
            if grid[i][j] == '.':

                que = deque([[i,j]])
                footprint = [[-1 for _ in range(W)] for _ in range(H)]
                footprint[i][j] = 0

                while que:
                    a, b = que.popleft()
                    c = footprint[a][b]
                    if c > res:
                        res = c

                    if a != 0 and footprint[a-1][b] == -1 and grid[a-1][b] == '.':
                        que.append([a-1, b])
                        footprint[a-1][b] = c + 1
                    if a != H-1 and footprint[a+1][b] == -1 and grid[a+1][b] == '.':
                        que.append([a+1, b])
                        footprint[a+1][b] = c + 1
                    if b != 0 and footprint[a][b-1] == -1 and grid[a][b-1] == '.':
                        que.append([a, b-1])
                        footprint[a][b-1] = c + 1
                    if b != W-1 and footprint[a][b+1] == -1 and grid[a][b+1] == '.':
                        que.append([a, b+1])
                        footprint[a][b+1] = c + 1

    print(res)
        


if __name__ == "__main__":
    resolve()

Solution (Python):
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall

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

g = [[0] * (H * W) for _ in range(H * W)]
for y in range(H):
    for x in range(W):
        if S[y][x] == '
            continue
        if y - 1 >= 0 and S[y - 1][x] != '
            g[y * W + x][(y - 1) * W + x] = 1
        if y + 1 < H and S[y + 1][x] != '
            g[y * W + x][(y + 1) * W + x] = 1
        if x - 1 >= 0 and S[y][x - 1] != '
            g[y * W + x][y * W + x - 1] = 1
        if x + 1 < W and S[y][x + 1] != '
            g[y * W + x][y * W + x + 1] = 1
g = floyd_warshall(csgraph_from_dense(g))

result = 0
for i in range(H * W):
    for j in range(H * W):
        if g[i][j] == float('inf'):
            continue
        result = max(result, g[i][j])
print(int(result))

Solution (Python):
from collections import deque



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

ans = 0
dyx = [(1,0), (0,1),(-1,0), (0,-1)]
for i in range(H):
    for j in range(W):
        if S[i][j] == '
        dist = [[0 for _ in range(W)] for _ in range(H)] 
        visited = [[False for _ in range(W)] for _ in range(H)]
        visited[i][j] = True
        q = deque()
        q.append((i,j))
        while q:
            y,x = q.popleft()
            for dy,dx in dyx:
                ny, nx = y+dy, x+dx
                if not 0 <= nx < W: continue
                if not 0 <= ny < H: continue
                if visited[ny][nx]: continue
                if S[ny][nx] == '
                visited[ny][nx] = True
                dist[ny][nx] = dist[y][x] + 1
                q.append((ny, nx))
                
                

        
        for p in range(H):
            ans = max(ans, max(dist[p]))
        
        

            

print(ans)