Problem:
 Score : 400 points    Problem Statement Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.  The square at the i -th row from the top and the j -th column is a "wall" square if S_{ij} is # , and a "road" square if S_{ij} is . .  From a road square, you can move to a horizontally or vertically adjacent road square.  You cannot move out of the maze, move to a wall square, or move diagonally.  Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.  Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.  In this situation, find the maximum possible number of moves Aoki has to make.      Constraints  1 \leq H,W \leq 20  S_{ij} is . or # .  S contains at least two occurrences of . .  Any road square can be reached from any road square in zero or more moves.         Input Input is given from Standard Input in the following format:  H  W  S_{11} ... S_{1W}  :  S_{H1} ... S_{HW}       Output Print the maximum possible number of moves Aoki has to make.        Sample Input 1 3 3
...
...
...      Sample Output 1 4  If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.       Sample Input 2 3 5
...#.
.#.#.
.#...      Sample Output 2 10  If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

h,w = LI()
maze = [list(input()) for _ in range(h)]

dx,dy = [0,1,0,-1],[1,0,-1,0]
ans = 0
for i in range(h):
    for j in range(w):
        if maze[i][j] == '
            continue
        que = deque()
        que.append((j,i))
        f = [[True]*w for _ in range(h)]
        d = [[0]*w for _ in range(h)]
        f[i][j] = False
        while que:
            x,y = que.popleft()
            for k in range(4):
                nx,ny = x + dx[k], y + dy[k]
                if 0 <= nx < w and 0 <= ny < h:
                    if f[ny][nx] and maze[ny][nx] == '.':
                        que.append((nx,ny))
                        d[ny][nx] = d[y][x] + 1
                        f[ny][nx] = False
        for k in range(h):
            ans = max(ans,max(d[k]))
print(ans)

Solution (Python):
from collections import deque

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

def solve(sh, sw):
    visited = [[-1]*w for i in range(h)]
    visited[sh][sw] = 0
    q = deque([(sh, sw)])
    max_ = 0
    while q:
        i, j = q.popleft()
        for ni, nj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
            if not(0 <= ni < h and 0 <= nj < w):
                continue
            if s[ni][nj] == "
                continue
            if visited[ni][nj] >= 0:
                continue
            visited[ni][nj] = visited[i][j] + 1
            max_ = max(max_, visited[ni][nj])
            q.append((ni, nj))
    return max_

ans = 0
for sh in range(h):
    for sw in range(w):
        if s[sh][sw] == "
            continue
        ans = max(ans, solve(sh, sw))
print(ans)

Solution (Python):
H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
from collections import deque
dire = [(0, -1), (-1, 0), (1, 0), (0, 1)]
def dfs(sx, sy):
    dist = [[-1]*W for _ in range(H)]
    dist[sx][sy] = 0
    res = 0
    que = deque([(sx, sy)])
    while que:
        x, y = que.popleft()
        d = dist[x][y]
        for dx, dy in dire:
            nx = x+dx
            ny = y+dy
            if 0<=nx<H and 0<= ny< W and S[nx][ny] == '.' and dist[nx][ny] == -1:
                dist[nx][ny] = d+1
                que.append((nx, ny))
                res = max(res, d+1)
    return res

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

Solution (Python):
from collections import deque
h,w = map(int,input().split())
maze = [list(input()) for i in range(h)]
ans = 0
for i in range(h):
  for j in range(w):
    if maze[i][j] == ".":
      visited = [[0 for k in range(w)] for l in range(h)]
      visited[i][j] = 1
      que = deque([])
      que.append((i,j,0))
      while que:
        (x,y,cnt) = que.popleft()
        for (nx,ny) in (x+1,y),(x-1,y),(x,y+1),(x,y-1):
          if 0<=nx<h and 0<=ny<w:
            if maze[nx][ny] == "." and visited[nx][ny] == 0:
              que.append((nx,ny,cnt+1))
              visited[nx][ny] = 1
      ans = max(ans,cnt)
print(ans)

