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: Runtime Error

Solution code:
import sys
import numpy as np

S = []
for e in sys.stdin:
    S.append(e.rstrip())

H, M = map(int, S[0].split())

meiro = []
for i in range(H):
    meiro.append([])
    for k in S[i + 1]:
        if k == '.':
            meiro[i].append(1)
        else:
            meiro[i].append(0)
meiro_array = np.array(meiro)
susumikata = [[1, 0], [-1, 0], [0, 1], [0, -1]]


def BFS(x, y):
    global max_distance
    if meiro_array[x, y] == 1:
        max_distance = 0
        reached = {(x, y): 0}
        for i in range(H * M):
            zahyous = [k for k, v in reached.items() if v == i]
            for zahyou in zahyous:
                for susumi in susumikata:
                    new_zahyou = tuple([zahyou[0] + susumi[0], zahyou[1] + susumi[1]])
                    if not(0 <= new_zahyou[0] < H and 0 <= new_zahyou[1] < M):
                        a = 0
                    elif new_zahyou not in reached.keys() and meiro_array[new_zahyou] == 1:
                        reached[new_zahyou] = i + 1
                        max_distance = i + 1

    return max_distance


keiro_max = []
for x in range(H):
    for y in range(M):
        keiro_max.append(BFS(x, y))

print(max(keiro_max))

Submission status: Runtime Error

Solution code:
h,w = (int(x) for x in input().split())
ab = []
count = 0
for _ in range(h):
    a = input()
    a = a+'#'
    ab.append(list(a))
ab.append(list('#'*w))
mx = 0

for i in range(h):
    for j in range(w):
        dp = [[0 for i in range(w)] for j in range(h)]
        step = [[i, j]]

        while len(step) > 0:
            y, x = step.pop(0)
            if ab[y+1][x] == '.' and dp[y+1][x] == 0 :
                step.append([y+1, x])
                dp[y+1][x] = dp[y][x] + 1
            if ab[y][x+1] == '.' and dp[y][x+1] == 0 :
                step.append([y, x+1])
                dp[y][x+1] = dp[y][x] + 1
            if ab[y-1][x] == '.' and dp[y-1][x] == 0 :
                step.append([y-1, x])
                dp[y-1][x] = dp[y][x] + 1
            if ab[y][x-1] == '.' and dp[y][x-1] == 0 :
                step.append([y, x-1])
                dp[y][x-1] = dp[y][x] + 1
        mx = max([mx, max(list(itertools.chain.from_iterable(dp)))])

print(mx)

Submission status: Runtime Error

Solution code:
from collections import deque
from itertools import chain
from math import inf

H, W = map(int, input().split())
maze = [list(input()) for _ in range(H)]
directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]


def bfs(start):
    queue = deque()
    queue.append(start)

    distance = [[inf] * W for _ in range(H)]
    sx, sy = start
    distance[sx][sy] = 0

    while len(queue) > 0:
        x, y = queue.popleft()
        for dx, dy in directions:
            nx = x + dx
            ny = y + dy
            if nx >= 0 and nx < H and ny >= 0 and ny < W and maze[nx][ny] == '.' and distance[nx][ny] == inf:
                queue.append((nx, ny))
                distance[nx][ny] = distance[x][y] + 1

    return max(filter(lambda d: d != inf, chain.from_iterable(distance)))


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

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

h, w = map(int, input().split())
c = [list(input()) for i in range(h)]
ans = -1

def bfs(sx, sy):
    que = deque([[sy, sx]])
    d = [["."] * w for _ in range(h)]
    count = 0
    d[sy][sx] = 0
    while que:
        y, x = que.popleft()
        for i, j in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            nx, ny = x+i, y+j
            if 0 <= nx and nx < w and 0 <= ny and ny < h and d[ny][nx] == "." and c[ny][nx] != "#":
                nx_, ny_ = nx-i, ny-j
                d[ny][nx] = d[ny_][nx_] + 1
                que.append([ny, nx])
    return max(max(d))

for i_ in range(h):
    for j_ in range(w):
        if c[i_][j_] == "#":
            continue
        ans = max(ans, bfs( j_, i_))

print(ans)

Submission status: Runtime Error

Solution code:
import collections

h,w = map(int,input().split())
maze = []
ans = 0
dy_dx = [[0,1],[1,0],[0,-1],[-1,0]]
for i in range(h):
    s = input()
    a = []
    for j in range(w):
        a.append(s[j])
    maze.append(a)
