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):
H, W = map(int, input().split())
S = []
S.append(['
for _ in range(H):
  s = input()
  s = '
  S.append([])
  for k in range(W+2):
    S[-1].append(s[k])
S.append(['
b = 0
start = []
for h in range(1, H+1):
  for w in range(1, W+1):
    if S[h][w] == '.':
      c = 0
      b += 1
      if S[h+1][w] == '.':
        c += 1
      if S[h-1][w] == '.':
        c += 1
      if S[h][w+1] == '.':
        c += 1
      if S[h][w-1] == '.':
        c += 1
      if c == 1:
        start.append([h, w])
if len(start) == 0:
  for h in range(1, H+1):
    for w in range(1, W+1):
      if S[h][w] == '.':
        c = 0
        if S[h+1][w] == '.':
          c += 1
        if S[h-1][w] == '.':
          c += 1
        if S[h][w+1] == '.':
          c += 1
        if S[h][w-1] == '.':
          c += 1
        if c == 2:
          start.append([h, w])

"""
def solve(nowh, noww, point):
  counter[nowh][noww] = point
  flag = True
  if counter[nowh+1][noww] > point + 1:
    solve(nowh+1, noww, point+1)
    flag = False
  if counter[nowh-1][noww] > point + 1:
    solve(nowh-1, noww, point+1)
    flag = False
  if counter[nowh][noww+1] > point + 1:
    solve(nowh, noww+1, point+1)
    flag = False
  if counter[nowh][noww-1] > point + 1:
    solve(nowh, noww-1, point+1)
    flag = False
  if flag:
    return 0
ans = 0
for item in start:
  original_counter = [[b for _ in range(W+2)] for _ in range(H+2)]
  for k in range(H+2):
    for j in range(W+2):
      if S[k][j] == '
        original_counter[k][j] = -1
  counter = original_counter
  solve(item[0], item[1], 0)
  anskouho = 0
  for h in range(1, H+1):
    for w in range(1, W+1):
      anskouho = max(anskouho, counter[h][w])
  ans = max(ans, anskouho)

print(ans)
"""

def solve(now, point):
  nextlist = []
  for n in now:
    if counter[n[0]+1][n[1]] > point + 1:
      counter[n[0]+1][n[1]] = point + 1
      nextlist.append([n[0]+1, n[1]])
    if counter[n[0]][n[1]+1] > point + 1:
      nextlist.append([n[0], n[1]+1])
      counter[n[0]][n[1]+1] = point + 1
    if counter[n[0]-1][n[1]] > point + 1:
      nextlist.append([n[0]-1, n[1]])
      counter[n[0]-1][n[1]] = point + 1
    if counter[n[0]][n[1]-1] > point + 1:
      nextlist.append([n[0], n[1]-1])
      counter[n[0]][n[1]-1] = point + 1
  if len(nextlist) == 0:
    anskouho.append(point)
    return 0
  else:
    solve(nextlist, point+1)

anskouho = []
for item in start:
  original_counter = [[b for _ in range(W+2)] for _ in range(H+2)]
  for k in range(H+2):
    for j in range(W+2):
      if S[k][j] == '
        original_counter[k][j] = -1
  counter = original_counter
  counter[item[0]][item[1]] = 0
  solve([item], 0)
print(max(anskouho))

Solution (Python):
H, W = map(int, input().split())
S = []
S.append(['
for _ in range(H):
  s = input()
  s = '
  S.append([])
  for k in range(W+2):
    S[-1].append(s[k])
S.append(['
b = 0
start = []
for h in range(1, H+1):
  for w in range(1, W+1):
    if S[h][w] == '.':
      c = 0
      b += 1
      if S[h+1][w] == '.':
        c += 1
      if S[h-1][w] == '.':
        c += 1
      if S[h][w+1] == '.':
        c += 1
      if S[h][w-1] == '.':
        c += 1
      if c == 1:
        start.append([h, w])
if len(start) == 0:
  for h in range(1, H+1):
    for w in range(1, W+1):
      if S[h][w] == '.':
        c = 0
        if S[h+1][w] == '.':
          c += 1
        if S[h-1][w] == '.':
          c += 1
        if S[h][w+1] == '.':
          c += 1
        if S[h][w-1] == '.':
          c += 1
        if c == 2:
          start.append([h, w])

def solve(nowh, noww, point):
  counter[nowh][noww] = point
  flag = True
  if counter[nowh+1][noww] > point + 1:
    solve(nowh+1, noww, point+1)
    flag = False
  if counter[nowh-1][noww] > point + 1:
    solve(nowh-1, noww, point+1)
    flag = False
  if counter[nowh][noww+1] > point + 1:
    solve(nowh, noww+1, point+1)
    flag = False
  if counter[nowh][noww-1] > point + 1:
    solve(nowh, noww-1, point+1)
    flag = False
  if flag:
    return 0

ans = 0
for item in start:
  original_counter = [[b for _ in range(W+2)] for _ in range(H+2)]
  for k in range(H+2):
    for j in range(W+2):
      if S[k][j] == '
        original_counter[k][j] = -1
  counter = original_counter
  solve(item[0], item[1], 0)
  anskouho = 0
  for h in range(1, H+1):
    for w in range(1, W+1):
      anskouho = max(anskouho, counter[h][w])
  ans = max(ans, anskouho)

print(ans)

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

h, w = list(map(int, input().split()))
t = h * w

s = ""
for i in range(h):
    s += input().replace( '\n' , '' )



adj = [[] for _ in range(t)]

for i in range(t):
    
    if i % w != 0 and s[i-1] == ".":
        adj[i].append(i-1)
    if i % w != w-1 and s[i+1] == ".":
        adj[i].append(i+1)
    
    if i - w >= 0 and s[i-w] == ".":
        adj[i].append(i-w)
    if i + w < t and s[i+w] == ".":
        adj[i].append(i+w)



m = 0
for i in range(t):
    if s[i] == "
        pass
    else:
        
        depth = [0] * t
        visited = [False] * t
        q = deque([i])
        visited[i] = True
        while len(q) > 0:
            v = q.popleft()
            for w in adj[v]:
                if not visited[w]:
                    q.append(w)
                    visited[w] = True
                    depth[w] = depth[v] + 1
        
        
        
        m = max(m, max(depth))

print(m)

Solution (Python):
import collections

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

def bfs(x0, y0):
    visited = [[0 for _ in range(w)] for _ in range(h)]
    deq = collections.deque()
    deq.append((x0, y0, -1))

    mx = 0
    while len(deq) > 0:
        x, y, d = deq.popleft()
        nd = d + 1
        visited[x][y] = 1
        mx = max(mx, nd)

        for dx, dy in [(-1, 0), (0, -1), (+1, 0), (0, +1)]:
            nx = x + dx
            ny = y + dy
            if not (0 <= nx < h) or not (0 <= ny < w):
                
                continue
            if smat[nx][ny] == '
                
                continue
            if visited[nx][ny] == 1:
                
                continue
            v = (nx, ny, nd)
            deq.append(v)
    
    return mx

if all(all(col == '.' for col in row) for row in smat):
    print((w - 1) + (h - 1))
else:
    mxall = 0
    for x0 in range(h):
        for y0 in range(w):
            if smat[x0][y0] == '.':
                mx = bfs(x0, y0)
                mxall = max(mxall, mx)
    print(mxall)

Solution (Python):
from collections import deque
from copy import deepcopy
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
ans=0
for i in range(h):
    for j in range(w):
        
        count=[[0]*w for _ in range(h)]
        if s[i][j]==".":
            s_copy=deepcopy(s)
            que=deque()
            que.append([i,j])
            s_copy[i][j]="
            
            while que:
                
                x,y=tuple(que.popleft())
                dx_dy=[[1,0],[0,1],[-1,0],[0,-1]]
                for k in range(4):
                    nx=x+dx_dy[k][0]
                    ny=y+dx_dy[k][1]
                    if 0<=nx<=h-1 and 0<=ny<=w-1:
                        if s_copy[nx][ny]==".":
                            s_copy[nx][ny]="
                            count[nx][ny]=count[x][y]+1
                            que.append([nx,ny])
        
            temp=0
            for l in range(h):
              temp=max(temp,max(count[l]))
            ans=max(temp,ans)
print(ans)

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


def bfs(table, i, j, h, w):
    dq = deque()
    ans = 0
    dq.append((i, j, 0))  
    table[i][j] = "
    while dq:
        x, y, dis = dq.popleft()
        ans = max(ans, dis)
        if x > 0 and (x - 1, y) and table[x - 1][y] != "
            dq.append((x - 1, y, dis + 1))
            table[x - 1][y] = "
        if x < h - 1 and (x + 1, y) and table[x + 1][y] != "
            dq.append((x + 1, y, dis + 1))
            table[x + 1][y] = "
        if y > 0 and (x, y - 1) and table[x][y - 1] != "
            dq.append((x, y - 1, dis + 1))
            table[x][y - 1] = "
        if y < w - 1 and (x, y + 1) and table[x][y + 1] != "
            dq.append((x, y + 1, dis + 1))
            table[x][y + 1] = "

    return ans


def main():
    h, w = [int(i) for i in input().strip().split()]
    grid = [list(input()) for _ in range(h)]
    ans = 0
    for i in range(h):
        for j in range(w):
            if grid[i][j] == ".":
                _grid = deepcopy(grid)
                max_path = bfs(_grid, i, j, h, w)
                ans = max(ans, max_path)

    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
from collections import deque
 
def main():
    H,W=map(int,input().split())
    S=[]
    for i in range(H):
        s=input()
        S.append(s)
 
    G=[]
    for i in range(H):
        for j in range(W):
            tmp=[]
            if S[i][j]=="
                G.append(tmp)
                continue
            if i-1>=0:
                if S[i-1][j]==".":
                    tmp.append((i-1)*W+j)
            if i+1<=H-1:
                if S[i+1][j]==".":
                    tmp.append((i+1)*W+j)
            if j-1>=0:
                if S[i][j-1]==".":
                    tmp.append(i*W+j-1)
            if j+1<=W-1:
                if S[i][j+1]==".":
                    tmp.append(i*W+j+1)
            G.append(tmp)
 
    res=0
 
    for start in range(H*W):
        dist = 0
        v = [-1 for _ in range(H * W)]
        que=deque([])
        que.append(start)
        v[start]=dist
        while len(que)>0:
            next_index=que.popleft()
            next=G[next_index]
            for i in next:
                if v[i]==-1:
                    que.append(i)
                    v[i]=v[next_index]+1
 
        if max(v)>=res:
            res=max(v)
 
    print(res)
 
 
if __name__=="__main__":
    main()

Solution (Python):
import os, sys, re, math


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


def set_moves(x, y, moves):
    if S[y + 1][x + 1] != '.':
        return
    if 0 <= grid[y][x] < moves:
        return

    grid[y][x] = moves
    set_moves(x, y - 1, moves + 1)
    set_moves(x, y + 1, moves + 1)
    set_moves(x - 1, y, moves + 1)
    set_moves(x + 1, y, moves + 1)


S = []
S.append('
has_wall = False
for i in range(H):
    s = input()
    has_wall |= '
    S.append('
S.append('

if not has_wall:
    result = W + H - 2
else:
    result = 0
    for gy in range(H):
        for gx in range(W):
            if S[gy + 1][gx + 1] != '.':
                continue
            grid = []
            for i in range(H):
                grid.append([-1] * W)
            set_moves(gx, gy, 0)

            result = max(result, max([max(row) for row in grid]))

print(result)

Solution (Python):
h, w = map(int, input().split())
s = [input() for _ in range(h)]

def bfs(x, y):
    q = []
    dp = {}
    def qpush(x, y, t):
        if 0 <= x < w and 0 <= y < h and s[y][x] != '
            q.append((x, y))
            dp[(x, y)] = t

    qpush(x, y, 0)
    while len(q) > 0:
        (x, y) = q.pop(0)
        qpush(x + 1, y, dp[(x, y)] + 1)
        qpush(x, y - 1, dp[(x, y)] + 1)
        qpush(x - 1, y, dp[(x, y)] + 1)
        qpush(x, y + 1, dp[(x, y)] + 1)
    return dp.get((x, y), 0)

t = 0
for y in range(h):
    for x in range(w):
        t = max(t, bfs(x, y))
print(t)

Solution (Python):
def resolve():
    H, W = list(map(int, input().split()))
    S = [list(input()) for _ in range(H)]
    import collections
    maxdist = 0

    for startx in range(H):
        for starty in range(W):
            if S[startx][starty] == "
                continue
            visited = [[-1 for _ in range(W)] for __ in range(H)]
            visited[startx][starty] = 0
            q = collections.deque([(startx, starty)])
            while q:
                x, y = q.pop()
                for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                    nx = x + dx
                    ny = y + dy
                    if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "
                        visited[nx][ny] = visited[x][y] + 1
                        q.appendleft((nx, ny))
            maxdist = max(maxdist,max(sum(visited, [])))
    print(maxdist)
    

if '__main__' == __name__:
    resolve()

Solution (Python):
r, c = list(map(int, input().split(' ')))
matrix = []
for i in range(r):
    matrix.append(input())

ans = 0
cost = {}  
for i in range(r):
    for j in range(c):
        if matrix[i][j] == '
            continue
        start = (i, j)
        cost[(i,j), (i,j)] = 0
        q = [start]
        while q:
            ti, tj = q.pop(0)
            for ni, nj in [(ti-1, tj), (ti, tj-1), (ti+1, tj), (ti, tj+1)]:
                if ni < 0 or nj < 0 or ni >= r or nj >= c or matrix[ni][nj] == '
                    continue
                if cost.get(((i,j), (ni, nj)), 99999999999999999) > cost[(i,j), (ti, tj)] + 1:
                    cost[(i,j), (ni, nj)] = cost[(i,j), (ti, tj)] + 1
                    ans = max(ans, cost[(i,j), (ni, nj)])
                    
                    q.append((ni, nj))
print(ans)

Solution (Python):
from collections import deque
H, W = map(int, input().split())
S_raw = [list(input()) for _ in range(H)]
m = 0
def calc(h,w):
    S = [list(S_raw[i][j] for j in range(W)) for i in range(H)]
    S[h][w]=0
    queue = deque([(h,w)])
    while queue:
        q = queue.popleft()
        for x in ((q[0]-1, q[1]),(q[0]+1, q[1]), (q[0], q[1]-1), (q[0], q[1]+1)):
          if 0<=x[0]<=H-1 and 0<=x[1]<=W-1:
            if S[x[0]][x[1]]==".":
              S[x[0]][x[1]] = S[q[0]][q[1]]+1
              queue.append(x)
    return max(S[h][w] for w in range(W) for h in range(H) \
                    if str(S[h][w]).isdigit())    
for h in range(H):
  for w in range(W):
    if S_raw[h][w]==".":
        m = max(m, calc(h,w))
print(m)

Solution (Python):
from collections import deque

def main():
    h, w = map(int, input().split())
    ls = [input() for _ in range(h)]

    def trans(a, b):
        return a * w + b

    ls2 = [[] for _ in range(h * w)]

    for i in range(h):
        for j in range(w):
            
            if ls[i][j] == '
                continue
            if i >= 1 and ls[i-1][j] != '
                ls2[trans(i, j)].append(trans(i-1, j))
            if i <= h-2 and ls[i+1][j] != '
                ls2[trans(i, j)].append(trans(i + 1, j))
            if j <= w-2 and ls[i][j+1] != '
                ls2[trans(i, j)].append(trans(i, j + 1))
            if j >= 1 and ls[i][j-1] != '
                ls2[trans(i, j)].append(trans(i, j - 1))


    


    def route(i):
        count = 1
        ss = deque(ls2[i])
        next = deque()
        explored = {i}
        while ss or next:
            if not ss:
                count +=1
                ss = next
                next = deque()
            now =ss.popleft()
            if now in explored:
                continue
            else:
                explored.add(now)
                next.extend(ls2[now])
        return count-1
    ans = 0
    for i in range(h * w - 1):
        if ls2[i] == []:
            continue
        ans = max(ans, route(i))

    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
import math
import collections
import fractions
import itertools
import functools
import operator
import numpy as np

def solve():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = 0
    can_move = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    for x in range(h):
        for y in range(w):
            if maze[x][y] == "
                continue
            dist = [[0]*w for _ in range(h)]
            stack = collections.deque()
            stack.append([x,y])
            while stack:
                h2, w2 = stack.popleft()
                for i, j in can_move:
                    newh, neww = h2+i, w2+j
                    if newh < 0 or neww < 0 or newh >= h or neww >= w:
                        continue
                    elif maze[newh][neww] != "
                        dist[newh][neww] = dist[h2][w2]+1
                        stack.append([newh, neww])
            dist[x][y] = 0
            ans = max(ans, np.max(dist))
    print(ans)
    return 0

if __name__ == "__main__":
    solve()

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


from bisect import bisect_left, bisect_right
import heapq

sys.setrecursionlimit(1000000)


input = sys.stdin.readline

getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = 10 ** 20
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)


def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD


def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD


def fact_and_inv(SIZE):
    inv = [0] * SIZE  
    fac = [0] * SIZE  
    finv = [0] * SIZE  
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def kaijyo(n):
    ret = [1]
    for i in range(1, n + 1):
        ret.append((ret[-1] * i)% MOD)
    return ret

def warshall_floyd(d, n):
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

class TwoDimGrid:
    
    def __init__(self, h, w, wall="
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid

    def pos(self, x, y):
        return y * (self.w + 2) + x + 1

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]

        ans = 0
        for i in range(1, self.h + 1):
            for j in range(1, self.w + 1):
                
                cx, cy = j, i
                if grid[cy][cx] == ".":
                    ret = self.search_each(cx, cy)
                    ans = max(ans, ret)
        print(ans)

    def search_each(self, x, y):
        grid = self.grid
        d = deque()
        d.append((x,y))
        dist = [INF for i in range(self.size)]
        
        dist[self.pos(x,y)] = 0
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        ret = 0
        while d:
            cx, cy = d.pop()
            ccos = dist[self.pos(cx, cy)]
            ret = max(ret, ccos)
            for mv in move:
                dx, dy = mv
                nx, ny = cx + dx, cy + dy
                
                if grid[ny][nx] == ".":
                    if dist[self.pos(nx, ny)] > ccos + 1:
                        dist[self.pos(nx, ny)] = ccos + 1
                        d.append((nx, ny))

        return max([r for r in dist if r != INF])


def solve():
    h, w = getList()
    G = TwoDimGrid(h, w)
    G.search()
    return



def main():
    n = getN()
    for _ in range(n):
        solve()


if __name__ == "__main__":
    
    solve()

Solution (Python):
from collections import deque

n , m = map(int, input().split())
maze = [['
maze = [['

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

costma=0
for i in range(1,n+1):
    for j in range(1,m+1):
        v = [[0]*(m+2) for i in range(n+2)]
        d = deque()
        d.append((i,j,0))
        v[i][j]=1
        while d:
            y,x,cost=d.popleft()
            if maze[y][x]=='.':
                for dy,dx in step:
                    if maze[y+dy][x+dx]=='.' and v[y+dy][x+dx]==0:
                        v[y+dy][x+dx]=1
                        d.append((y+dy,x+dx,cost+1))
                        costma=max(cost+1,costma)
print(costma)

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

for i in range(h):
  s=[x for x in input()]
  l.append(s)

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

def bfs(x,y):
  done=[[-1 for i in range(w)] for j in range(h)]
  ans,cnt = 0,0
  que=[[x,y,cnt]]
  done[y][x]=0

  while(que):
    nx,ny,cnt = que.pop(0)

    for dx,dy in move:
      mx=nx+dx
      my=ny+dy

      if 0<=mx<w and 0<=my<h and done[my][mx]==-1 and l[my][mx]==".":
        done[my][mx]=cnt+1
        que.append([mx,my,cnt+1])
        ans=max(ans,cnt+1)

  return ans


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

Solution (Python):
def solve():
    def bfs(maze, start):
        from collections import deque

        directions = ((-1,0), (1,0), (0,-1), (0, 1))
        H = len(maze)
        W = len(maze[0])
        visited = []
        for i in range(H):
            visited.append(maze[i][:])

        nexts = deque()
        nexts.append((start, 0))
        x,y = start
        visited[x][y] = '
        longest_distance = 0
        while nexts:
            cur_pos,cur_distance = nexts.popleft()
            longest_distance = max(cur_distance, longest_distance)
            x,y = cur_pos
            for direction in directions:
                dx,dy = direction
                next_x = x + dx
                next_y = y + dy
                next_pos = (next_x, next_y)
                if 0 <= next_x < H and 0 <= next_y < W and next_pos:
                    if visited[next_x][next_y] == '.':
                        visited[next_x][next_y] = '
                        nexts.append(((next_x, next_y), cur_distance+1))
        return longest_distance

    H,W = [int(i) for i in input().split()]
    maze = []
    for i in range(H):
        row = [c for c in input()]
        maze.append(row)

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

    print(ans)


if __name__ == "__main__":
    solve()

Solution (Python):

from collections import deque

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


def bfs(si, sj):
    offset = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    INF = 10 ** 9 + 7
    d = [[INF] * W for _ in range(H)]
    d[si][sj] = 0 if X[si][sj] == "." else INF
    q = deque()
    q.append((si, sj))
    while q:
        u, v = q.popleft()
        for i, j in offset:
            if (0 <= u + i < H and 0 <= v + j < W and X[u + i][v + j] == "."
                    and d[u + i][v + j] > d[u][v] + 1):
                d[u + i][v + j] = d[u][v] + 1
                q.append((u + i, v + j))

    res = 0
    for x in d:
        for v in x:
            if v < INF:
                res = max(res, v)

    return res


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

print(ans)

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


def max_dist(input_maze,startx,starty,mazex,mazey):
    input_maze[starty][startx]=0
    que=deque([[starty,startx]])

    while que:

        y,x=que.popleft()
        for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if (nexty>=0) & (nextx>=0) & (nextx<mazex) & (nexty<mazey):
                dist=input_maze[nexty][nextx]
                if dist!=-1:
                    if (dist>input_maze[y][x]+1) & (dist > 0):
                        input_maze[nexty][nextx]=input_maze[y][x]+1
                        que.append([nexty,nextx])


    return max(list(map(lambda x: max(x),copy_maze)))

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


for y in range(h):
    for x in range(w):
        if maze[y][x]=='.':
            maze[y][x]=math.inf
        elif maze[y][x] == '
            maze[y][x]=int(-1)

results = []

for y in range(h):
    for x in range(w):
        if maze[y][x]==math.inf:
            copy_maze = copy.deepcopy(maze)
            max_dist_result = max_dist(copy_maze,x,y,w,h)
            results.append(int(max_dist_result))
            

print(max(results))

Solution (Python):
H, W = map(int, input().split())

maze = []

for r in range(H):
  maze.append(list(input()))
maxVisit = 0
for row in maze:
  for road in row:
    if (road == "."):
      maxVisit += 1

def findMaxBFS(start):
  
  if (maze[start[0]][start[1]] == "
    return 0
  
  visitedCount = 1
  visitedPoints = []
  for r in range(H):
    visitedPoints.append([])
    for c in range(W):
      if (r == start[0]) and (c == start[1]):
        visitedPoints[r].append("Y")
      else:
        visitedPoints[r].append("N")
  points = [start]
  directions = [[0,1], [0,-1], [1,0], [-1,0]]
  steps = 0
  
  while (visitedCount < maxVisit):
    steps += 1
    nextPoints = []
    for p in points:
      for d in directions:
        nextP = [p[0]+d[0], p[1]+d[1]]
        
        if (0<=nextP[0] and nextP[0]<H) and (0<=nextP[1] and nextP[1]<W):
          road = maze[nextP[0]][nextP[1]]
          
          if (road == "."):
            
            if (visitedPoints[nextP[0]][nextP[1]] == "N"):
              nextPoints.append(nextP)
              visitedCount += 1
              visitedPoints[nextP[0]][nextP[1]] = "Y" 
    points = nextPoints
  
  
  return steps

max_steps = []
for r in range(H):
  for c in range(W):
    max_steps.append(findMaxBFS([r,c]))
print(max(max_steps))

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


def bfs(i, j):
    dq = deque()
    maze_c = copy.deepcopy(maze)
    maze_c[i][j] = 0
    dq.appendleft([i, j])
    res = 0
    while len(dq) > 0:
        ni, nj = dq.pop()
        if maze_c[ni][nj] == "
            continue
        for di, dj in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            if ni + di < 0 or nj + dj < 0 or ni + di >= H or nj + dj >= W:
                continue
            if maze_c[ni + di][nj + dj] == ".":
                maze_c[ni + di][nj + dj] = maze_c[ni][nj] + 1
                res = max(res, maze_c[ni + di][nj + dj])
                dq.appendleft([ni + di, nj + dj])
    return res

ans = 0
for i in range(H):
    for j in range(W):
        if maze[i][j] == ".":
            ans = max(ans, bfs(i, j))
print(ans)

Solution (Python):
H,W = list(map(int,input().split()))
N=H*W


wall=[]
for h in range(H):
    for w_idx,w in enumerate(list(input())):
        if w == '
            wall.append(W*h+w_idx+1)

path=[_ for _ in range(1,N+1) if _ not in wall]


ad = {}
for n in range(N):
    ad[n+1]=[]
    
for n in range(N):
    n=n+1
    if n not in wall:
        up = n-W
        if up > 0 and up not in wall:
            ad[n].append(up)
            
        down = n+W
        if down <= N and down not in wall:
            ad[n].append(down)
            
        left = n-1
        if n % W != 1 and left not in wall and left > 0:
            ad[n].append(left)
        
        right = n+1
        if n % W != 0 and right not in wall:
            ad[n].append(right)      

from collections import deque

def BFS(start):
    que = deque([start])
    visit = deque([])

    color = {}
    for n in range(N):
        color[n+1] = -1
    color[start] = 0

    depth = {}
    for n in range(N):
        depth[n+1] = -1

    depth[start] = 0
    while len(que) > 0:
        start = que[0]
        for v in ad[start]:
            if color[v] == -1:
                que.append(v)
                color[v] = 0
                depth[v] = depth[start]+1

        color[start] = 1
        visit.append(que.popleft())

    return depth[start]

ans=-1
for start in path:
    ans_=BFS(start)
    if ans < BFS(start):
        ans = ans_
    

    
print(ans)

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

h,w=map(int,input().split())
M=[list(input().strip()) for _ in range(h)]

def bfs(x,y):
    if M[x][y]=='
        return 0
    q=deque()
    q.append((x,y))
    count = [[-1]*w for _ in range(h)]
    count[x][y]=0

    while q:
        x,y=q.pop()
        for i,j in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
            if 0<=i<h and 0<=j<w and count[i][j]==-1 and M[i][j]=='.':
                count[i][j]=count[x][y]+1
                q.appendleft((i,j))

    return max([max(c) for c in count])
        
ans = 0
for i in range(h):
    for j in range(w):
        ans = max(ans,bfs(i,j))
print(ans)

Solution (Python):
from collections import deque
import itertools

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



def bfs(x, y):
    
    d = [[-1] * w for _ in range(h)]
    
    d[x][y] = 0
    q = deque([(x, y)])
    while q:
        tx, ty = q.popleft()
        
        for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            nx, ny = tx + dx, ty + dy
            
            if 0 <= nx < h and 0 <= ny < w and g[nx][ny] == '.' and d[nx][ny] < 0:
                d[nx][ny] = d[tx][ty] + 1
                q.append((nx, ny))
    
    return max(list(itertools.chain.from_iterable(d)))


max_count = 0
for x in range(h):
    for y in range(w):
        if g[x][y] == ".":
            max_count = max(max_count, bfs(x, y))

print(max_count)

Solution (Python):
from queue import Queue
def isSafe(row, col):
    return row >= 0 and col >= 0 and row<h and col<w and mat[row][col] != '


def bfs(row, col):
    visited = [[False]*w for _ in range(h)]
    que = Queue()
    dst = 0
    que.put([row, col, 0])
    visited[row][col] = True
    moves = [[-1, 0],[1, 0], [0, -1], [0, 1]]
    while not que.empty():
        root = que.get()
        row, col, dst = root
        for nrow, ncol in moves:
            row2 = row + nrow
            col2 = col + ncol 
            if isSafe(row2, col2) is True and visited[row2][col2] is False:
                visited[row2][col2] = True
                que.put([row2, col2, dst+1])
                 
    return dst 

h, w = map(int, input().split())
mat = [input() for _ in range(h)]
ans = 0
for row in range(h):
    for col in range(w):
        if mat[row][col] == '.':
            ans = max(ans, bfs(row, col))

print(ans)