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.



Sample input:
3 3
...
...
...


Sample output:
4

Submission status: Accepted

Solution code:
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
# MOD = 998244353

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()))

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

Solution code:
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()  # ignore trailing spaces

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)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
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

#Solve
if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
maze = [list(input()) for i in range(h)]

def find_shortest():
  d = [[float("inf")] * w for i in range(h)]
  dx = [1, 0, -1, 0]
  dy = [0, 1, 0, -1]

  que = deque([])
  que.append((sy,sx))
  d[sy][sx] = 0

  while que:
    p = que.popleft()
    if p[0] == gy and p[1] == gx:
      break
    for i in range(4):
      nx = p[0] + dx[i]
      ny = p[1] + dy[i]
      if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
        que.append((nx, ny))
        d[nx][ny] = d[p[0]][p[1]] + 1
  return d[gy][gx]

route = []

sg = []
for j in range(h):
  for i in range(w):
    if maze[j][i] == '.':
      sg.append([j,i])

ans = -1
for sy,sx in sg:
  for gy,gx in sg:
    if find_shortest() != float("inf"):
      ans = max(ans,find_shortest())

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

h,w = map(int,input().split())
maze = []

for _ in range(h):
    maze.append(input())

ans = 0

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

for i in range(h):
    for j in range(w):
        if(maze[i][j]=="."):
            dist = [ [99999999]*w for _ in range(i) ]
            
            dq = deque()
            y=i
            x=j
            d=0
            
            dq.append((y,x,d))
            
            while(len(dq)):
                
                y,x,d = dq.popleft()
                dist[y][x]=d
                for m in move:
                    if((0<=x+m[0]<w) and (0<=y+m[1]<h) and
                        (dist[y+m[1]][x+m[0]] > d+1) and
                            (maze[y+m[1]][x+m[0]] == ".")):
                                dq.append((y+m[1],x+m[0],d+1))
                                
            ans = max(ans,d)
            # print(d,i,j)
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

h,w = map(int,input().split())
maze = []

for _ in range(h):
    maze.append(input())

ans = 0

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

for i in range(h):
    for j in range(w):
        if(maze[i][j]=="."):
            dist = [ [99999999]*w for _ in range[i] ]
            
            dq = deque()
            y=i
            x=j
            d=0
            
            dq.append((y,x,d))
            
            while(len(dq)):
                
                y,x,d = dq.popleft()
                dist[y][x]=d
                for m in move:
                    if((0<=x+m[0]<w) and (0<=y+m[1]<h) and
                        (dist[y+m[1]][x+m[0]] > d+1) and
                            (maze[y+m[1]][x+m[0]] == ".")):
                                dq.append((y+m[1],x+m[0],d+1))
                                
            ans = max(ans,d)
            # print(d,i,j)
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

h,w = map(int,input().split())
maze = []

for _ in range(h):
    maze.append(input())

ans = 0

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

for i in range(h):
    for j in range(w):
        if(maze[i][j]=="."):
            dist = np.ones((h,w))*99999999
            
            dq = deque()
            y=i
            x=j
            d=0
            
            dq.append((y,x,d))
            
            while(len(dq)):
                
                y,x,d = dq.popleft()
                dist[y][x]=d
                for m in move:
                    if((0<=x+m[0]<w) and (0<=y+m[1]<h) and
                        (dist[y+m[1]][x+m[0]] > d+1) and
                            (maze[y+m[1]][x+m[0]] == ".")):
                                dq.append((y+m[1],x+m[0],d+1))
                                
            ans = max(ans,d)
            # print(d,i,j)
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
H, W = map(int, input().split())
maze = [input() for i in range(H)]