for i in range(h):
    for j in range(w):
        if maze[i][j] != '#':
            next = collections.deque()
            dist = []
            checked = []
            curmax = 0
            for k in range(h):
                a = [0]*w
                b = [0]*w
                dist.append(a)
                checked.append(b)
            next.append([i,j])
            while len(next) != 0:
                cur = next.popleft()
                checked[cur[0]][cur[1]] = 1
                for l in range(4):
                    t = cur[0]+dy_dx[l][0]
                    u = cur[1]+dy_dx[l][1]
                    if (0 <= t <= h-1) and (0 <= u <= w-1):
                        if checked[t][u] == 0:
                            if maze[t][u] == '.':
                                dist[t][u] = dist[cur[0]][cur[1]]+1
                                next.append([t,u])
                                curmax = max(curmax,dist[t][u])
        ans = max(ans,curmax)
print(ans)

Submission status: Runtime Error

Solution code:
import collections

h,w = map(int,input().split())
maze = []
ans = 0
dy_dx = [[0,1],[1,0],[0,-1],[-1,0]]
for i in range(h):
    s = input()
    a = []
    for j in range(w):
        a.append(s[j])
    maze.append(a)
for i in range(h):
    for j in range(w):
        if maze[i][j] != '#':
            next = collections.deque()
            dist = []
            checked = []
            curmax = 0
            for k in range(h):
                a = [0]*w
                b = [0]*w
                dist.append(a)
                checked.append(b)
            next.append([i,j])
            while len(next) != 0:
                cur = next.popleft()
                checked[cur[0]][cur[1]] = 1
                for l in range(4):
                    if (0 <= cur[0]+dy_dx[l][0] <= h-1) and (0 <= cur[1]+dy_dx[l][1] <= w-1):
                        if checked[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]] == 0:
                            if maze[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]] == '.':
                                dist[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]] = dist[cur[0]][cur[1]]+1
                                next.append([cur[0]+dy_dx[l][0],cur[1]+dy_dx[l][1]])
                                curmax = max(curmax,dist[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]])
        ans = max(ans,curmax)
print(ans)

Submission status: Runtime Error

Solution code:
import collections

h,w = map(int,input().split())
maze = []
ans = 0
dy_dx = [[0,1],[1,0],[0,-1],[-1,0]]
for i in range(h):
    s = input()
    a = []
    for j in range(w):
        a.append(s[j])
    maze.append(a)
for i in range(h):
    for j in range(w):
        if maze[i][j] != '#':
            next = collections.deque()
            dist = []
            checked = []
            curmax = 0
            for k in range(h):
                a = [0]*w
                b = [0]*w
                dist.append(a)
                checked.append(b)
            next.append([i,j])
            while len(next) != 0:
                cur = next.popleft()
                checked[cur[0]][cur[1]] = 1
                for l in range(4):
                    if (0 <= cur[0]+dy_dx[l][0] <= h-1) and (0 <= cur[1]+dy_dx[l][1] <= w-1):
                        if checked[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]] == 0:
                            if maze[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]] == '.':
                                dist[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]] = dist[cur[0]][cur[1]]+1
                                next.append([cur[0]+dy_dx[l][0],cur[1]+dy_dx[l][1]])
                                curmax = max(curmax,dist[cur[0]+dy_dx[l][0]][cur[1]+dy_dx[l][1]])
        ans = max(ans,curmax)
print(ans)

Submission status: Runtime Error

Solution code:
h,w = map(int, input().split())
board = [list(input()) for i in range(h)]

road = []

for i in range(h):
    for j in range(w):
        if board[i][j] == ".":
            road.append([i,j])

from heapq import heappop, heappush

def dfs(start, end):
    dxdy = [(0,1),(1,0),(0,-1),(-1,0)]
    dist = [[float("inf")]*w for i in range(h)]
    heap = [(0, *start)]
    while heap:
        c,x,y = heappop(heap)
        if dist[x][y] <= c:
            continue
        dist[x][y] = c
        for dx, dy in dxdy:
            nx = x + dx
            ny = y + dy
            if 0<=nx<h and 0<=ny<w and board[nx][ny] == ".":
                heappush(heap, (c+1, nx, ny))
    return dist[end[0]][end[1]]