Solution (Python):
h,w=map(int,input().split())
b=[[1]*(w+2)]
for i in range(h):
  bb=[1]
  s=input()
  for j in range(w):
    if s[j]=="
    else:bb.append(0)
  bb.append(1)
  b.append(bb)
b.append([1]*(w+2))

ans=0
d=[[-1,0],[1,0],[0,-1],[0,1]]
for si in range(1,h+1):
  for sj in range(1,w+1):
    if b[si][sj]:continue
    visited={(si,sj)}
    Q=[(si,sj)]
    count=-1
    while Q:
      P=[]
      for i,j in Q:
        for di,dj in d:
          if b[i+di][j+dj]:continue
          if (i+di,j+dj)in visited:continue
          visited.add((i+di,j+dj))
          P.append((i+di,j+dj))
      Q=P
      count+=1
    ans=max(ans,count)
print(ans)

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

S=[]

for i in range(H):
    S.append(input())

e_list = [[] for i in range(H*W)]

def z(i,j):
    return i*W + j

for i in range(H):
    for j in range(W):
        if i!=H-1:
            if S[i][j]=="." and S[i+1][j]==".":
                e_list[z(i,j)].append(z(i+1,j))
                e_list[z(i+1,j)].append(z(i,j))
        if j!=W-1:
            if S[i][j]=="." and S[i][j+1]==".":
                e_list[z(i,j)].append(z(i,j+1))
                e_list[z(i,j+1)].append(z(i,j))

vi = 0 
from collections import deque
N=H*W
def BFS(vi):
    Q = deque([vi])
    checked_list = [False for i in range(N)]
    checked_list[vi]=True
    min_path_list = [10**27 for i in range(N)] 
    min_path_list[vi] = 0
    while len(Q)>0:
        v = Q.pop()
        for v1 in e_list[v]:
            if not checked_list[v1]:
                checked_list[v1]=True
                Q.appendleft(v1)
                min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) 
    max_d = 0
    for i in range(N):
        if min_path_list[i]<10**27:
            max_d = max(max_d,min_path_list[i])
    return max_d
ans = 0
for i in range(N):
    ans = max(BFS(i),ans)

print(ans)

Solution (Python):
from collections import deque


def dfs(field, s):
    MOVE = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    q = deque([(0, s)])
    dist = [[-1] * w for _ in range(h)]

    d, i, j = -1, -1, -1
    while q:
        d, (i, j) = q.popleft()
        if dist[i][j] != -1:
            continue
        dist[i][j] = d
        for di, dj in MOVE:
            ni, nj = i + di, j + dj
            if not 0 <= ni < h or not 0 <= nj < w:
                continue
            if field[ni][nj] == '
                continue
            if dist[ni][nj] != -1:
                continue
            q.append((d + 1, (ni, nj)))
    return d, i, j


h, w = map(int, input().split())
field = [input() for _ in range(h)]
ans = 0
for i in range(h):
    for j in range(w):
        if field[i][j] == '.':
            d, i, j = dfs(field, (i, j))
            ans = max(ans, d)
print(ans)

Solution (Python):
h,w=map(int,input().split())
b=[[1]*(w+2)]
for i in range(h):
  bb=[1]
  s=input()
  for j in range(w):
    if s[j]=="
    else:bb.append(0)
  bb.append(1)
  b.append(bb)
b.append([1]*(w+2))

ans=0
d=[[-1,0],[1,0],[0,-1],[0,1]]
for si in range(1,h+1):
  for sj in range(1,w+1):
    if b[si][sj]:continue
    visited={(si,sj)}
    Q=[(si,sj)]
    count=-1
    while Q:
      P=[]
      for i,j in Q:
        for di,dj in d:
          if b[i+di][j+dj]:continue
          if (i+di,j+dj)in visited:continue
          visited.add((i+di,j+dj))
          P.append((i+di,j+dj))
      Q=P
      count+=1
    ans=max(ans,count)
print(ans)

Solution (Python):
h, w = map(int, input().split())
n = h*w
INF = 1<<30
field = []
for i in range(h):
    field.append(input())

