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

H,W = map(int, input().split())
s = ["

def bfs(sh,sw):
  if s[sh][sw] == "
    return 0
  queue = deque([(sh,sw)]) 
  dist = [[-1] * (W+1) for i in range(H+1)] 
  dist[sh][sw] = 0 
  while queue:
    h,w = queue.popleft() 
    d = dist[h][w] 
    
    for i in [h-1,h+1]: 
      if s[i][w] == "." and dist[i][w] == -1: 
        dist[i][w] = d + 1 
        queue.append((i,w)) 
    for j in [w-1,w+1]: 
      if s[h][j] == "." and dist[h][j] == -1:
        dist[h][j] = d + 1
        queue.append((h,j))
          
  max_dist = 0
  for i in dist:
    max_dist = max(max_dist,max(i)) 
  return max_dist
      

ans = 0          
for i in range(1,H+1):
  for j in range(1,W+1):
    now = bfs(i,j)
    ans = max(ans, now)
print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7


H, W = MAP()
S = [input() for _ in range(H)]
dy = (1, 0, -1, 0)
dx = (0, -1, 0, 1)

def diff_max(start_y, start_x):
	check = [[-1]*W for _ in range(H)]
	check[start_y][start_x] = 0
	q = deque([(start_y, start_x)])

	while 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:
				if check[ny][nx] == -1 and S[ny][nx] == ".":
					check[ny][nx] = check[y][x] + 1
					q.append((ny, nx))

	return max([max(x) for x in check])



ans = -INF
for i in range(H):
	for j in range(W):
		if S[i][j] == ".":
			ans = max(ans, diff_max(i, j))

print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7


H, W = MAP()
S = [input() for _ in range(H)]
dy = (1, 0, -1, 0)
dx = (0, -1, 0, 1)

def diff_max(start_y, start_x):
	check = [[-1]*W for _ in range(H)]
	check[start_y][start_x] = 0
	q = deque([(start_y, start_x)])

	while 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:
				if check[ny][nx] == -1 and S[ny][nx] == ".":
					check[ny][nx] = check[y][x] + 1
					q.append((ny, nx))

	return max([max(x) for x in check])



ans = -INF
for i in range(H):
	for j in range(W):
		if S[i][j] == ".":
			ans = max(ans, diff_max(i, j))

print(ans)

Solution (Python):
from collections import deque
import copy

digtmp = [[0, 1], [1, 0], [0, -1], [-1, 0]]

def bfs(maze, s):
    que = deque([s])
    maze[s[0]][s[1]] = 0
    ans = 0
    for _ in range(pow(10, 3)):
        fr = que.popleft()
        for d in digtmp:
            to = [fr[0] + d[0], fr[1] + d[1]]
            if maze[to[0]][to[1]] == '.':
                nxt = maze[fr[0]][fr[1]] + 1
                maze[to[0]][to[1]] = nxt
                ans = max(ans, nxt)
                que.append(to)
        if len(que) == 0:
            break
    return ans

def main():
    H, W = map(int, input().split())
    grid = []; road = []
    grid.append(['
    for i in range(H):
        tmp = list(input())
        for j in range(W):
            if tmp[j] == '.':
                road.append([i+1, j+1])
        grid.append(['
    grid.append(['
    
    ans = 1
    for r in road:
        maze = copy.deepcopy(grid)
        ans = max(ans, bfs(maze, r))
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):


import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
grid = [readline().rstrip() for i in range(H)]

ans = 0
cases = ((0,1),(0,-1),(1,0),(-1,0))
from collections import deque
for i in range(H):
  for j in range(W):
    q = deque([[i,j,0]])
    visited = [[False] * W for i in range(H)]
    while q:
      y,x,d = q.popleft()
      if grid[y][x] == "
        continue
      if visited[y][x]:
        continue
      visited[y][x] = True
      if d > ans:
        ans = d
      for c in cases:
        if 0 <= y + c[0] < H and 0 <= x + c[1] < W:
          q.append([y + c[0],x + c[1],d + 1])
print(ans)

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

def bfs(field, sx, sy, seen):
    queue = deque([(sx, sy)])
    seen[sx][sy] += 1
    
    while queue:
        x, y = queue.popleft()

        for dx, dy in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
            nx = x + dx
            ny = y + dy
            
            if seen[nx][ny] == -1 and field[nx][ny] != "
                seen[nx][ny] = seen[x][y] + 1
                queue.append((nx, ny))

    return seen[x][y]


def main():
    H,W = map(int, readline().split())
    c = ["
    for _ in range(H):
        c.append("
    c.append("

    ans = 0
    for sx in range(1,H+1):
        for sy in range(1,W+1):
            if c[sx][sy] == ".":
                seen = [[-1] * (W + 2) for i in range(H+2)]
                dist = bfs(c, sx, sy, seen)
                ans = max(ans, dist)

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque

h,w = map(int, input().split())
grid = []
for i in range(h):
    s = list(input().rstrip())
    grid.append(s)
dydx = [[0, 1], [1,0], [-1, 0], [0, -1]]

def find_longest_path(xy):
    visited = [[0]*w for _ in range(h)]
    dist = [[0]*w for _ in range(h)]
    visited[xy[1]][xy[0]]=1
    que = deque()
    que.append(xy)
    while que:
        v = que.popleft()
        x,y = v[0],v[1]
        for i in dydx:
            dx = i[0]
            dy = i[1]
            if ((x+dx<w and y+dy<h) and ((x+dx)>-1)and(y+dy)>-1) and not visited[y+dy][x+dx]:
                if(grid[y+dy][x+dx]=="."):
                    que.append([x+dx, y+dy])
                    visited[y+dy][x+dx]=1
                    dist[y+dy][x+dx]=dist[y][x]+1
                    u,k = x+dx, y+dy
                    r = dist[y+dy][x+dx]

    return r

def main():
    k=0
    for i in range(h):
        for j in range(w):
            if grid[i][j]==".":
                k = max(k, find_longest_path([j,i]))
    print(k)

if __name__ == '__main__':
    main()

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

from collections import deque
ans=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='
            continue
        d=[[-1]*w for _ in range(h)]
        queue=deque()
        queue.append((i,j))
        d[i][j]=0
        tmp_ans=-1
        while queue:
            y,x=queue.popleft()
            for d_y, d_x in zip(dx,dy):
                new_y=y+d_y
                new_x=x+d_x
                if new_y<0 or h<=new_y or new_x<0 or w<=new_x:
                    continue
                if s[new_y][new_x]=='.' and d[new_y][new_x]==-1:
                    d[new_y][new_x]=d[y][x]+1
                    queue.append((new_y, new_x))
                    tmp_ans=max(tmp_ans, d[new_y][new_x])
        ans=max(ans, tmp_ans)
print(ans)

Solution (Python):
from collections import deque
def bfs(maze,sy,sx):
  queue=deque([[sy,sx]])
  visited=[[0]*w for _ in range(h)]
  visited[sy][sx]=1
  mx=0
  while queue:
    y,x=queue.popleft()
    for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
      n_y,n_x=y+j,x+k
      if not (0<=n_y<h and 0<=n_x<w):
        continue
      if maze[n_y][n_x]=='.' and visited[n_y][n_x]==0:
        visited[n_y][n_x]=visited[y][x]+1
        mx=max(mx,visited[n_y][n_x])
        queue.append([n_y,n_x])
  return mx

h,w=map(int,input().split())
s=[input() for _ in range(h)]
ans=0
for sy in range(h):
  for sx in range(w):
    if s[sy][sx]=='
      continue
    ans=max(ans,bfs(s,sy,sx)-1)
print(ans)

Solution (Python):
from collections import deque
h , w = map(int,input().split())
S = [input() for i in range(h)]
dxy = [(0,1),(1,0),(-1,0), (0,-1)]

ans = 0
for y in range(h):
    for x in range(w):
        if S[y][x] == '
        dist =[[0]*w for i in range(h)]
        visited = [[0]*w for i in range(h)]
        visited[y][x] = 1
        q = deque([(x,y)])
        while q:
            x,y = q.popleft()
            for dx, dy in dxy:
                nx, ny = x + dx, y+ dy
                if not 0 <= nx < w: continue
                if not 0 <= ny < h: continue 
                if visited[ny][nx]:continue
                if S[ny][nx] == '
                visited[ny][nx] = 1
                dist[ny][nx] = dist[y][x] + 1
                q.append((nx,ny))
        ans = max(ans, max(max(row) for row in dist)) 
print(ans)

Solution (Python):
h,w=[int(x) for x in input().rstrip().split()]
l=[list(input()) for i in range(h)]
move=[[1,0],[-1,0],[0,-1],[0,1]]
def bfs(x,y):
  stack=[[x,y]]
  done=[[False]*w for i in range(h)]
  dist=[[0]*w for i in range(h)]
  max_val=0
  while(stack):
    nx,ny=stack.pop(0)
    done[ny][nx]=True
    for dx,dy in move:
      mx=nx+dx
      my=ny+dy
      if not(0<=mx<=w-1) or not(0<=my<=h-1) or done[my][mx]==True or l[my][mx]=="
        continue
      done[my][mx]=True
      dist[my][mx]=dist[ny][nx]+1
      max_val=max(max_val,dist[my][mx])
      stack.append([mx,my])
  return max_val

ans=0
for i in range(w):
  for j in range(h):
    if l[j][i]!="
      now=bfs(i,j)
      ans=max(ans,now)
print(ans)

Solution (Python):

from collections import deque

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] == '
        q = deque([(i, j)])
        dist = [[-1]*w for _ in range(h)]
        dist[i][j] = 0
        while q:
            x, y = q.popleft()
            for k, l in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                if 0 <= x+k < h and 0 <= y+l < w and dist[x+k][y+l] < 0 and s[x+k][y+l] == '.':
                    dist[x+k][y+l] = dist[x][y] + 1
                    ans = max(ans, dist[x+k][y+l])
                    q.append((x+k, y+l))
print(ans)

Solution (Python):
h,w = map(int,input().split())
s = [input() for i in range(h)]
ans = 0
from collections import deque
for i in range(h):
    for j in range(w):
        if s[i][j]=='
        q = deque([(i,j)])
        reach = [[-1]*w for _ in range(h)]
        reach[i][j] = 0
        c = 0
        while q:
            x,y = q.popleft()
            for k,l in[[-1,0],[0,1],[1,0],[0,-1]]:
                if 0<=x+k<h and 0<=y+l<w:
                    if reach[x+k][y+l]<0 and s[x+k][y+l]=='.':
                        reach[x+k][y+l] = reach[x][y]+1
                        ans = max(ans,reach[x+k][y+l])
                        q.append((x+k,y+l))
            
print(ans)

Solution (Python):
def main():
    import numpy as np
    h,w = map(int,input().split())
    maize = []
    for i in range(h):
        s = input()
        maize.append(s)
    ans = 0
    for i in range(h):
        for j in range(w):
            que = [[i,j]]
            if maize[i][j] == '.':
                dis = [[-1 for i in range(w)] for i in range(h)]
                dis[i][j] = 0
                while len(que)>0:
                    q = que.pop(0)
                    if q[0]>0:
                        n = [q[0]-1,q[1]]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                    if q[0] < h-1:
                        n = [q[0]+1,q[1]]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                    if q[1] > 0:
                        n = [q[0],q[1]-1]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                    if q[1] < w-1:
                        n = [q[0],q[1]+1]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                dis = np.array(dis)
                if np.max(dis)>ans:
                    ans = np.max(dis)
    print(ans)
    

if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
def main():
    H,W = map(int, input().split())
    S = [[0]*W for _ in range(H)]
    for i in range(H):
        
        tmp = list(map(lambda x:1 if x=='.' else 0, input()))
        S[i] = tmp
    
    ans = 0
    for i in range(H):
        for j in range(W):
            
            
            if S[i][j] == 0:
                continue
            dist = [[-1]*W for _ in range(H)]
            dist[i][j] = 0
            que = deque([(i,j)])
            while que:
                si,sj = que.pop()
                for r,b in [(1,0),(0,1),(-1,0),(0,-1)]: 
                    gi = si+r
                    gj = sj+b
                    
                    if gi<0 or (H-1)<gi or gj<0 or (W-1)<gj:
                        continue
                    
                    if S[gi][gj] == 0:
                        continue
                    
                    if dist[gi][gj]!=-1:
                        continue
                    dist[gi][gj] = dist[si][sj]+1
                    que.appendleft((gi,gj))
            ans = max(ans,max([max(d) for d in dist]))
    print(ans)

main()

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

M = []
H = 0
W = 0
qx = deque()
qy = deque()
qc = deque()

def main():
    global M,H,W
    H,W = map(int, input().split())  
    for i in range(H):
        M.append(list(input()))

    startX = 0
    startY = 0
    mx = 0
    for i in range(H):
        for j in range(W):
            if M[i][j]=='.':
                rv =  bfs(i,j)
                if rv > mx:
                    mx = rv


    print(mx)

def bfs(y,x):
    global M,H,W
    Mtemp = deepcopy(M)
    Mtemp[y][x] = '
    qx.append(x)
    qy.append(y)
    qc.append(0)
    cnt = 0

    while len(qx) !=0:
        x =  qx.popleft()
        y =  qy.popleft()
        cnt = qc.popleft()

        if x-1>=0:
            if Mtemp[y][x-1] == '.':
                Mtemp[y][x-1] = '
                qx.append(x-1)
                qy.append(y)
                qc.append(cnt+1)
        if x+1<W:
            if Mtemp[y][x+1] == '.':
                Mtemp[y][x+1] = '
                qx.append(x+1)
                qy.append(y)
                qc.append(cnt+1)
        if y-1>=0:
            if Mtemp[y-1][x] == '.':
                Mtemp[y-1][x] = '
                qx.append(x)
                qy.append(y-1)
                qc.append(cnt+1)
        if y+1<H:
            if Mtemp[y+1][x] == '.':
                Mtemp[y+1][x] = '
                qx.append(x)
                qy.append(y+1)
                qc.append(cnt+1)

    return cnt




if __name__ == '__main__':
    main()

Solution (Python):
import sys
import copy
sys.setrecursionlimit(9**9)
H,W=map(int,input().split())
M=[list(input()) for _ in range(H)]
N=copy.deepcopy(M)
m=x=y=0
def d(c,P):
    global m,x,y
    Q=[]
    for p in P:
        h=p[0]
        w=p[1]
        if h!=H-1 and M[h+1][w]=='.':
            M[h+1][w]='
            Q.append([h+1,w])
        if h!=0 and M[h-1][w]=='.':
            M[h-1][w]='
            Q.append([h-1,w])
        if w!=W-1 and M[h][w+1]=='.':
            M[h][w+1]='
            Q.append([h,w+1])
        if w!=0 and M[h][w-1]=='.':
            M[h][w-1]='
            Q.append([h,w-1])
    if len(Q)!=0:
      c+=1
      return d(c,Q)
    else:
        m=max(m,c)
f=False
for i in range(H):
    for j in range(W):
        if M[i][j]=='.':
            M[i][j]='
            d(0,[[i,j]])
            M=copy.deepcopy(N)
print(m)

Solution (Python):
import sys
import copy
sys.setrecursionlimit(9**9)
H,W=map(int,input().split())
M=[list(input()) for _ in range(H)]
N=copy.deepcopy(M)
m=x=y=0
def d(c,P):
    global m,x,y
    Q=[]
    for p in P:
        h=p[0]
        w=p[1]
        if h!=H-1 and M[h+1][w]=='.':
            M[h+1][w]='
            Q.append([h+1,w])
        if h!=0 and M[h-1][w]=='.':
            M[h-1][w]='
            Q.append([h-1,w])
        if w!=W-1 and M[h][w+1]=='.':
            M[h][w+1]='
            Q.append([h,w+1])
        if w!=0 and M[h][w-1]=='.':
            M[h][w-1]='
            Q.append([h,w-1])
    if len(Q)!=0:
      c+=1
      return d(c,Q)
    else:
        m=max(m,c)
f=False
for i in range(H):
    for j in range(W):
        if M[i][j]=='.':
            M[i][j]='
            d(0,[[i,j]])
            M=copy.deepcopy(N)
print(m)

Solution (Python):
from collections import deque
import numpy as np
H,W = map(int,input().split())
s = [list(input()) for _ in range(H)]

state = [[-1]*W for _ in range(H)]
start_list = []
for i in range(H):
    for j in range(W):
        if s[i][j] == '.':
            start_list.append((i,j))
            state[i][j] = 0

def dfs(black_cells,state):
    d = 0
    dist = [[0]*W for _ in range(H)]
    while black_cells:
        h, w =  black_cells.popleft()
        d = dist[h][w]
        for dy, dx in ((1,0), (0,1), (-1,0), (0,-1)):
            new_h = h+dy
            new_w = w+dx
            if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                continue
            if state[new_h][new_w] == 0 and dist[new_h][new_w] == 0:
                dist[new_h][new_w] = d+1
                if d == 0:dist[h][w] = 1
                black_cells.append((new_h, new_w))
    
    return np.array(dist).max()

ans = 0
for start in start_list:
    black_cells = deque()
    black_cells.append((start))
    ans = max(ans, dfs(black_cells,state))
print(ans)

Solution (Python):
from collections import deque
H, W = [int(_) for _ in input().split()]
e = "
maze = [e]
for i in range(H):
    s = input()
    maze.append("
maze.append(e)
max_count = 0
for h in range(H):
    for w in range(W):
        visited = [[False for i in range(W+2)] for j in range(H+2)]
        visited[h+1][w+1] = True
        if maze[h+1][w+1] == '
            continue
        q = deque([[w+1, h+1, 0]])
        def search(x, y, c):
            if maze[y][x] == '.' and not visited[y][x]:
                q.append([x, y, c+1])
                visited[y][x] = True
        count = 0
        while len(q) != 0:
            p = q.popleft()
            search(p[0]+1, p[1], p[2])
            search(p[0]-1, p[1], p[2])
            search(p[0], p[1]+1, p[2])
            search(p[0], p[1]-1, p[2])
            count = p[2]
        max_count = max(max_count, count)
print(max_count)

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

INF = 10**9
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]
def update(v, h, d, dist, q):
    if dist[W*v+h] != INF:
        return
    dist[W*v+h] = d
    q.append((v, h))

ans = 0
for si in range(H):
    for sj in range(W):
        if s[si][sj] == "
            continue
        dist = [INF]*H*W
        dist[W*si+sj] = 0
        q = [(si, sj)]
        while len(q) > 0:
            current = q.pop(0)
            v = current[0]
            h = current[1]
            for dir in range(4):
                ni = v+di[dir]
                nj = h+dj[dir]
                
                if ni<0 or H<=ni or nj<0 or W<= nj:
                    continue
                if s[ni][nj] == "
                    continue
                update(ni, nj, dist[W*v+h]+1,dist, q)
        for v in dist:
            if v == INF:
                continue
            ans = max(ans, v)
print(ans)

Solution (Python):
import sys
from collections import deque

input = lambda: sys.stdin.readline().rstrip()


def bfs(H, W, start, s):

    q = deque()
    q.append(start)
    d = [[-1 for _ in range(W)] for _ in range(H)]
    d[start[1]][start[0]] = 0
    move = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    while q:
        now = q.popleft()
        x, y = now
        for m in move:
            n_x, n_y = x + m[0], y + m[1]
            if (0 <= n_x and n_x < W) and (0 <= n_y and n_y < H):
                if d[n_y][n_x] == -1 and s[n_y][n_x] == '.':
                    d[n_y][n_x] = d[y][x] + 1
                    q.append((n_x, n_y))

    r = 0
    for t in d:
        r = max(r, max(t))

    return r


def solve():
    H, W = map(int, input().split())
    s = [list(input()) for _ in range(H)]

    ans = 0
    for x in range(W):
        for y in range(H):
            if s[y][x] == '.':
                start = (x, y)
                d = bfs(H, W, start, s)
                ans = max(ans, d)

    print(ans)


if __name__ == '__main__':
    solve()

Solution (Python):
from collections import deque

H, W = map(int, input().split())
s = []
for _ in range(H):
    s.append(input())
dh = [0, 0, 1, -1]
dw = [1, -1, 0, 0]
ans = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == "
            continue
        dismax = 0
        dist = [[-1 for j in range(W)] for i in range(H)]
        queue = deque([[i, j]])
        dist[i][j] = 0
        while len(queue) != 0:
            now = queue.popleft()
            h = now[0]
            w = now[1]
            for k in range(4):
                nh = h + dh[k]
                nw = w + dw[k]
                if nh < 0 or nw < 0 or nh >= H or nw >= W:
                    continue
                if dist[nh][nw] != -1 or s[nh][nw] == "
                    continue
                else:
                    dist[nh][nw] = dist[h][w] + 1
                    dismax = max(dist[nh][nw], dismax)
                    queue.append([nh, nw])
        ans = max(ans, dismax)
print(ans)

Solution (Python):

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)


from collections import Counter,deque,defaultdict
import itertools





h,w=n1()
s=s4(h)
def make_around(s):
    sss=[[-1]*(w+2)]
    for line in s:
        sss.append([-1]+[-1 if i=="
    sss.append([-1]*(w+2))
    return sss

s=make_around(s)
d=[]
for i in range(1,h+1):
    for j in range(1,w+1):
        if s[i][j]==0:
            d.append((i,j))

from copy import deepcopy
ans=0
for i in range(len(d)):
    ss=deepcopy(s)
    x,y=d[i]
    q=deque([(x,y)])
    ss[x][y]=1
    while len(q)>0:
        x,y=q.popleft()
        if ss[x+1][y]==0:
            ss[x+1][y]=ss[x][y]+1
            q.append((x+1,y))
        if ss[x-1][y]==0:
            ss[x-1][y]=ss[x][y]+1
            q.append((x-1,y))
        if ss[x][y+1]==0:
            ss[x][y+1]=ss[x][y]+1
            q.append((x,y+1))
        if ss[x][y-1]==0:
            ss[x][y-1]=ss[x][y]+1
            q.append((x,y-1))
    ans=max(ans,max(list(itertools.chain.from_iterable(ss))))
print(ans-1)

Solution (Python):

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)


from collections import Counter,deque,defaultdict
import itertools





h,w=n1()
s=s4(h)
def make_around(s,h):
    sss=[[-1]*(w+2)]
    for line in s:
        sss.append([-1]+[-1 if i=="
    sss.append([-1]*(w+2))
    return sss

s=make_around(s,h)
d=[]
for i in range(1,h+1):
    for j in range(1,w+1):
        if s[i][j]==0:
            d.append((i,j))

from copy import deepcopy
ans=0
for i in range(len(d)):
    ss=deepcopy(s)
    x,y=d[i]
    q=deque([(x,y)])
    ss[x][y]=1
    while len(q)>0:
        x,y=q.popleft()
        if ss[x+1][y]==0:
            ss[x+1][y]=ss[x][y]+1
            q.append((x+1,y))
        if ss[x-1][y]==0:
            ss[x-1][y]=ss[x][y]+1
            q.append((x-1,y))
        if ss[x][y+1]==0:
            ss[x][y+1]=ss[x][y]+1
            q.append((x,y+1))
        if ss[x][y-1]==0:
            ss[x][y-1]=ss[x][y]+1
            q.append((x,y-1))
    ans=max(ans,max(list(itertools.chain.from_iterable(ss))))
print(ans-1)

Solution (Python):

from collections import deque
import copy

h,w=map(int, input().split())
d=[list(input()) for i in range(h)]
inf=10**7

def bfs(sx,sy):
    a=copy.deepcopy(d)
    for i in range(h):
        for j in range(w):
            if a[i][j]=='.':
                a[i][j]=inf
    que=deque([[sy,sx]])
    a[sy][sx]=0

    while que:
        y,x=que.popleft()
        for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            ny,nx=y+i,x+j
            if nx>=0 and nx<w and ny>=0 and ny<h:
                dist=a[ny][nx]
                if dist!='
                    if dist>a[y][x]+1:
                        a[ny][nx]=a[y][x]+1
                        que.append([ny,nx])

    m=0
    for i in range(h):
        for j in range(w):
            if a[i][j]!='
                if a[i][j]>m:
                    m=a[i][j]
    return m
    

ans=0
for i in range(h):
    for j in range(w):
        if d[i][j]=='.':
            if ans<bfs(j,i):
                ans=bfs(j,i)
print(ans)

Solution (Python):

from collections import deque


r,c = map(int,input().split())
c_list = [list(input()) for nesya in range(r)]
for hoge in c_list:
  hoge.insert(0,'
  hoge.append('
c_list.insert(0,['
c_list.append(['

ans = 0
for j in range(r+2):
  for i in range(c+2):
    
    d = deque()
    
    hoge_list = [[-1]*(c+2) for motsu in range(r+2)]
    if  c_list[j][i] == '
      continue
    else:
      
      d.append((j,i))
      hoge_list[j][i] = 0

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

      
      while len(d) > 0:
        
        coord = d.popleft()
  
        
        for k in range(4):
          
          x = coord[1] + move[k][1]
          y = coord[0] + move[k][0]
    
          
          if hoge_list[y][x] != -1:
            pass
          
          elif c_list[y][x] == '
            hoge_list[y][x] = -2
          
          else:
            
            hoge_list[y][x] = hoge_list[coord[0]][coord[1]] + 1
            ans = max(hoge_list[y][x],ans)
            
            d.append((y,x))
    


print(ans)

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

for sx in range(w):
  for sy in range(h):
    if G[sy][sx] == "
      continue
      
    dist = [[-1] * w for i in range(h)]
    dist[sy][sx] = 0
    que = deque([[sy, sx]])
    
    while len(que):
      y,x = que.popleft()
      for dx,dy in directions:
        nx = x + dx
        ny = y+ dy
        if not (0<=nx<w and 0<=ny<h) or G[ny][nx]=="
          continue
        if dist[ny][nx] != -1:
          continue
      
        dist[ny][nx] = dist[y][x] +1
        que.append([ny,nx])
      
    ans = max(ans, max([max(d) for d in dist]))
    
print(ans)

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

def bfs(s_l, sy, sx, h, w):
    visited = [ [-1]*w for i in range(h)]
    q = deque([[sy,sx]])
    visited[sy][sx] = 0
    last_dist = -1
    while q:
        y, x = q.popleft()
        
        
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            n_y, n_x = y+j, x+k
            if n_y >= h or n_x >= w or n_y < 0 or n_x < 0:
                continue
            if s_l[n_y][n_x] == '.' and visited[n_y][n_x] == -1:
                visited[n_y][n_x] = visited[y][x] + 1
                last_dist = visited[n_y][n_x]
                q.append([n_y,n_x])
    return last_dist

def main():
    h, w = map(int, input().split()) 
    s_l = []
    all_dot_cnt = 0
    for i in range(h):
        row = list(input())
        s_l.append(row)
        all_dot_cnt += row.count('.')
    
    curr_ans = -1
    visited = [ [-1]*w for i in range(h)]
    for i in range(h):
        for j in range(w):
            if s_l[i][j] == '.':
                res = bfs(s_l, i, j, h, w)
                if res > curr_ans:
                    curr_ans = res
    print(curr_ans)

if __name__ == "__main__":
    main()