from itertools import combinations

ans = 0
for start, end in combinations(road, 2):
    #print(start, end)
    tmp = dfs(start, end)
    if tmp != float("inf"):
        ans = max(ans, tmp)
print(ans)

Submission status: Runtime Error

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

N = H * W
D = []
for i in range(N):
  d = [N  for _ in range(N)]
  d[i] = 0
  D.append(d)
for row in range(H):
  for col in range(W):
    i = row * W + col
    if row < H - 1:
      j = i + H
      if S[row][col] == '.' and S[row+1][col] == '.':
        D[i][j] = D[j][i] = 1
    if col < W - 1:
      k = i + 1
      if S[row][col] == '.' and S[row][col+1] == '.':
        D[i][k] = D[k][i] = 1

for i in range(N):
  for j in range(N):
    for k in range(N):
      D[j][k] = min(D[j][k], D[j][i] + D[i][k])

print(max([max([e for e in d if e < N]) for d in D]))

Submission status: Runtime Error

Solution code:
import queue
from itertools import product

test_lines = test_input.split("\n")
H, W = map(int, test_lines.pop(0).split())
road_grid = [row for row in test_lines]

# for each start point, find the furthest travellable point
# then return largest path length of all these
# ps y is down, x is right
furthest_so_far = -1
for y_init, x_init in product(range(H), range(W)):
    if road_grid[y_init][x_init] == "#": continue
    boundary = queue.Queue()
    boundary.put((y_init, x_init))
    steps_taken = [[-1]*W for _ in range(H)]
    steps_taken[y_init][x_init] = 0
    while not boundary.empty():
        y, x = boundary.get()
        neighbours = [(y+1, x), (y, x+1), (y-1, x), (y, x-1)]
        for (new_y, new_x) in neighbours:
            if (0 <= new_y < H and 0 <= new_x < W
                and steps_taken[new_y][new_x] == -1 and road_grid[new_y][new_x] == "."):
                steps_taken[new_y][new_x] = steps_taken[y][x] + 1
                boundary.put((new_y, new_x))
    furthest_so_far = max(furthest_so_far, max(max(steps_taken)))
print(furthest_so_far)

Submission status: Runtime Error

Solution code:
import queue
height,width=map(int,input().split())

graph=[]
for _ in range(height):
    s_row = input()
    row = []
    for s in s_row:
        row.append(s)
    graph.append(row)

diff=[[0,-1],[0,1],[-1,0],[1,0]]
max_step=[]
for h in range(height):
    for w in range(width):
        if graph[h][w]=='#':
            continue

        route = []
        for _ in range(height):
            route.append([-1]*width)

        # start x,y,経路数
        q = queue.Queue()
        q.put([w,h,0])

        while not q.empty():
            now = q.get()

            route[now_h][now[0]] = now[2]

            for dx,dy in diff:
                next_w = now[0]+dx
                next_h = now[1]+dy
                if   width<=next_w \
                  or height<=next_h \
                  or next_w < 0 \
                  or next_h < 0 \
                  or graph[next_h][next_w]=='#' \
                  or route[next_h][next_w]>-1:
                    continue
                q.put([next_w, next_h, now[2]+1])
        
        max_step.append(max(max(step) for step in route))
        
print(max(max_step))

Submission status: Runtime Error

Solution code:
import queue
height,width=map(int,input().split())

graph=[]
for _ in range(height):
    s_row = input()
    row = []
    for s in s_row:
        row.append(s)
    graph.append(row)

diff=[[0,-1],[0,1],[-1,0],[1,0]]
max_step=[]
for h in range(height):
    for w in range(width):
        if graph[h][w]=='#':
            continue

        route = []
        for _ in range(height):
            route.append([-1]*width)

        # start x,y,経路数
        q = queue.Queue()
        q.put([w,h,0])

        while not q.empty():
            now = q.get()
            now_w = now[0]
            now_h = now[1]
            now_n = now[2]

            route[now_h][now_w] = now_n

            for dx,dy in diff:
                next_w = now_w+dx
                next_h = now_h+dy
                if   width<next_w \
                  or height<next_h \
                  or next_w < 0 \
                  or next_h < 0 \
                  or graph[next_h][next_w]=='#' \
                  or route[next_h][next_w]>-1:
                    continue
                q.put([next_w, next_h, now_n+1])
        
        max_step.append(max(max(step for step in route)))
        
