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 bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

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


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


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


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


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


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


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


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


def mt(f):
    import time

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

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

    return wrap


def warshall_floyd(g, N):
    d = g
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]

    return d


@mt
def slv(H, W, S):
    ans = 0
    g = [[INF] *(H*W) for _ in range(H*W)]
    def idx(i, j):
        return i*W + j
    for i in range(H):
        for j in range(W):
            if S[i][j] != '.':
                continue
            if i > 0 and S[i-1][j] == '.':
                g[idx(i, j)][idx(i-1, j)] = 1

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

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

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

    d = warshall_floyd(g, W*H)
    ans = 0
    for i, r in enumerate(d):
        for j, v in enumerate(r):
            if v != INF and i != j:
                ans = max(ans, v)
    return ans


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


    
    
    
    print(slv(H, W, S))

if __name__ == '__main__':
    main()

Solution (Python):
import sys
import copy
input = sys.stdin.readline
from collections import deque
H, W = [int(x) for x in input().split()]
S = []
for _ in range(H):
    S.append(list(input().rstrip()))
can = []
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            can.append([i, j])
ans = []
for u in can:
    S_ = copy.deepcopy(S)
    D = {}
    queue = deque([u])
    def bfs(u, S):
        S_2 = S[:]
        D[tuple(u)] = 0
        while queue:
            v = queue.popleft()
            S_2[v[0]][v[1]] = "
            x, y = v
            next_ = [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]
            for r in next_:
                if 0 <= r[0] < H and 0 <= r[1] < W:
                    if S_2[r[0]][r[1]] == ".":
                        S_2[r[0]][r[1]] = "
                        D[tuple(r)] = D[tuple(v)] + 1
                        queue.append(r)
        return max(D.values())
    ans.append(bfs(u, S_))
print(max(ans))

Solution (Python):
H,W = map(int,input().split())
State = []
for i in range(H):
    State.append(input())