dist = [[INF] * n for _ in range(n)]

for i in range(h):
    for j in range(w):
        if field[i][j] == "
        if j + 1 < w and field[i][j+1] != "
            dist[i * w + j][i * w + j + 1] = 1
            dist[i * w + j + 1][i * w + j] = 1
        if i + 1 < h and field[i+1][j] != "
            dist[i * w + j][(i+1) * w + j] = 1
            dist[(i+1) * w + j][i * w + j] = 1

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

ans = 0
            
for i in range(n):
    for j in range(n):
        if(i == j):continue
        if(dist[i][j] == INF):continue
        ans = max(ans, dist[i][j])
        

print(ans)

Solution (Python):
import sys
from collections import deque

def solve():
    input = sys.stdin.readline
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]
    search = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    maxmove = 0
    for h in range(H):
        for w in range(W):
            if S[h][w] == ".":
                dist = [[-1 for _ in range(W)] for i in range(H)]
                q = deque()
                for di, dj in search:
                    if 0 <= h + di < H and 0 <= w + dj < W:
                        if S[h+di][w+dj] == ".": q.append((1, h + di, w + dj))
                dist[h][w] = 0
                move = 0
                while q:
                    nd, nh, nw = q.popleft()
                    if dist[nh][nw] == -1:
                        dist[nh][nw] = nd
                        move = max(move, nd)
                        for di, dj in search:
                            if 0 <= nh + di < H and 0 <= nw + dj < W:
                                if S[nh+di][nw+dj] == "." and dist[nh+di][nw+dj] == -1:
                                    q.append((nd + 1, nh+di, nw+dj))
                maxmove = max(maxmove, move)
    print(maxmove)


    return 0

if __name__ == "__main__":
    solve()

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

inf = 10**9+7
direc = [(0, 1), (1, 0), (-1, 0), (0, -1)]
def bfs(h, w):
    Q = deque([(h, w)])
    used = set([(h, w)])
    dist = [[inf]*(W+2) for _ in range(H+2)] 
    dist[h][w] = 0
    while Q:
        nx, ny = Q.pop()
        for dx, dy in direc:
            if G[nx+dx][ny+dy]:
                continue
            if (nx+dx, ny+dy) in used:
                continue
            used.add((nx+dx, ny+dy))
            dist[nx+dx][ny+dy] = min(dist[nx+dx][ny+dy], 1+dist[nx][ny])
            Q.appendleft((nx+dx, ny+dy))
    res = 0
    for i in range(H+2):
        for j in range(W+2):
            if dist[i][j] < inf:
                res = max(res, dist[i][j])
    return res