print(max(max_step))

Submission status: Runtime Error

Solution code:
from collections import deque
from copy import copy

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

dxs = [0, 0, 1, -1]
dys = [1, -1, 0, 0]
cand = []
field_org = [-1] * (W * H)
for j in range(H):
    for i in range(W):
        if S[j][i] == '#':
            continue
        q = deque()
        q.append((i, j, 0))
        field = copy(field_org)
        field[j * H + i] = 0
        while q:
            p = q.popleft()
            for dx, dy in zip(dxs, dys):
                x, y = p[0] + dx, p[1] + dy
                f_idx = y * H + x
                if not (0 <= x < W) or not (0 <= y < H) or S[y][x] == '#' or field[f_idx] != -1:
                    continue
                field[f_idx] = p[2] + 1
                q.append((x, y, p[2] + 1))
        cand.append(max(field))
print(max(cand))

Submission status: Runtime Error

Solution code:
# coding:utf-8

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

index_map = [[i * w + j for j in range(w)] for i in range(h)]
rev_index_map = [(int(i / w), i % w) for i in range(h * w)]
diff = [[h * w + 1 for i in range(h * w)] for j in range(h * w)]


def isSame(r1, c1, r2, c2):
    if r1 != r2:
        return False
    if c1 != c2:
        return False
    return True


def isNear(r1, c1, r2, c2):
    if r1 == r2:
        if abs(c1 - c2) == 1:
            return True
    elif abs(r1 - r2) == 1:
        if c1 == c2:
            return True
    return False


ans = 0

for idx1 in range(h * w):
    for idx2 in range(h * w):
        (r2, c2) = rev_index_map[idx2]
        if map[r2][c2] == "#":
            continue
        for idx3 in range(h * w):
            (r3, c3) = rev_index_map[idx3]
            if map[r3][c3] == "#":
                continue
            if isSame(r2, c2, r3, c3):
                diff[idx2][idx3] = 0
            elif isNear(r2, c2, r3, c3):
                diff[idx2][idx3] = 1
            else:
                tmp = dif[idx2][idx1] + diff[idx1][idx3]
                if diff[idx2][idx3] > tmp:
                    diff[idx2][idx3] = tmp

for i in diff:
    for j in i:
        if j > h*w:
            continue
        ans = max(ans,j)
print(ans)

Submission status: Runtime Error

Solution code:
# coding:utf-8

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

index_map = [[i * w + j for j in range(w)] for i in range(h)]
rev_index_map = [(int(i / w), i % w) for i in range(h * w)]
diff = [[h * w + 1 for i in range(h * w)] for j in range(h * w)]


def isSame(r1, c1, r2, c2):
    if r1 != r2:
        return False
    if c1 != c2:
        return False
    return True


def isNear(r1, c1, r2, c2):
    if r1 == r2:
        if abs(c1 - c2) == 1:
            return True
    elif abs(r1 - r2) == 1:
        if c1 == c2:
            return True
    return False


ans = 0

for idx1 in range(h * w):
    for idx2 in range(h * w):
        (r2, c2) = rev_index_map[idx2]
        if map[r2][c2] == "#":
            continue
        for idx3 in range(h * w):
            (r3, c3) = rev_index_map[idx3]
            if map[r3][c3] == "#":
                continue
            if isSame(r2, c2, r3, c3):
                diff[idx2][idx3] = 0
            elif isNear(r2, c2, r3, c3):
                diff[idx2][idx3] = 1
            else:
                tmp = dif[idx2][idx1] + diff[idx1][idx3]
                if diff[idx2][idx3] > tmp:
                    diff[idx2][idx3] = tmp

for i in diff:
    for j in i:
        if j > h*w:
            continuef
        ans = max(ans,j)
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import numpy as np
 
 
H,W= [int(x) for x in input().split()]
n=[]
T=np.zeros((H,W),dtype=int)
T=[]
S=np.zeros_like(T,dtype=int) 
for i in range(H):
  T[i]=[x for x in input().split()]