def bfs(maze, sy, sx, gy, gx):
    visited = [[-1]*W for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        if [y, x] == [gy, gx]:
            return visited[y][x]
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y+j, x+k
            if 0 <= new_y < H and 0 <= new_x < W:
                if maze[new_y][new_x] == "." and visited[new_y][new_x] == -1 :
                    visited[new_y][new_x] = visited[y][x] + 1
                    queue.append([new_y, new_x])
ma=0
for sy in range(H):
    for sx in range(W):
        for gy in range(H):
            for gx in range(W):

        if maze[sy][sx] == "." and maze[gy][gx] == ".":
            if bfs(maze,sy,sx,gy,gx) is not None:
                ma = max(bfs(maze, sy, sx, gy, gx),ma)
print(ma)

Submission status: Runtime Error

Solution code:
from collections import deque
from typing import List


def main():
    h, w = map(int, input().split())
    g = []
    for _ in range(h):
        r = input().split()
        g.append(r)
    print(mm(h, w, g))


def mm(h: int, w: int, g: List[List[str]]) -> int:
    ret = 0
    for i in range(h):
        for j in range(w):
            if (g[i][j] == '#'):
                continue
            cnt = 0
            q = deque([(i, j, cnt)])
            v = set()
            while q:
                ii, jj, cnt = q.popleft()
                v.add((ii, jj))
                ret = max(ret, cnt)
                # ↓
                if ii < h - 1 and g[ii + 1][jj] == '.' and (ii + 1, jj) not in v:
                    q.append((ii + 1, jj, cnt + 1))
                # →
                if jj < w - 1 and g[ii][jj + 1] == '.' and (ii, jj + 1) not in v:
                    q.append((ii, jj + 1, cnt + 1))
                # ↑
                if ii > 0 and g[ii - 1][jj] == '.' and (ii - 1, jj) not in v:
                    q.append((ii - 1, jj, cnt + 1))
                # ←
                if jj > 0 and g[ii][jj - 1] == '.' and (ii, jj - 1) not in v:
                    q.append((ii, jj - 1, cnt + 1))
    return ret


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
H, W = map(int,input().split())
grid = [list(input().split()) for _ in H]
res = 0
def bfs(tup,visited):
  def helper(tup, total):
    if tup in visited():
      res = max(res, total)
    elif tup[0]>=H or tup[0] < 0 or tup[1]>=W or tup[1]<0 or grid[tup[0]][tup[1]]:
      res = max(res, total)
    else:
      visited.add(tup)
      h, w = tup
      helper((h+1, w),total+1)
      helper((h-1, w),total+1)
      helper((h, w-1),total+1)
      helper((h, w+1),total+1)
  helper(tup,0)
  return res
      
ans = 0
for h in H:
  for w in W:
    if grid[h][w] == '#':
      continue
    ans = max(ans,bfs((h,w),set()))
print(ans)

Submission status: Runtime Error

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

def bfs(start):
    already = {}
    queue = []
    counter = 0
    queue.append((start[0], start[1], 0))
    already(start) = True
    max_depth = 0
    while counter < len(queue):
        y, x, depth = queue[counter]
        if depth > max_depth:
            max_depth = depth
        for move in ((-1, 0), (0, 1), (1, 0), (0, -1)):
            new_y = y + move[0]
            new_x = x + move[1]
            if new_y >= 0 \
            and new_y < H \
            and new_x >= 0 \
            and new_x < W \
            and S[new_y][new_x] == '.' \
            and (new_y, new_x) not in already:
                already[(new_y, new_x)] = True
                queue.append((new_y, new_x, depth+1))
        counter += 1
    return max_depth

answer = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        depth = bfs((i, j))
        if answer < depth:
            answer = depth
print(answer)

Submission status: Runtime Error

Solution code:
def dfs(i,x,y,maze):
    if not(0<=x<h) or not(0<=y<w):
        return
    if maze[x][y]=='#':
        return
    if maze[x][y]=='.':
        maze[x][y]=i
    if maze[x][y]>=i:
        maze[x][y]=i
        dfs(i+1,x+1,y,maze)
        dfs(i+1,x,y+1,maze)
        dfs(i+1,x-1,y,maze)
        dfs(i+1,x,y-1,maze)

import copy
h,w = map(int,input().split())
maze = []
for i in range(h):
    s = str(input())
    tmp = []
    for moji in s:
        tmp.append(moji)
    maze.append(tmp)

ans_list = []
for i in range(h):
    for j in range(w):
        myMaze = copy.copy(maze)
        dfs(0,i,j,myMaze)
        
        ans = 0
        for i in range(h):
            ans = max(ans,max([s for s in myMaze[i] if s!='#']))
        ans_list.append(ans)
print(max(ans_list))

Submission status: Runtime Error

Solution code:
from collections import deque
 
H, W = [int(x) for x in input().split()]
 
field = []
for i in range(H):
    field.append(input())
 
conn = [[[] for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            for e in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                h, w = i + e[0], j + e[1]
                if 0 <= h < H and 0 <= w < W and field[h][w] == '.':
                    conn[i][j].append([h, w])
d = 0
for i in range(H):
    for j in range(W):
        l = 0
        q = deque([[i, j]])
        dist = [[-1 for _ in range(W)] for _ in range(H)]
        dist[i][j] = 0
        while q:
            v = q.popleft()
            for w in conn[v[0]][v[1]]:
                if dist[w[0]][w[1]] == -1:
                    q.append(w)
                    dist[w[0]][w[1]] = dist[v[0]][v[1]] + 1
                    l = dist[w[0]][w[1]]
 
    	d = max(d, l)
 
print(d)

Submission status: Runtime Error

Solution code:
from collections import deque

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

field = []
for i in range(H):
    field.append(input())

conn = [[[] for _ in range(W)] for _ in range(H)]
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            for e in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                h, w = i + e[0], j + e[1]
                if 0 <= h < H and 0 <= w < W and field[h][w] == '.':
                    conn[i][j].append([h, w])
d = 0
for i in range(H):
    for j in range(W):
        if field[i][j] == '.':
            l = 0
            q = deque([[i, j]])
            dist = [[-1 for _ in range(W)] for _ in range(H)]
            dist[i][j] = 0
            while q:
                v = q.popleft()
                for w in conn[v[0]][v[1]]:
                    if dist[w[0]][w[1]] == -1:
                        q.append(w)
                        dist[w[0]][w[1]] = dist[v[0]][v[1]] + 1
                        l = dist[w[0]][w[1]]

        d = max(d, l)

print(d)

Submission status: Runtime Error

Solution code:
def abc151d_maze_master():
    h, w = map(int, input().split())
    s = []
    max_val = 0
    for i in range(h):
        s.append(input())
    for hi in range(h):
        for wi in range(w):
            if s[hi][wi] == '#': continue
            flg = [[-1] * w for _ in range(h)]
            flg[hi][wi] = 0
            q = [(0, hi, wi)]
            heapq.heapify(q)
            while len(q) > 0:
                d, hj, wj = heapq.heappop(q)
                for dh, dw in zip([0, 0, 1, -1], [1, -1, 0, 0]):
                    if 0 <= hj + dh < h and 0 <= wj + dw < w and s[hj + dh][wj + dw] != '#' and \
                            (flg[hj + dh][wj + dw] == -1 or flg[hj + dh][wj + dw] > flg[hj][wj] + 1):
                        heapq.heappush(q, (d + 1, hj + dh, wj + dw))
                        flg[hj + dh][wj + dw] = flg[hj][wj] + 1
                # print(q)
            max_val = max(max_val, max([max(v) for v in flg]))
    print(max_val)


abc151d_maze_master()

Submission status: Runtime Error

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

mv = {(1, 0), (-1, 0), (0, 1), (0, -1)}


def BFS(St):
    stk = deque([[St[0],St[1],0]])
    seen = [[False]*W for _ in range(H)]
    while len(stk) > 0:
        l = stk.pop()
        i = l[0]
        j = l[1]
        ct = l[2]
        seen[i][j] = True
        for k in mv:
            x = i+k[0]
            y = j+k[1]
            if 0 <= x < H and 0 <= y < W:
                if S[x][y] == '.' and seen[x][y] == False:
                    stk.appendleft([x, y, ct+1])
    return(ct)

ans = 0
# 各スタート地点に対して最大距離を出力すればいいですねって話

for i in range(H):
    for j in range(W):
        
            continue
        ans=max(ans,BFS([i,j]))
print(ans)

Submission status: Runtime Error

Solution code:
import collections
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall

H, W, *S = open(0).read().split()
H, W = [int(_) for _ in [H, W]]
A = []
B = []
C = []
for i in range(H * W):
    x, y = divmod(i, W)
    if S[x][y] == '.':
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            nx, ny = x + dx, y + dy
            if not (0 <= nx < H and 0 <= ny < W):
                continue
            if S[nx][ny] == '.':
                A += [i]
                B += [nx * W + ny]
                C += [1]
print(int(np.max(floyd_warshall(csr_matrix((C, (A, B)), shape=(H*W, H*W))))))

Submission status: Runtime Error

Solution code:
import collections
H, W, *S = open(0).read().split()
H,W=[int(_) for _ in [H,W]]
G = [set() for _ in range(H * W)]
for i in range(H * W):
    x, y = divmod(i, W)
    if S[x][y] == '.':
        for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            nx, ny = x + dx, y + dy
            if not (0 <= nx < H and 0 <= ny < W):
                continue
            if S[nx][ny] == '.':
                G[i].add(nx * W + ny)
dist = [INF] * (H * W)
ans = 0
for s in range(H * W):
    if len(G[s]) and dist[s] != INF:
        Q = collections.deque([s])
        INF = 10 ** 10
        dist[s] = 0
        while True:
            if not Q:
                break
            i = Q.popleft()
            d = d1[i]
            for j in G[i]:
                if d1[j] != INF:
                    continue
                k = j
                d1[j] = d + 1
                Q.appendleft(j)
        d1 = [INF] * (H * W)
        d1[k] = 0
        Q = collections.deque([k])
        while True:
            if not Q:
                break
            i = Q.popleft()
            d = d1[i]
            for j in G[i]:
                if d1[j] != INF:
                    continue
                k = j
                d1[j] = d + 1
                Q.appendleft(j)
        ans = max(ans, d1[k])
print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50

def bfs(MAZE, goal, start, seen, H, W):
    queue = deque([start + (0 ,)])
    while queue:
        y,x,count = queue.popleft()
        if (y, x) == goal:
            return count
        for i,j in ((0,1), (0,-1), (1,0), (-1, 0)):
            next_y, next_x = y + i, x + j
            if not seen[next_y][next_x] and MAZE[next_y][next_x] == '.' and 1 <= next_x <= W and 1 <= next_y <= H:
                seen[next_y][next_x] = 1
                queue.append((next_y, next_x, count+1))
    return False


def dfs(MAZE, goal, current, seen, H, W, min_count = INF):
    y, x, count = current
    #print(x,y,count)
    if count > min_count:
        return min_count
    if (y,x) == goal:
        min_count = min(min_count, count)
    else:
        for i,j in ((0,1), (0,-1), (1,0), (-1, 0)):
            next_y, next_x = y+i, x+j
            if 1 <= next_x <= W and 1 <= next_y <= H and not seen[next_y][next_x] and MAZE[next_y][next_x] == '.':
                seen[next_y][next_x] = 1
                min_count = min(dfs(MAZE, goal, (next_y, next_x, count+1), seen, H, W, min_count), min_count)
                seen[next_y][next_x] = 0
    return min_count

def run():
    H, W = map(int, input().split())
    MAZE = ['#' * (W+2)]
    for _ in range(H):
        s = input()
        s = '#' + s + '#'
        MAZE.append(s)
    MAZE.append('#' * (W+2))

    seen = [[0] * (W+2) for i in range(H+1)]
    ways = []
    for i in range(1, H+1):
        for j in range(1, W+1):
            if MAZE[i][j] == '.':ways.append((i, j))

    max_count = 0
    for s_i, s_j in ways:
        for g_i, g_j in ways:
            if s_i == g_i and s_j == g_j:continue
            seen = [[0] * (W+2) for i in range(H+1)]
            min_count = bfs(MAZE, (g_i, g_j), (s_i, s_j), seen, H, W)
            #print((s_i, s_j), '->', (g_i, g_j))
            #print(min_count)
            if not min_count:
                continue
            max_count = max(max_count, min_count)
            seen[s_i][s_j] = 0

    print(max_count)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[11]:


from collections import deque


# In[23]:


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


# In[24]:


def bfs(sx,sy):
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    d = [[-1]*W for _ in range(H)]
    q = deque([])
    q.append([sx,sy])
    d[sx][sy] = 0
    ans = 0
    while q:
        x,y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "#" and d[nx][ny] == -1:
                q.append([nx,ny])
                d[nx][ny] = d[x][y] + 1
                ans = max(ans,d[nx][ny])
    return ans


# In[25]:


for sh in range(H):
    if "." in S[sh]:
        for sw in range(W):
            if S[sh][sw] == ".":
                ans = max(ans,bfs(sh,sw))
print(ans)


# In[ ]:

Submission status: Runtime Error

Solution code:
import queue

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

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

ans=0
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            seen=[[0 for _ in range(w)] for _ in range(h)]
            length=[[0 for _ in range(w)] for _ in range(h)]
            q=queue.Queue()
            q.put([i,j])
            seen[i][j]=1
            while not q.empty():
                ci,cj=q.get()
                for ni,nj in [[ci-1,cj],[ci+1,cj],[ci,cj-1],[ci,cj+1]]:
                    if 0<=ni<h and 0<=nj<w and s[ni][nj]=="." and seen[ni][nj]==0:
                        q.put([ni,nj])
                        length[ni][nj]=length[ci][cj]+1
                        seen[ni][nj]=1
        ans=max(ans,max(max(length)))

print(ans)

Submission status: Runtime Error

Solution code:
import math
H, W = map(int, input().split())
S = []
for i in range(H):
  S.append(str(input()))
d = [[float('inf') for i in range(V)] for j in range(V)]

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, string, queue, copy
import numpy as np
import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

h,w = inpm()
maze = inplL(h)

ans = 0
for sh in range(h):
    for sw in range(w):
        q = queue.Queue()
        q.put((sh,sw,0))

        field = [[-1]*w for i in range(h)]
        tmp = 0
        while not q.empty():
            yy,xx,kk = q.get()
            if field[yy][xx] >= 0: continue

            field[yy][xx] = kk
            if tmp < kk:
                gh,gw = (yy,xx)
                tmp = kk
            if yy != h-1 and maze[yy+1][xx] == '.':
                q.put((yy+1,xx,kk+1))
            if xx != w-1 and  maze[yy][xx+1] == '.':
                q.put((yy,xx+1,kk+1))
            if yy != 0 and  maze[yy-1][xx] == '.':
                q.put((yy-1,xx,kk+1))
            if xx != 0 and  maze[yy][xx-1] == '.':
                q.put((yy,xx-1,kk+1))
        ans = max(ans,field[gh][gw])

print(ans)