H, W = map(int, readline().split())
X = (H+2)*(W+2)
G = [[1]*(W+2)] + [[1] + [1 if s == '
ans = 0
for h in range(1, H+1):
    for w in range(1, W+1):
        if not G[h][w]:
            ans = max(ans, bfs(h, w))
print(ans)

Solution (Python):
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

H,W = inpl()
inMAP = [['

ans = -1
for sx in range(1,W+1):
    for sy in range(1,H+1):
        if inMAP[sy][sx] == "
            continue

        MAP = [m[:] for m in inMAP]

        q = queue.Queue()
        q.put([sx,sy,0])
        while not q.empty():
            x,y,n = q.get()
            if MAP[y][x] == '.':
                MAP[y][x] = n
                q.put([x-1,y,n+1])
                q.put([x+1,y,n+1])
                q.put([x,y-1,n+1])
                q.put([x,y+1,n+1])


        for x in range(1,W+1):
            for y in range(1,H+1):
                if MAP[y][x] != "
                    ans = max(ans,MAP[y][x])


print(ans)

Solution (Python):
import heapq
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]


class Graph:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.edges = [[] for _ in range(n_nodes)]

    def add_edge(self, s, t, d=None, undirected=False):
        if d is not None:
            self.edges[s].append((t, d))
        else:
            self.edges[s].append(t)
        if undirected:
            self.add_edge(t, s, d)

    def add_edges(self, edges, undirected=False):
        for edge in edges:
            self.add_edge(*edge, undirected=undirected)


class Dijkstra:
    def __init__(self, graph):
        self.graph = graph

    def compute(self, s, t):
        distances = [float('inf') for _ in range(self.graph.n_nodes)]
        visited = [False for _ in range(self.graph.n_nodes)]
        prev_nodes = [None for _ in range(self.graph.n_nodes)]
        distances[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        while q:
            dist_x, x = heapq.heappop(q)
            if x == t:
                return distances, prev_nodes

            if visited[x]:
                continue
            visited[x] = True

            for y, d_xy in self.graph.edges[x]:
                if visited[y]:
                    continue
                dist_y = dist_x + d_xy
                if dist_y < distances[y]:
                    distances[y] = dist_y
                    prev_nodes[y] = x
                    heapq.heappush(q, (dist_y, y))
        return distances, prev_nodes

    def compute_all(self, s):
        distances = [float('inf') for _ in range(self.graph.n_nodes)]
        visited = [False for _ in range(self.graph.n_nodes)]
        prev_nodes = [None for _ in range(self.graph.n_nodes)]
        distances[s] = 0
        q = []
        for t in range(self.graph.n_nodes):
            heapq.heappush(q, (distances[t], t))
        while q:
            dist_x, x = heapq.heappop(q)
            if visited[x]:
                continue
            visited[x] = True

            for y, d_xy in self.graph.edges[x]:
                if visited[y]:
                    continue
                dist_y = dist_x + d_xy
                if dist_y < distances[y]:
                    distances[y] = dist_y
                    prev_nodes[y] = x
                    heapq.heappush(q, (dist_y, y))
        return distances, prev_nodes


h, w = ril()
ls = rss(h)
graph = Graph(h * w)
for i in range(h):
    for j in range(w):
        if ls[i][j] == '.':
            for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                ni = i + di
                nj = j + dj
                if 0 <= ni < h and 0 <= nj < w and ls[ni][nj] == '.':
                    graph.add_edge(i * w + j, ni * w + nj, 1, True)
dijkstra = Dijkstra(graph)
res = 0
for i in range(h):
    for j in range(w):
        if ls[i][j] == '.':
            distances, _ = dijkstra.compute_all(i * w + j)
            res = max(res, max(d for d in distances if d < float('inf')))
print(res)

Solution (Python):
from collections import deque
dxdy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
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] == '
            continue
        d = [[-1] * w for _ in range(h)]
        q = deque([(i, j)])
        d[i][j] = 0
        while q:
            y, x = q.popleft()
            for dx, dy in dxdy:
                if 0 <= x + dx < w and 0 <= y + dy < h and s[y + dy][x + dx] == '.' and d[y + dy][x + dx] == -1:
                    q.append((y + dy, x + dx))
                    d[y + dy][x + dx] = d[y][x] + 1
        for row in d:
            ans = max(ans, max(row))
print(ans)

Solution (Python):
from heapq import heappop,heappush
H,W = map(int,input().split())
S = [list(input()) for i in range(H)]
ans = 0
for h in range(H):
    for w in range(W):
        if S[h][w]==".":
            D = [[False]*W for i in range(H)]
            Q = [(0,(h,w))]
            while Q:
                q = heappop(Q)
                qh,qw = q[1][0],q[1][1]
                if qh<0 or qh>=H or qw<0 or qw>=W:continue
                if S[qh][qw]=="
                if D[qh][qw]:continue
                D[qh][qw]=True
                ans = max(q[0],ans)
                heappush(Q,(q[0]+1,(qh+1,qw)))
                heappush(Q,(q[0]+1,(qh-1,qw)))
                heappush(Q,(q[0]+1,(qh,qw+1)))
                heappush(Q,(q[0]+1,(qh,qw-1)))
print(ans)

Solution (Python):
import os
import sys

import numpy as np
from scipy.sparse.csgraph._shortest_path import floyd_warshall

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7


H, W = list(map(int, sys.stdin.buffer.readline().split()))
S = [sys.stdin.buffer.readline().decode().rstrip() for _ in range(H)]


def to_i(h, w):
    return h * W + w


N = H * W
graph = [[0] * N for _ in range(N)]
for h in range(H):
    for w in range(W):
        if S[h][w] == '.':
            if 0 <= h - 1 < H and S[h - 1][w] == '.':
                graph[to_i(h - 1, w)][to_i(h, w)] = 1
                graph[to_i(h, w)][to_i(h - 1, w)] = 1
            if 0 <= h + 1 < H and S[h + 1][w] == '.':
                graph[to_i(h + 1, w)][to_i(h, w)] = 1
                graph[to_i(h, w)][to_i(h + 1, w)] = 1
            if 0 <= w - 1 < W and S[h][w - 1] == '.':
                graph[to_i(h, w - 1)][to_i(h, w)] = 1
                graph[to_i(h, w)][to_i(h, w - 1)] = 1
            if 0 <= w + 1 < W and S[h][w + 1] == '.':
                graph[to_i(h, w + 1)][to_i(h, w)] = 1
                graph[to_i(h, w)][to_i(h, w + 1)] = 1
dist = floyd_warshall(graph, directed=False)
dist[dist == np.inf] = 0
print(int(dist.max()))

Solution (Python):
import sys
import collections


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    h, w = list(map(int, readline().split()))
    s = [list(str(readline().rstrip().decode('utf-8'))) for _ in range(h)]

    mt = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] != "
                ql = [[0, i, j]]
                ql = collections.deque(ql)
                fq = collections.defaultdict(list)
                fq[i, j]
                while True:
                    if len(ql) != 0:
                        cost, xv, yv = ql.popleft()
                        mt = max(mt, cost)
                        for xv, yv in [[xv + 1, yv], [xv - 1, yv], [xv, yv + 1], [xv, yv - 1]]:
                            if 0 <= xv < h and 0 <= yv < w and s[xv][yv] != "
                                if (xv, yv) not in fq:
                                    ql.append([cost + 1, xv, yv])
                                    fq[xv, yv]
                    else:
                        break
    print(mt)


if __name__ == '__main__':
    solve()

Solution (Python):
import sys
from collections import deque

stdin = sys.stdin

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

n, m = na()
b = [ns() for _ in range(n)]
dr = [1, 0, -1, 0]
dc = [0, 1, 0, -1]
dmax = 0
for i in range(n):
    for j in range(m):
        if b[i][j] == ".":
            q = deque()
            q.append((i, j))
            d = [[9999999] * m for _ in range(n)]
            d[i][j] = 0
            while len(q):
                cur = q.popleft()
                dmax = max(dmax, d[cur[0]][cur[1]])
                for k in range(4):
                    nr, nc = cur[0] + dr[k], cur[1] + dc[k]
                    if 0 <= nr < n and 0 <= nc < m and b[nr][nc] == "." and d[nr][nc] > d[cur[0]][cur[1]] + 1:
                        d[nr][nc] = d[cur[0]][cur[1]] + 1
                        q.append((nr, nc))
print(dmax)

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    m = [(1,0),(-1,0),(0,1),(0,-1)]
    def bfs(sx,sy):
        d = [[float("inf")]*h for i in range(w)]
        d[sx][sy] = 0
        q = deque([(sx,sy)])
        res = 0
        while q:
            x,y = q.popleft()
            nd = d[x][y]+1
            for dx,dy in m:
                nx,ny = x+dx,y+dy
                if 0 <= nx < w and 0 <= ny < h:
                    if s[ny][nx] == "
                        continue
                    if nd < d[nx][ny]:
                        d[nx][ny] = nd
                        q.append((nx,ny))
                        res = nd
        return res
    h,w = LI()
    s = [input() for i in range(h)]
    ans = 0
    for y in range(h):
        for x in range(w):
            if  s[y][x] == ".":
                res = bfs(x,y)
                if ans < res:
                    ans = res
    print(ans)
    return


if __name__ == "__main__":
    solve()