starts = [(i%H,i//H) for i in range(H*W)]
goals = [(i%H,i//H) for i in range(H*W)]
from collections import deque
def min_dist(start):
    visited = [[False for i in range(W)] for j in range(H)]
    dists = [[float('inf') for i in range(W)] for j in range(H)]
    dists[start[0]][start[1]]=0
    diffs = [(0,1),(1,0),(0,-1),(-1,0)]
    Q = deque([start])
    while Q:
        current_pos = Q.pop()
        for diff in diffs:
            next_pos = (current_pos[0]-diff[0],current_pos[1]-diff[1])
            if next_pos[0] < H and next_pos[0] >= 0 and next_pos[1] < W and next_pos[1] >= 0:
                if State[next_pos[0]][next_pos[1]] == '.':
                    dists[next_pos[0]][next_pos[1]] = min(dists[current_pos[0]][current_pos[1]]+1,dists[next_pos[0]][next_pos[1]])
                    if not visited[next_pos[0]][next_pos[1]]:
                        visited[next_pos[0]][next_pos[1]] = True
                        Q.appendleft(next_pos)
    return dists
max_dist = -100000
for start in starts:
    if State[start[0]][start[1]] == '.':
        dists = min_dist(start)
        local_max_dist = -1000000
        for i in range(W):
            for j in range(H):
                if dists[j][i] != float('inf'):
                    if local_max_dist < dists[j][i]:
                        local_max_dist = dists[j][i]
        if local_max_dist > max_dist:
            max_dist = local_max_dist
print(max_dist)

Solution (Python):
from collections import deque
r,c=map(int,input().split())
ko =[list(input()) for i in range(r)]
d=[(-1,0),(1,0),(0,-1),(0,1)]


ans = 0
for sy in range(r):
    for sx in range(c):
        if ko[sy][sx] == "." :
            
            dist = [[r*(2*c) for i in range(c)] for i in range(r)]
            H = deque()
            H.append((sy,sx))
            dist[sy][sx]=0


            while H:
                y,x=H.popleft()
                
                for i in d:
                    if 0<=y+i[0]< r and 0<=x+i[1]< c and ko[y+i[0]][x+i[1]]=="." and dist[y+i[0]][x+i[1]]>dist[y][x]+1:
                        dist[y+i[0]][x+i[1]] = dist[y][x]+1
                        H.append((y+i[0],x+i[1]))

            
            maxnow = 0
            for i in range(r):
                for j in range(c):
                    if dist[i][j] > maxnow and dist[i][j] != r*2*c:
                        maxnow = dist[i][j]
            if maxnow > ans :
                ans = maxnow

print(ans)

Solution (Python):
import copy

H,W=map(int,input().split())
s=[['
for i in range(H):
    s.append(['
s.append(['


c=copy.deepcopy(s)

L=[]
for i in range(H+2):
    for j in range(W+2):
        if c[i][j]!='
            L.append([i+1,j+1])



from collections import deque

def move(yxc):
    global Q
    y,x,cost=yxc[0],yxc[1],yxc[2]
    if c[y+1][x]=='.':
        c[y+1][x]=cost+1
        Q.append([y+1,x,cost+1])
    if c[y-1][x]=='.':
        c[y-1][x]=cost+1
        Q.append([y-1,x,cost+1])
    if c[y][x+1]=='.':
        c[y][x+1]=cost+1
        Q.append([y,x+1,cost+1])
    if c[y][x-1]=='.':
        c[y][x-1]=cost+1
        Q.append([y,x-1,cost+1])

ans=0
for i in range(len(L)):
    sx,sy=L[i][1],L[i][0]
    c=copy.deepcopy(s)
    Q=deque([[sy-1,sx-1,0]])
    c[sy-1][sx-1]='S'
    u=0
    while len(Q)>0:
        q=Q.popleft()
        move(q)
        u=max(q[2],u)



    ans=max(ans,u)

print(ans)

Solution (Python):
from collections import deque

h,w=map(int,input().split())

maze=[list("
INF=10800 
visited=[[-INF]*(w+2) for i in range(h+2)]

ss=[]

for i in range(1,h+1):
  for j in range(1,w+1):
    if maze[i][j]==".":
      ss.append((i,j))



def bfs(maze,visited,sy,sx):
  queue=deque([[sy,sx]])
  visited[sy][sx]=0
  while queue:
    [y,x]=queue.popleft()
    for i,j in ((-1,0),(1,0),(0,1),(0,-1)):
      y_new,x_new=y+i,x+j
      if maze[y_new][x_new]=="." and visited[y_new][x_new]==-INF:
        visited[y_new][x_new]=visited[y][x]+1
        queue.append([y_new,x_new])

        
        
ans=0
for i,j in ss:
  visited=[[-INF]*(w+2) for i in range(h+2)]
  bfs(maze,visited,i,j)
  for i in range(1,h+1):
    for j in range(1,w+1):
      ans=max(ans,visited[i][j])

    
    
print(ans)

Solution (Python):
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


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


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YN = ['No', 'Yes']
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']


show_flg = True
show_flg = False


def main():
    BLACK = '
    WHITE = '.'
    H, W = MI()
    graph = [[0 for i in range(W)] for i in range(H)]
    ans = 0
    options = [(-1, 0), (0, 1), (1, 0), (0, -1)]

    for i in range(H):
        S = input()

        for j in range(W):
            graph[i][j] = S[j]

    if H == 1 and W == 1:
        print(0)
        return

    if (H == 2 and W == 1) or (H == 1 and W == 2):
        print(1)
        return

    
    
    

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

            visited = [[False for i in range(W)] for i in range(H)]
            q = deque()
            q.append(((h, w), 0))
            arr = []
            while len(q) != 0:
                p, c = q.popleft()
                

                for d in options:
                    i = p[0] + d[0]
                    j = p[1] + d[1]

                    if i >= 0 and i < H and j >= 0 and j < W and not visited[i][j] and graph[i][j] == WHITE:
                        visited[i][j] = True
                        q.append(((i, j), c+1))
                        
                    else:
                        arr.append(c)
            
            ans = max(ans, max(arr))

    print(ans)



if __name__ == '__main__':
    main()

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


H, W = map(int, input().split())
S = []
for i in range(H):
    S.append(input().strip())


def f(sx, sy):
    q = collections.deque()
    q.append((sx, sy))
    dist = [[float("inf") for w in range(W)] for h in range(H)]
    dist[sx][sy] = 0
    dx = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while q:
        h, w = q.popleft()
        d = dist[h][w]
        for x, y in dx:
            h2 = h + y
            w2 = w + x
            if h2 >= 0 and h2 < H and w2 >= 0 and w2 < W:
                if S[h2][w2] == "." and dist[h2][w2] == float("inf"):
                    dist[h2][w2] = d+1
                    q.append((h2, w2))
    ma = 0
    for d in dist:
        for i in d:
            if i != float("inf"):
                ma = max(ma, i)
    return ma


def main():
    ans = 0
    for y in range(H):
        for x in range(W):
            if S[y][x] == ".":
                ans = max(ans, (f(y, x)))
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
from collections import deque

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

f_inf = float('inf')
ans = []
for h in range(H):
    for w in range(W):
        if grid[h][w] == "
            continue
        else:
            maze = [[f_inf] * W for _ in range(H)]
            sh, sw = h, w
            maze[sh][sw] = 0
            que = deque([[sh, sw]])
            while que:
                h, w = que.popleft()
                for dh, dw in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    next_h, next_w = h + dh, w + dw
                    if next_h < 0 or next_h >= H or next_w < 0 or next_w >= W:
                        continue
                    elif grid[next_h][next_w] == "
                        continue
                    elif grid[next_h][next_w] == ".":
                        if maze[next_h][next_w] > maze[h][w] + 1:
                            maze[next_h][next_w] = maze[h][w] + 1
                            que.append([next_h, next_w])
                            ans.append(maze[next_h][next_w])

print(max(ans))

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

for i in range(H):
    S[i]=input()
    
def warshall_floyd(d):
    
    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

n=H*W
inf=10**9

d = [[inf]*n for _ in range(n)] 

for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            if j+1<W:
                if S[i][j+1]==".":
                    d[i*W+j][i*W+j+1]=1
                    d[i*W+j+1][i*W+j]=1
            if i+1<H:
                if S[i+1][j]==".":
                    d[i*W+j][(i+1)*W+j]=1
                    d[(i+1)*W+j][i*W+j]=1
    
        
for i in range(n):
    d[i][i] = 0 
ans=0

warshall_floyd(d)

for i in range(n):
    for j in range(n):
        if d[i][j]>=ans and d[i][j]<=inf-10:
            ans=d[i][j]

print(ans)

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


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


def bfs(sx, sy):
    d = [[-1]*w for i in range(h)]
    que = deque([])
    que.append((sx, sy))
    d[sy][sx] = 0

    while que:
        p = que.popleft()

        for i in range(4):
            nx = p[0]+dx[i]
            ny = p[1]+dy[i]

            if (0 <= nx < w) and (0 <= ny < h) and (grid[ny][nx] != "
                que.append((nx, ny))
                d[ny][nx] = d[p[1]][p[0]] + 1

    return max(sum(d, []))


ans = 0
for sy in range(h):
    for sx in range(w):
        if grid[sy][sx] != "
            temp = bfs(sx, sy)
            if ans < temp:
                ans = temp
print(ans)

Solution (Python):
H, W = map(int, input().split())
l = [input() for i in range(H)]

from collections import deque
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]

ans = 0
for i in range(H):
    for j in range(W):
        if l[i][j] == '
            continue
        ll = [[0] * W for _ in range(H)]
        q = deque([(i, j)])
        while q:
            y, x = q.popleft()
            for dy, dx in d:
                if 0 <= y+dy < H and 0 <= x+dx < W and l[y+dy][x+dx] == '.' and (y+dy, x+dx) != (i, j):
                    n = ll[y][x] + 1
                    if ll[y+dy][x+dx] == 0 or ll[y+dy][x+dx] > n:
                        ll[y+dy][x+dx] = n
                        q.append((y+dy, x+dx))
                        if ans < n:
                            ans = n

print(ans)

Solution (Python):
import copy

def check(ss, l):
    ns = []
    for s in ss:
        for i in range(4):
            if nmaze[s[0]+move[i][0]][s[1]+move[i][1]] == '.':
                nmaze[s[0]+move[i][0]][s[1]+move[i][1]] = l
                ns.append([s[0]+move[i][0], s[1]+move[i][1]])
    if len(ns) > 0:
        return check(ns, l+1)
    else:
        return l

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

move = [[-1, 0], [1, 0], [0, -1], [0, 1]]
ans = 0
for i in range(1, H+1):
    for j in range(1, W+1):
        if maze[i][j] == '.':
            nmaze = copy.deepcopy(maze)
            nmaze[i][j] = 0
            l = check([[i, j]], 0)
            if ans < l:
                ans = l
print(ans)

Solution (Python):
from collections import deque
H,W = map(int,input().split())
S = [["
lis = [[0]*(W+2) for _ in range(H+2)]
q = deque()
ans = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        lis = [[0]*(W+2) for _ in range(H+2)]
        q = deque()
        if S[i][j] == ".":
            q.append([i,j,0])
        else:
            continue
        se = set()
        while q:
            n = q.popleft()
            if lis[n[0]][n[1]]:
                continue
            else:
                lis[n[0]][n[1]] = 1
            
            ans = max(ans,n[2])
            if S[n[0]][n[1]-1] == ".":
                q.append([n[0],n[1]-1,n[2]+1])
            if S[n[0]][n[1]+1] == ".":
                q.append([n[0],n[1]+1,n[2]+1])
            if S[n[0]-1][n[1]] == ".":
                q.append([n[0]-1,n[1],n[2]+1])
            if S[n[0]+1][n[1]] == ".":
                q.append([n[0]+1,n[1],n[2]+1])
print(ans)

Solution (Python):

import sys
from collections import deque

INF = float("inf")

XX = [1, -1, 0, 0]
YY = [0, 0, 1, -1]


def main():

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

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

    ans = 0
    for h in range(H):
        for w in range(W):
            
            if S[h][w] == "
                continue
            
            dist = [[INF]*W for _ in range(H)]

            dist[h][w] = 0
            q = deque([(h, w, 0)])
            while len(q) > 0:
                y, x, p = q.popleft()
                
                for dx, dy in zip(XX, YY):
                    if y + dy < 0 or y + dy >= H:
                        continue
                    if x + dx < 0 or x + dx >= W:
                        continue
                    if S[y+dy][x+dx] == "
                        continue
                    if p + 1 < dist[y+dy][x+dx]:
                        dist[y+dy][x+dx] = p+1
                        q.append((y+dy, x+dx, p+1))

            
            toku = -1
            I, J = -1, -1
            for i in range(H):
                for j in range(W):
                    if dist[i][j] != INF:
                        if dist[i][j] >= toku:
                            I, J = i, j
                        toku = max(dist[i][j], toku)
            if toku >= ans:
                ans = max(toku, ans)
                

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):



from queue import Queue

ans = 0
h,w = map(int, input().split())
maps = [input() for _ in range(h)]
for i in range(h):
    for j in range(w):
        if maps[i][j] == '.':
            visited = [[-1]*w for _ in range(h)]
            q = Queue()
            q.put([i,j])
            visited[i][j] = 0
            while not q.empty():
                y,x = q.get()
                for k,l in [[1,0],[-1,0],[0,1],[0,-1]]:
                    if 0 <= y+k < h and 0<= x+l < w:
                        new_y,new_x = y+k,x+l
                    else: continue
                    if visited[new_y][new_x]== -1 and maps[new_y][new_x]==".":
                        visited[new_y][new_x]=visited[y][x]+1
                        q.put([new_y,new_x])
   
          
        
            for ii in range(h):
                for jj in range(w):
                    ans = max(ans,visited[ii][jj])


print(ans)

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

mat=[]
mat.append([False]*(W+2))
for i in range(H):
  line=input()
  row=[False]
  for j in line:
    if j=="
      row.append(False)
    else:
      row.append(True)
  row.append(False)
  mat.append(row)
mat.append([False]*(W+2))


max_depth=0
for i in range(1,H+1):
  for j in range(1,W+1):
    if not mat[i][j]:
      continue
    
    bfs_mat=[]
    for ii in range(H+1):
      bfs_mat.append([99]*(W+1))
      
    
    max_dist=0
    bfs_queue=[(i,j,0)]
    while(len(bfs_queue)>0):
      new_queue=set()
      for (ii,jj,dist) in bfs_queue:
        
        bfs_mat[ii][jj]=dist
        max_dist=dist
        if mat[ii-1][jj] and bfs_mat[ii-1][jj]==99:
          new_queue.add((ii-1,jj,dist+1))
        if mat[ii+1][jj] and bfs_mat[ii+1][jj]==99:
          new_queue.add((ii+1,jj,dist+1))
        if mat[ii][jj-1] and bfs_mat[ii][jj-1]==99:
          new_queue.add((ii,jj-1,dist+1))
        if mat[ii][jj+1] and bfs_mat[ii][jj+1]==99:
          new_queue.add((ii,jj+1,dist+1))

      bfs_queue=new_queue
      

    
    if max_dist>max_depth:
      max_pos=(i,j)
      max_depth=max_dist


print(max_depth)

Solution (Python):
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def main():
    inf=1000
    h,w=MI()
    ss=[[c=="
    mx=0
    for si in range(h):
        for sj in range(w):
            if ss[si][sj]:continue
            bfs={}
            bfs[si,sj]=0
            vis=[[False]*w for _ in range(h)]
            vis[si][sj]=True
            while bfs:
                nxt={}
                for (i,j),d in bfs.items():
                    if d>mx:mx=d
                    for ni, nj in [(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)]:
                        if ni<0 or nj<0 or ni>=h or nj>=w:continue
                        if ss[ni][nj]:continue
                        if vis[ni][nj]:continue
                        vis[ni][nj]=True
                        nxt[ni,nj]=d+1
                bfs=nxt
    print(mx)

main()

Solution (Python):
import math
import sys
sys.setrecursionlimit(10**9)
H,W = map(int,input().split())

S = []
for h in range(H):
    s = input()
    t = []
    for ss in s:
        if ss==".":
            t.append(True)
        else:
            t.append(False)
    S.append(t)



V = H*W

d = [[float("inf") for i in range(V)] for j in range(V)]

for h in range(H):
    for w in range(W):
        i = h*W+w
        if S[h][w]:
            if 0<=h<=H-2 and S[h+1][w]:
                j = (h+1)*W+w
                d[i][j], d[j][i] = 1,1
            if 1<=h<=H-1 and S[h-1][w]:
                j = (h-1)*W+w
                d[i][j], d[j][i] = 1,1
            if 0<=w<=W-2 and S[h][w+1]:
                j = h*W+(w+1)
                d[i][j], d[j][i] = 1,1
            if 1<=w<=W-1 and S[h][w-1]:
                j = h*W+(w-1)
                d[i][j], d[j][i] = 1,1



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

    return d 


dd = warshall_floyd(d, V)


mx = 0
for i,ddd in enumerate(dd):
    for j,n in enumerate(ddd):
        if math.isfinite(n) and i!=j:
            mx = max(mx, n)

print(mx)

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

n_list = []
v_table = {}
for y in range(H):
	for x in range(W):
		n = (x, y)
		n_list.append(n)
		v_table[n] = []

prev = None
ns = None
for y in range(H):
	cur = input()
	for x in range(W):
		if cur[x] == ".":
			nc = (x, y)
			ns = nc
			if y > 0 and prev[x] == ".":
				np = (x, (y - 1))
				v_table[np].append(nc)
				v_table[nc].append(np)
			if x > 0 and cur[x - 1] == ".":
				np = (x - 1, y)
				v_table[np].append(nc)
				v_table[nc].append(np)
	prev = cur

def calc_dists(x, n_list, edges):
	dists = { x: 0 }
	queue = [ x ]
	
	while queue:
		cur = queue.pop(0)
		dist = dists[cur] + 1
		for v2 in edges[cur]:
			if (not v2 in dists) or (dists[v2] > dist):
				dists[v2] = dist
				queue.append(v2)
	
	return dists

max_dist = 0
for n in n_list:
	dists = calc_dists(n, n_list, v_table)
	for n2, dist in dists.items():
		if dist > max_dist:
			max_dist = dist
print(max_dist)

Solution (Python):
h,w=map(int,input().split())
s=[list(input())for i in range(h)]
e=0
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            p=[i,j]
            q=[p]
            t=[[1]*w for j in range(h)]
            t[p[0]][p[1]]=0
            g=0
            while q:
                c=[]
                for i,j in q:
                    a=[1,-1,0,0]
                    b=[0,0,1,-1]
                    for d in range(4):
                        if 0<=i+a[d]<h and 0<=j+b[d]<w:
                            if s[i+a[d]][j+b[d]]==".":
                                if t[i+a[d]][j+b[d]]:
                                    t[i+a[d]][j+b[d]]=0
                                    c.append([i+a[d],j+b[d]])
                if len(c)==0:
                    break
                else:
                    g+=1
                    q=c[::]
            e=max(e,g)
print(e)

Solution (Python):
H,W = map(int,input().split())
grid = [input() for i in range(H)]

INF = 10 ** 18

ans = 0
for h in range(H):
    for w in range(W):
        if grid[h][w] == '
            continue
        dist = [[INF] * W for _ in range(H)]
        dist[h][w] = 0
        q = [(h,w)]
        d = 1
        while q:
            qq = []
            for y,x in q:
                for dy,dx in [(-1,0),(1,0),(0,-1),(0,1)]:
                    yy,xx = y+dy, x+dx
                    if not (0 <= yy < H and 0 <= xx < W):
                        continue
                    if grid[yy][xx] == '
                        continue
                    if dist[yy][xx] != INF:
                        continue
                    dist[yy][xx] = d
                    qq.append((yy,xx))
            q = qq
            d += 1
        for i in range(H):
            for j in range(W):
                if dist[i][j] != INF:
                    ans = max(ans,dist[i][j])

print(ans)

Solution (Python):
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    h, w = map(int, input().split())

    s = []
    for _ in range(h):
        s.append(list(input())[:-1])

    ans = 0

    from collections import deque
    import copy

    reach_queue = deque()
    next_queue = deque()

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

    for i in range(w):
        for j in range(h):
            if s[j][i] == '.':
                next_queue.append((i, j))
                not_visited = [[True]*w for _ in range(h)]
                not_visited[j][i] = False
                cnt = -1
                while True:
                    if len(next_queue) == 0:
                        ans = max([ans, cnt])
                        break
                    reach_queue = copy.deepcopy(next_queue)
                    next_queue = deque()
                    while True:
                        if len(reach_queue) == 0:
                            cnt += 1
                            break
                        new_i, new_j = reach_queue.popleft()
                        if new_i != 0:
                            if s[new_j][new_i-1] == '.' and not_visited[new_j][new_i-1]:
                                not_visited[new_j][new_i-1] = False
                                next_queue.append((new_i-1, new_j))
                        if new_j != 0:
                            if s[new_j-1][new_i] == '.' and not_visited[new_j-1][new_i]:
                                not_visited[new_j-1][new_i] = False
                                next_queue.append((new_i, new_j-1))
                        if new_i != w-1:
                            if s[new_j][new_i+1] == '.' and not_visited[new_j][new_i+1]:
                                not_visited[new_j][new_i+1] = False
                                next_queue.append((new_i+1, new_j))
                        if new_j != h-1:
                            if s[new_j+1][new_i] == '.' and not_visited[new_j+1][new_i]:
                                not_visited[new_j+1][new_i] = False
                                next_queue.append((new_i, new_j+1))

    print(ans)

Solution (Python):

import queue

row, col = map(int, input().split(' '))
maze = [list(input()) for _ in range(row)]

                
def BPS(si, sj):
    done = [[0 for _ in range(col)] for _ in range(row)]
    q = queue.Queue()
    q.put((si, sj, 0))
    around = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    maxv = 0
    while not q.empty():
        i, j, cnt = q.get()
        done[i][j] = 1
        for ar in around:
            di, dj = ar[0], ar[1]
            i_n, j_n = i + di, j + dj
            if (i_n >= 0 and i_n < row and j_n >= 0 and j_n < col) == False:
                continue
            if maze[i_n][j_n] == '
                continue
            if done[i_n][j_n] == 1:
                continue
            if done[i_n][j_n] == 2:
                continue
            maxv = max(maxv, cnt + 1)
            q.put((i_n, j_n, cnt + 1))
            done[i_n][j_n] = 2
        
    return maxv
            
            
def main():        
    maxv = 0
    for i in range(row):
        for j in range(col):
            if maze[i][j] == '
                continue
            maxv = max(maxv, BPS(i,j))
    print(maxv)
                    
                
                    
    
main()

Solution (Python):
from collections import deque

def bfs(si, sj):
    q = deque()
    q.append([si, sj, 0])
    used = set()
    used.add((si,sj))
    ans = MAX_VALUE
    while len(q) > 0:
        prvi, prvj, d = q.popleft()
        for i, j in [[prvi-1, prvj], [prvi+1, prvj], [prvi, prvj-1], [prvi, prvj+1]]:
            if (i,j) in used:
                continue
            if grid[j][i] == '
                ans = min(ans, d)
                continue
            else:
                q.append([i,j,d+1])
                used.add((i,j))
    return d

H, W = map(int, input().split())
MAX_VALUE = (H+2) * (W+2) + 1
grid = ['

ans = 1
for j in range(1, H + 1):
    for i in range(1, W + 1):
        if grid[j][i] == '
            continue
        res = bfs(i, j)
        if res != MAX_VALUE:
            ans = max(ans, res)
print(ans)

Solution (Python):
H, W = map(int, input().split())
s = "
for _ in range(H):
    s+="
s += "



ff = (W+2)*(H+2)
from scipy.sparse.csgraph import csgraph_from_dense,floyd_warshall
dp = [[-1]*ff for _ in range(ff)]
for i in range(1, H+1):
    for j in range(1, W+1):
        u = j+(W+2)*i
        v = j+(W+2)*(i-1)
        if s[u] == "." and s[u-1] == ".":

            dp[u][u-1] = 1
        if s[u] == "." and s[v] == ".":

            dp[u][v] = 1

G = csgraph_from_dense(dp,  null_value=-1)
Q = floyd_warshall(G, directed=False)
r = -1
for q in Q:
    for x in q:
        if x < 10**9:
            r = max(r, int(x))
print(r)

Solution (Python):
from collections import deque
import copy

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

ans=0

for hh in range(h):
 for ww in range(w):
  dist=[[-1]*(w+1) for i in range(h+1)]
  c=copy.deepcopy(ss)
  xx=c[hh][ww]
  if xx=='
   continue
  dist[hh][ww]=0
  dq=deque()
  dq.append((hh,ww))
  c[hh][ww]='
  while dq:
   y,x=dq.popleft()
   for dx,dy in [[1,0],[-1,0],[0,1],[0,-1]]:
    nx=x+dx
    ny=y+dy
    if 0<=nx<w and 0<=ny<h and c[ny][nx]!='
     dq.append((ny,nx))
     c[ny][nx]='
     dist[ny][nx]=dist[y][x]+1
  for i in dist:
   ans=max(ans,max(i))
print(ans)