#B=T.copy()    
d=0
c=deque()  
for i in range(H):
    for j in range(W):
         
        if T[i][j] =="#":continue
 
          
        c.append((i,j))
        S[i][j] = 1
        #c.append(j)
        
        #t=len(c)
        while True:

                try:
                  m,n = c.popleft()
                except IndexError: break
                
                
                for kk in [(m+1,n),(m-1,n),(m,n+1),(m,n-1)]:
                  if not (0<=kk[0]<H and 0<= kk[1] <W): continue
                  if T[kk]=="#":continue
                  if S[kk] == 0:
                    c.append(kk)
                    S[kk] = S[m][n]+1        
                        
 
        #print(T)
        d = max(d,np.max(S))
        S=np.zeros_like(T,dtype=int)
        
print(d-1)

Submission status: Runtime Error

Solution code:
import queue

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

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

ans = 0

for i in range(h) :
    for j in range(w) :
        #print(i,j)
        if s[i][j] == '#' :
            continue
        dist = [[-1 for i in range(w)] for j in range(h)]
        q = queue.Queue()
        q.put([i,j])
        dist[i][j] = 0
        cnt = 0
        while not q.empty() :
            xy = q.get()
            for k in range(4) :
                y = xy[0] + dx[k]
                x = xy[1] + dy[k]
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if dist[y][x] != -1 :
                    continue
                q.put([x, y])
                dist[y][x] = dist[xy[0]][xy[1]] + 1
        for k in range(h) :
            for l in range(w) :
                ans = max(ans, dist[k][l])
        #print(dist)


print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
#abc151_d
import sys
from collections import deque
mv = ((1,0),(-1,0),(0,1),(0,-1))
h,w = map(int,input().split())
board = [["#"]*(w+2) for _ in range(h+2)]
for i in range(h):
    s = input()
    for j in range(w):
        board[i+1][j+1] = str(s[j])
cur_max = 0 # 初期点を変更しながら全探索した時のmax
#print(board[0][0] == ".")
for i in range(h+2):
    for j in range(w+2):
        #print(i,j,board[i][j])
        tmp =  board[i][j]
        if tmp == ".":
            visit = deque()
            start_pos = (i,j)
            visit.append(start_pos)
            cnt = [[-1]*(w+2) for _ in range(h+2)] # -1埋め
            cnt[i][j] = 0 #スタート地点は0
            while visit:
                point = visit.popleft()
                for i in mv:
                    pos = point + i
                    if str(board[pos[0]][pos[1]]) == ".":
                        if cnt[pos[0]][pos[1]] == -1: #unvisited
                            cnt[pos[0]][pos[1]] = cnt[point[0]][point[1]] + 1
                            if cnt[pos[0]][pos[1]] > cur_max:
                                cur_max = cnt[pos[0]][pos[1]]
print(cur_max)                    

"""



# 既に訪れたかどうかを確かめるため、最短経路パスを保存するためにh+2*w+2の２次元配列を用意する
for i in range(h+2):
	for j in range(w+2):
		if i*(i-h-2) == 0 or j*(j-w-2) == 0 or s[i-1][j-1] == "#":
			#ここは通れない地点なのでdist = -1にする
			dist[i][j] = -1
        else: 
            dist[i][j] = 0
# スタートにできる全ての地点に対してループを回す
ans = 0
for i in range(h+2):
    for j in range(w+2):
        if dist[i][j] == 0:
            q = deque()
            start_pos = (i,j)
            q.append(start_pos)
            max_ = 0
            while len(q) > 0:
                pos = q.popleft()
                for i in range(4):
                    next_pos = (pos[0]+mv[i][0],pos[1]+mv[i][1])
                    if dist[next_pos[0]][next_pos[1]] == 0:
                        dist[next_pos[0]][next_pos[1]] = dist[pos[0]][pos[1]] + 1 
                        q.append(next_pos)
                        max_ = max(max_,dist[next_pos[0]][next_pos[1]])
            ans = max(max_,ans)
print(ans)"""

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
from collections import deque
visited = deque()
# inputで盤面と、start,goalをいれる
r,c = map(int,input().split())
s = tuple(map(int,input().split()))
g = tuple(map(int,input().split()))
s = (s[0]-1,s[1]-1)
g = (g[0]-1,g[1]-1) 
visited.append(s)
maze = []
for x in range(r):
	maze.append(input())
cost = [[-1]*c for _ in range(r)]
cost[s[0]][s[1]] = 0
flag = 0
while visited and flag == 0:
    start = visited.popleft()
    #print(start)
    for dx,dy in ((1,0),(0,-1),(0,1),(-1,0)):
        tmp = (start[0]+dx,start[1]+dy)
        if maze[start[0]+dx][start[1]+dy] == ".":
            if cost[start[0]+dx][start[1]+dy] == -1:
                cost[start[0]+dx][start[1]+dy] = cost[start[0]][start[1]] + 1
                visited.append(tmp)
                if tmp == g:
                    flag = cost[start[0]+dx][start[1]+dy]
print(flag)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque
mv = ((1,0),(-1,0),(0,1),(0,-1))
h,w = map(int,input().split())
board = [["#"]*(w+2) for _ in range(h+2)]
for i in range(h):
    s = input()
    for j in range(w):
        board[i+1][j+1] = str(s[j])
cur_max = 0 # 初期点を変更しながら全探索した時のmax
#print(board[0][0] == ".")
for i in range(h+2):
    for j in range(w+2):
        #print(i,j,board[i][j])
        if str(board[i][j]) == "#":
            visit = deque()
            start_pos = (i,j)
            visit.append(start_pos)
            cnt = [[-1]*(w+2) for _ in range(h+2)] # -1埋め
            cnt[i][j] = 0 #スタート地点は0
            while visit:
                point = visit.popleft()
                for i in mv:
                    pos = point + i
                    if str(board[pos[0]][pos[1]]) == ".":
                        if cnt[pos[0]][pos[1]] == -1: #unvisited
                            cnt[pos[0]][pos[1]] = cnt[point[0]][point[1]] + 1
                            if cnt[pos[0]][pos[1]] > cur_max:
                                cur_max = cnt[pos[0]][pos[1]]
print(cur_max)                    

"""



# 既に訪れたかどうかを確かめるため、最短経路パスを保存するためにh+2*w+2の２次元配列を用意する
for i in range(h+2):
	for j in range(w+2):
		if i*(i-h-2) == 0 or j*(j-w-2) == 0 or s[i-1][j-1] == "#":
			#ここは通れない地点なのでdist = -1にする
			dist[i][j] = -1
        else: 
            dist[i][j] = 0
# スタートにできる全ての地点に対してループを回す
ans = 0
for i in range(h+2):
    for j in range(w+2):
        if dist[i][j] == 0:
            q = deque()
            start_pos = (i,j)
            q.append(start_pos)
            max_ = 0
            while len(q) > 0:
                pos = q.popleft()
                for i in range(4):
                    next_pos = (pos[0]+mv[i][0],pos[1]+mv[i][1])
                    if dist[next_pos[0]][next_pos[1]] == 0:
                        dist[next_pos[0]][next_pos[1]] = dist[pos[0]][pos[1]] + 1 
                        q.append(next_pos)
                        max_ = max(max_,dist[next_pos[0]][next_pos[1]])
            ans = max(max_,ans)
print(ans)"""

Submission status: Runtime Error

Solution code:
H,W= [int(x) for x in input().split()]
n=[]
T=np.zeros((H,W),dtype=int)

for i in range(H):
  n=input()
  for j in range(W):
    if n[j]=="#": T[i][j]=1
B=T.copy()    
d=0
for i in range(H):
    for j in range(W):
         
        if T[i][j] ==1:continue

        c=deque()    
        s=0
        c+=[i,j]
        
        t=len(c)//2
        while t>0:
                s+=1
                t=len(c)//2
                for k in range(t):
                        m = c.popleft()
                        n = c.popleft()
                        T[m][n]=s
                        if m != H-1:
                                if T[m+1][n]==0:
                                        c.append(m+1)
                                        c.append(n)
                        if m != 0:
                                if T[m-1][n]==0:
                                        c.append(m-1)
                                        c.append(n)
 
                        if n != W-1:
                                if T[m][n+1]==0:
                                        c.append(m)
                                        c.append(n+1)
                                        
                        if n != 0:
                                if T[m][n-1]==0:
                                        c.append(m)
                                        c.append(n-1)

        #print(T)
        d = max(d,s)
        T=B.copy()
        
print(d-2)

Submission status: Runtime Error

Solution code:
n, m = list(map(int, input().split()))
maze = []
for i in range(n):
  l = input()
  dl = []
  for j in range(m):
    if l[j] == '.':
      dl.append(0)
    else:
      dl.append(1)
  maze.append(dl)
ans = 0
for i in range(n):
  for j in range(m):
    if maze[i][j] == 0:
      a = [list(l) for l in maze]
      a[i][j] = 1
      q = [(i, j)]
      d = 0
      while len(q) > 0:
        nq = []
        d += 1
        for x, y in q:
          if x > 0 and a[x - 1][y] == 0:
            a[x - 1][y] = 1
            np.append((x - 1, y))
          if y > 0 and a[x][y - 1] == 0:
            a[x][y - 1] = 1
            np.append((x, y - 1))
          if x < n - 1 and a[x + 1][y] == 0:
            a[x + 1][y] = 1
            np.append((x + 1, y))
          if y < m - 1 and a[x][y + 1] == 0:
            a[x][y + 1] = 1
            np.append((x, y + 1))
        q = nq
      ans = max(ans, d)
print(ans)

Submission status: Runtime Error

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

for i in range(H):
    S = input()
    for j in range(W):
        s = S[j]
        if s=='.':
            D[i][j] = 1

ans = 0
import heapq

for i in range(H):
    for j in range(W):
        if D[i][j] == 1:
            tmp = 0
            h = [[0,i,j]]
            visited = [[0]*W for i in range(H)]
            while h!=[]:
                w,nowi,nowj = heapq.heappop(h)
                tmp = max(tmp,w)
                visited[nowi][nowj] = 1
                if 0<nowi<H-1:
                    for k in [-1,1]:
                        if D[nowi+k][nowj]==1 and visited[nowi+k][nowj]==0:
                            heapq.heappush(h,[w+1,nowi+k,nowj])
                            visited[nowi+k][nowj]=1
                elif nowi==0:
                    if D[nowi+1][nowj]==1 and visited[nowi+1][nowj]==0:
                        heapq.heappush(h,[w+1,nowi+1,nowj])
                        visited[nowi+1][nowj]=1
                else:
                    if D[nowi-1][nowj]==1 and visited[nowi-1][nowj]==0:
                        heapq.heappush(h,[w+1,nowi-1,nowj])
                        visited[nowi-1][nowj]=1

                if 0<nowj<W-1:
                    for k in [-1,1]:
                        if D[nowi][nowj+k]==1 and visited[nowi][nowj+k]==0:
                            heapq.heappush(h,[w+1,nowi,nowj+k])
                            visited[nowi][nowj+k]=1
                elif nowj == W-1:
                    if D[nowi][nowj-1]==1 and visited[nowi][nowj-1]==0:
                        heapq.heappush(h,[w+1,nowi,nowj-1])
                        visited[nowi][nowj-1]=1
                else:
                    if D[nowi][nowj+1]==1 and visited[nowi][nowj+1]==0:
                        heapq.heappush(h,[w+1,nowi,nowj+1])
                        visited[nowi][nowj+1]=1
            ans = max(ans,tmp)
            
print(ans)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from copy import copy
from queue import Queue

H, W = map(int, input().split())

maze = []
for _ in range(H):
  maze.append([i for i in input()])
  
# 無向グラフを作ってワーシャルフロイド法で解く
d = {}
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      d[((i, j), (i, j))] = 0

directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      for di, dj in directions:
        if i + di >= 0 and i + di < H\
        and j + dj >= 0 and j + dj < W\
        and maze[i + di][j + dj] == '.':
          d[((i, j), (i + di, j + dj))] = 1
          d[((i + di, j + dj), (i, j))] = 1

            
# 連結成分ごとにワーシャルフロイド法を実行し、最大距離を計算する
for i1 in range(H):
  for j1 in range(W):
    for i2 in range(H):
      for j2 in range(W):
        for i3 in range(H):
          for j3 in range(W):
            if maze[i1][j1] == '.'\
            and maze[i2][j2] == '.'\
            and maze[i3][j3] == '.':
              d[((i1, j1), (i3, j3))]\
              = min(
                d[((i1, j1), (i3, j3))],
                d[((i1, j1), (i2, j2))] + d[((i2, j2), (i3, j3))]
              )

# 全ての連結成分の最大距離を求めて出力

ret = 0
for i1 in range(H):
  for j1 in range(W):
    for i2 in range(H):
      for j2 in range(W):
        if d[((i1, j1), (i2, j2))] != inf\
        and d[((i1, j1), (i2, j2))] > ret:
          ret = d[((i1, j1), (i2, j2))]
          
print(ret)