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
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
import numpy as np
from heapq import heappop, heappush
 
H,W = map(int,readline().split())
grid = np.full((H+2,W+2),b'#',dtype='S1')
grid[1:-1,1:-1] = np.frombuffer(read(),'S1').reshape(H,-1)[:,:W]
INF = 400
def shortest(grid, start, cost=0):
    dist = np.array([[INF for _ in range(W+2)] for _ in range(H+2)])
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    st = [(cost, start)]
    dist[start[0]][start[1]]=0
    while(st):
        c, [sx, sy] = heappop(st)
        for a, b in zip(dx, dy):
            x = sx + a
            y = sy + b
            if grid[x][y]==b'#':
              continue
            dxy = dist[sx][sy] + 1
            if dist[x][y] <= dxy:
                continue
            dist[x][y] = dxy
            heappush(st, (dist[x][y], [x, y]))
    return dist

m=0
for i in range(1,H+1):
  for j in range(1,W+1):
    print(i,j)
    if grid[i,j]==b'#':
      continue
    res=shortest(grid, [3,1], cost=0)[1:-1,1:-1]
    res[res==400]=0
    tm=np.max(res)
    if m < tm:
      m=tm
print(m)

Submission status: Runtime Error

Solution code:
from collections import deque

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

def solve(s):
    offset = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    visited = [[-1] * W for _ in range(H)]
    visited[0][0] = 0
    
    if s[0] == W or s[1] == H or S[1][0] == "#":
        return visited

    visited[s[1]][s[0]] = 1
    
    q = deque()
    q.append(s)

    while q:
        x, y = q.popleft()

        for u, v in offset:
            if not (0 <= x + u < W) or not (0 <= y + v < H):
                continue

            if visited[y + v][x + u] > -1 or S[y + v][x + u] == "#":
                continue

            visited[y + v][x + u] = visited[y][x] + 1
            q.append((x + u, y + v))
            
    return visited

ans_1 = (0, 0, 0)
for y, v in enumerate(solve((0, 1))):
    for x, c in enumerate(v):
        if c >= ans_1[2]:
            ans_1 = (x, y, c)
        
ans_2 = (0, 0, 0)
for y, v in enumerate(solve((1, 0))):
    for x, c in enumerate(v):
        if c >= ans_2[2]:
            ans_2 = (x, y, c)
        
if ans_1[0] == ans_2[0] and ans_1[1] == ans_2[1]:
    print(min(ans_1[2], ans_2[2]))
else:
    print(ans_1[2] + ans_2[2])

Submission status: Runtime Error

Solution code:
from collections import deque

def bfs():
    cnt = 0
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    while len(Q) > 0:
        q = Q.popleft()
        y,x =  q[0], q[1]
        if cnt >= H*W:
            for i in range(H):
                ans.append(max(box[i]))
            return
        for i in range(4):
            ny = y+dy[i]
            nx = x+dx[i]
            if ny >= 0 and ny < H and nx >= 0 and nx < W and S[ny][nx] == "#" and box[ny][nx] == 0:
                cnt += 1
                box[ny][nx] = -1
            if ny >= 0 and ny < H and nx >= 0 and nx < W and S[ny][nx] == "." and box[ny][nx] == 0:
                cnt += 1
                box[ny][nx] = box[y][x] + 1
                Q.append([ny,nx])


H,W = map(int,input().split())
S = [ []for _ in range(H)]
for i in range(H):
    S[i] = list(input())
ans = []
INF = 50**2
Q = deque()
#queueにスタート地点を追加
for i in range(H):
    for j in range(W):
        #各マス目に到達するために必要な移動回数
        box = [[0 for _ in range(W)] for __ in range(H)]
        box[i][j] = 0
        Q.append([i,j])
        bfs()
print(max(ans))

Submission status: Runtime Error

Solution code:
from collections import deque
H,W = map(int,input().split())
#A = list(map(int,input().split()))
S = []

def bfs(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        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-1 and 0<= new_x<=W-1:
                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])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    for i in range(H):
        if maxa in visited[i]:
            ret = [i,visited[i].index(maxa)]
            break
    return ret
def bfs2(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        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-1 and 0<= new_x<=W-1:
                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])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    return maxa
    

for i in range(H):
    s = list(input())
    S.append(s)
for i in range(H):
    if '.' in s:
        start = [i,S[i].index('.')]
        break
ret = bfs(S,start[0],start[1])
ans = bfs2(S,ret[0],ret[1])
print(ans)

Submission status: Runtime Error

Solution code:
import networkx as nx

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

G = nx.Graph()
for i in range(len(S)):
    for j in range(len(S[i])):
        if S[i][j] == '.':
            G.add_node((i,j))

for i in list(G.nodes):
    if G.has_node((i[0],i[1]+1)):
        G.add_edge(i, (i[0], i[1]+1))
    if G.has_node((i[0]+1,i[1])):
        G.add_edge(i, (i[0]+1, i[1]))

maxpath = 0
nodes = list(G.nodes)
for i in range(len(nodes)-1):
    for j in range(i+1, len(nodes)):
        l = len(nx.shortest_path(G, source=nodes[i], target=nodes[j]))
        maxpath = max(l, maxpath)

print(maxpath - 1)

Submission status: Runtime Error

Solution code:
from collections import deque
INF = 10 ** 9

class Edge:
	def __init__(self, t, w):
		self.t = t
		self.w = w

def around(i, j, H, W):
	if i == 0:
		if j == 0:
			ans = [(i, j+1), (i+1, j)]
		elif j == W-1:
			ans = [(i, j-1), (i+1, j)]
		else:
			ans = [(i, j-1), (i, j+1), (i+1, j)]
	elif i == H - 1:
		if j == 0:
			ans = [(i-1, j), (i, j+1)]
		elif j == W-1:
			ans = [(i-1, j), (i, j-1)]
		else:
			ans = [(i-1, j), (i, j-1), (i, j+1)]
	else:
		if j == 0:
			ans = [(i-1, j), (i, j+1), (i+1, j)]
		elif j == W-1:
			ans = [(i-1, j), (i, j-1), (i+1, j)]
		else:
			ans = [(i-1, j), (i, j-1), (i, j+1), (i+1, j)]
	return ans

def bfs(s):
	d = [INF for _ in range(H*W)]
	Q = deque()
	Q.append(s)
	d[s] = 0
	while len(Q) > 0:
		u = Q.popleft()
		for e in G[u]:
			if d[e.t] == INF:
				d[e.t] = d[u] + e.w
				Q.append(e.t)
	return d

def solve(s):
	d = bfs(s)
	maxv = 0
	tgt = 0
	for i in range(W*H):
		if d[i] == INF:
			continue
		if maxv < d[i]:
			maxv = d[i]
			tgt = i
	d = bfs(tgt)
	maxv = 0
	for i in range(W*H):
		if d[i] == INF:
			continue
		maxv = max(maxv, d[i])
	return maxv

if __name__ == "__main__":
	H, W = map(int, input().split())
	S = [[0 for j in range(W)] for i in range(H)]
	# print(S)
	for i in range(H):
		s = input()
		for j in range(W):
			if s[j] == "#":
				S[i][j] = 1
	# print(S)
	G = [[] for _ in range(H*W)]
	for i in range(H):
		for j in range(W):
			if S[i][j] != 1:
				for (k, l) in around(i, j, H, W):
					if S[k][l] != 1:
						G[i*W + j].append(Edge(k*W + l, 1))
						G[k*W + l].append(Edge(i*W + j, 1))

	ans = 0
	for i in range(H):
		for j in range(W):
			if S[i][j] != 1:
				v = solve(i*W + j)
				ans = max(ans, v)
	print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque

def a():
    H,W = map(int,input().split())
    S = ["" for _ in range(H)]
    for _ in range(H):
        S[_] = input()
    b = lambda n:S[n//W][n%W]
    u = (lambda n:(n%W,n//W))(min(range(H*W),key=b))

    def bfs(root):
        depth = [[-1]*W for _ in range(H)]
        q = deque()
        q.append((root,0))
        while q:
            r,d = q.popleft()
            x,y = r
            depth[y][x] = d
            for dx,dy in ((1,0),(-1,0),(0,1),(0,-1)):
                dx += x
                dy += y
                if 0 <= dx < W and 0 <= dy < H and depth[dy][dx] == -1 and S[dy][dx] == ".":
                    q.append(((dx,dy),d+1))
        return depth

    c = bfs(u)
    d = lambda n:c[n//W][n%W]
    v = (lambda n:(n%W,n//W))(max(range(H*W),key=d))

    e = bfs(v)
    f = lambda n:e[n//W][n%W]
    print(f(max(range(H,W),key=f)))



a()

Submission status: Runtime Error

Solution code:
from collections import deque
INF = 10 ** 9

class Edge:
	def __init__(self, t, w):
		self.t = t
		self.w = w

def around(i, j, H, W):
	if i == 0:
		if j == 0:
			ans = [(i, j+1), (i+1, j)]
		elif j == W-1:
			ans = [(i, j-1), (i+1, j)]
		else:
			ans = [(i, j-1), (i, j+1), (i+1, j)]
	elif i == H - 1:
		if j == 0:
			ans = [(i-1, j), (i, j+1)]
		elif j == W-1:
			ans = [(i-1, j), (i, j-1)]
		else:
			ans = [(i-1, j), (i, j-1), (i, j+1)]
	else:
		if j == 0:
			ans = [(i-1, j), (i, j+1), (i+1, j)]
		elif j == W-1:
			ans = [(i-1, j), (i, j-1), (i+1, j)]
		else:
			ans = [(i-1, j), (i, j-1), (i, j+1), (i+1, j)]
	return ans

def bfs(s):
	d = [INF for _ in range(H*W)]
	Q = deque()
	Q.append(s)
	d[s] = 0
	while len(Q) > 0:
		u = Q.popleft()
		for e in G[u]:
			if d[e.t] == INF:
				d[e.t] = d[u] + e.w
				Q.append(e.t)
	return d

def solve(s):
	d = bfs(s)
	maxv = 0
	tgt = 0
	for i in range(W*H):
		if d[i] == INF:
			continue
		if maxv < d[i]:
			maxv = d[i]
			tgt = i
	d = bfs(tgt)
	maxv = 0
	for i in range(W*H):
		if d[i] == INF:
			continue
		maxv = max(maxv, d[i])
	return maxv

if __name__ == "__main__":
	H, W = map(int, input().split())
	S = [[0 for j in range(W)] for i in range(H)]
	print(S)
	for i in range(H):
		s = input()
		for j in range(W):
			if s[j] == "#":
				S[i][j] = 1
	# print(S)
	G = [[] for _ in range(H*W)]
	for i in range(H):
		for j in range(W):
			if S[i][j] != 1:
				for (k, l) in around(i, j, H, W):
					if S[k][l] != 1:
						G[i*W + j].append(Edge(k*W + l, 1))
						G[k*W + l].append(Edge(i*W + j, 1))

	ans = 0
	for i in range(H):
		for j in range(W):
			if S[i][j] != 1:
				v = solve(i*W + j)
				ans = max(ans, v)
	print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**6)

def main():
    H,W = map(int, input().split())

    S = ["" for _ in range(H)]
    for i in range(H):
        S[i] = input()

    INF = float("inf")
    dp = [[INF for _ in range(H*W)] for _ in range(H*W)]

    for i in range(H):
        for j in range(W):
            
            if j != W-1 and S[i][j] == "." and S[i][j+1] == ".":
                dp[(H*i)+j][(H*i)+j+1] = 1
                dp[(H*i)+j+1][(H*i)+j] = 1

            if i != H-1 and S[i][j] == "." and S[i+1][j] == ".":
                dp[(H*i)+j][(H*(i+1))+j] = 1
                dp[(H*(i+1))+j][(H*i)+j] = 1
        
            dp[(H*i)+j][(H*i)+j] = 0


    N = H*W
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

    ans = 0
    for i in range(N):
        for j in range(N):
            if dp[i][j] != INF:
                ans = max(ans, dp[i][j])
    
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
h, w = map(int,input().split())
grid = []
grid.append('#' * (w+2))
for _ in range(h):
    grid.append('#' + input().rstrip() + '#')
grid.append('#' * (w+2))
            
from collections import deque
import sys
sys.setrecursionlimit(1000000)


def flatten_2dim(array):
    return [item for sublist in array for item in sublist]
def all_argmax_2dim(array):
    flat_array = flatten_2dim(array)

    row_num = len(array)
    max_value = max(flat_array)

    for i, elem in enumerate(flat_array):
        if elem == max_value:
            yield i // row_num, i % row_num

maxstep = 0
flag = 0
step = [[-1] * (w+2) for _ in range(h+2)]
def bfs():
    global maxstep

    dy = [1, 0, -1, 0]
    dx = [0, 1, 0, -1]
    
    que = deque([])
    que.append((s_y, s_x))
    step[s_y][s_x] = 0
    
    while que:
        y, x = que.popleft()

        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if step[ny][nx] == -1 and grid[ny][nx] != "#":
                que.append((ny, nx))
                step[ny][nx] = step[y][x] + 1
    if flag == 0:
        maxstep = max(flatten_2dim(step))
    else:
        maxstep = max(max(flatten_2dim(step)), maxstep)
    
for i in range(h+2):
    for j in range(w+2):
        if grid[i][j] == ".":
            s_y, s_x = i, j
            break
bfs()
flag = 1
li = []
for argmax in all_argmax_2dim(step):
    li.append(argmax)

for s_y, s_x in li:
    bfs()
for argmax in all_argmax_2dim(step):
    li.append(argmax)
for s_y, s_x in li:
    bfs()   
print(maxstep)

Submission status: Runtime Error

Solution code:
def main():
    import networkx as nx
    import numpy as np
    h,w = map(int, input().split())
    s = [list(input()) for i in range(h)]
    dic = {'.':0, '#':1}
    g = [[dic[i] for i in _s] for _s in s]
    graph = nx.grid_graph(dim=[h, w])
    rm_node = np.array(g)

    for (u, _) in graph.nodes(data=True):
        if rm_node[u]:
            graph.remove_node(u)
    #後はダイクストラ法で解くだけ
    ans1 = nx.dijkstra_path(graph, (0, 0), (h-1, w-1))
    ans2 = nx.dijkstra_path(graph, (h-1, 0), (0, w-1))
#    ans3 = nx.dijkstra_path(graph, (0, w-1), (h-1, 0))
#    ans4 = nx.dijkstra_path(graph, (h-1, w-1), (0, 0))
    print(max(len(ans1),len(ans2))-1)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
h, w = map(int,input().split())
grid = []
grid.append('#' * (w+2))
for _ in range(h):
    grid.append('#' + input().rstrip() + '#')
grid.append('#' * (w+2))
            
from collections import deque
import sys
sys.setrecursionlimit(1000000)


def flatten_2dim(array):
    return [item for sublist in array for item in sublist]
def all_argmax_2dim(array):
    flat_array = flatten_2dim(array)

    row_num = len(array)
    max_value = max(flat_array)

    for i, elem in enumerate(flat_array):
        if elem == max_value:
            yield i // row_num, i % row_num

maxstep = 0
flag = 0
step = [[-1] * (w+2) for _ in range(h+2)]
def bfs():
    global maxstep

    dy = [1, 0, -1, 0]
    dx = [0, 1, 0, -1]
    
    que = deque([])
    que.append((s_y, s_x))
    step[s_y][s_x] = 0
    
    while que:
        y, x = que.popleft()

        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if step[ny][nx] == -1 and grid[ny][nx] != "#":
                que.append((ny, nx))
                step[ny][nx] = step[y][x] + 1
    if flag == 0:
        maxstep = max(flatten_2dim(step))
    else:
        maxstep = max(max(flatten_2dim(step)), maxstep)
    
for i in range(h+2):
    for j in range(w+2):
        if grid[i][j] == ".":
            s_y, s_x = i, j
            break
bfs()
flag = 1
li = []
for argmax in all_argmax_2dim(step):
    li.append(argmax)

for s_y, s_x in li:
    bfs()
print(maxstep)

Submission status: Runtime Error

Solution code:
#幅優先探索


from queue import Queue

ans = 0
h,w = map(int, input().split())
maps = [input() for _ in range(h)]
for i in range(1):
    for j in range(1,2):
        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)

Submission status: Runtime Error

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
# print(S)
INF = 10**9

V = H*W
d = [[INF for _ in range(V)] for _ in range(V)]
for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            v = i*H + j
            d[v][v] = 0
            if i != 0 and S[i-1][j] == '.':
                x = (i-1)*H + j
                d[v][x] = 1
                d[x][v] = 1
            if i != H-1 and S[i+1][j] == '.':
                x = (i+1)*H + j
                d[v][x] = 1
                d[x][v] = 1
            if j != 0 and S[i][j-1] == '.':
                x = i*H + j-1
                d[v][x] = 1
                d[x][v] = 1
            if j != W-1 and S[i][j+1] == '.':
                x = i*H + j+1
                d[v][x] = 1
                d[x][v] = 1

def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    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

d = warshall_floyd(d)
# print(d)
ans = 0
for i in range(V):
    for j in range(V):
        if d[i][j] != INF:
            ans = max(ans, d[i][j])

print(ans)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
from collections import defaultdict

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

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

def bfs(start):
    Visit={}
    q=deque()
    q.append(start)
    Visit[start]=1
    L=defaultdict(lambda: 0)    #距離

    while q:
        fro_x,fro_y=q.popleft()
        for dx,dy in D:
            to_x=fro_x+dx
            to_y=fro_y+dy
            if 0<=to_x<H and 0<=to_y<W:
                if S[to_x][to_y]=="." and (to_x,to_y) not in Visit:
                    Visit[to_x,to_y]=1
                    L[(to_x,to_y)]=L[(fro_x,fro_y)]+1
                    q.append((to_x,to_y))

    return max(L.values())

ans=0
for h in range(H):
    for w in range(W):
        ans=max(ans,bfs((h,w)))

print ans

Submission status: Runtime Error

Solution code:
from collections import deque
#import numpy as np

h,w=map(int,input().split())
#sy,sx=map(int,input().split())
#sy=sy-1
#sx=sx-1
#gy,gx=map(int,input().split())
#gy=gy-1
#gx=gx-1
maze=[list("#"*(w+2))]+[list("#"+input()+"#") for i in range(h)]+[list("#"*(w+2))]
INF=10800 #>50*50
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):#,gy,gx):
  queue=deque([[sy,sx]])
  visited[sy][sx]=0
  while queue:
    [y,x]=queue.popleft()
    #if (y,x)==(gy,gx):
    #  return visited[gy][gx]
    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:
  bfs(maze,visited,3,1)
  for i in range(1,h+1):
    for j in range(1,w+1):
      ans=max(ans,visited[i][j])

    
    
print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
H,W = map(int,input().split())
#A = list(map(int,input().split()))
S = []

def bfs(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        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-1 and 0<= new_x<=W-1:
                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])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    for i in range(H):
        if maxa in visited[i]:
            ret = [i,visited[i].index(maxa)]
            break
    return ret
def bfs2(maze,sy, sx):
    visited = [[-1 for i in range(W)] for j in range(H)]
    queue = deque([[sy, sx]])
    visited[sy][sx] = 0
    while queue:
        y, x = queue.popleft()
        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-1 and 0<= new_x<=W-1:
                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])
    maxa = 0
    for i in range(H):
        maxa = max(maxa,max(visited[i]))
    return maxa
    

for i in range(H):
    s = list(input())
    S.append(s)
for i in range(H):
    if '.' in s:
        start = [i,s.index('.')]
        break

ret = bfs(S,start[0],start[1])

ans = bfs2(S,ret[0],ret[1])
print(ans)

Submission status: Runtime Error

Solution code:
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] == "#":
            break
        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 or grid[next_h][next_w] == "#":
                        continue
                    else:
                        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))

Submission status: Runtime Error

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

V = H*W
d = [[float("inf") for _ in range(V)] for _ in range(V)]
for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            v = i*H + j
            d[v][v] = 0
            if i != 0 and S[i-1][j] == '.':
                x = (i-1)*H + j
                d[v][x] = 1
                d[x][v] = 1
            if i != H-1 and S[i+1][j] == '.':
                x = (i+1)*H + j
                d[v][x] = 1
                d[x][v] = 1
            if j != 0 and S[i][j-1] == '.':
                x = i*H + j-1
                d[v][x] = 1
                d[x][v] = 1
            if j != W-1 and S[i][j+1] == '.':
                x = i*H + j+1
                d[v][x] = 1
                d[x][v] = 1

def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    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

d = warshall_floyd(d)
# print(d)
ans = 0
for i in range(V):
    for j in range(V):
        if d[i][j] != float("inf"):
            ans = max(ans, d[i][j])

print(ans)

Submission status: Runtime Error

Solution code:
def main():
    H,W = map(int, input().split())

    S = ["" for _ in range(H)]
    for i in range(H):
        S[i] = input()

    INF = float("inf")
    dp = [[INF for _ in range(H*W)] for _ in range(H*W)]

    for i in range(H):
        for j in range(W):
            
            if j != W-1 and S[i][j] == "." and S[i][j+1] == ".":
                dp[(H*i)+j][(H*i)+j+1] = 1
                dp[(H*i)+j+1][(H*i)+j] = 1

            if i != H-1 and S[i][j] == "." and S[i+1][j] == ".":
                dp[(H*i)+j][(H*(i+1))+j] = 1
                dp[(H*(i+1))+j][(H*i)+j] = 1
        
            dp[(H*i)+j][(H*i)+j] = 0


    N = H*W
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j])

    ans = 0
    for i in range(N):
        for j in range(N):
            if dp[i][j] != INF:
                ans = max(ans, dp[i][j])
    
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from collections import deque

H, W = map(int, input().split())
# sx, sy = map(int, input().split())
# gx, gy = map(int, input().split())
# sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1
c = [input() for i in range(H)]

dist = [[float('inf') for i in range(W)] for j in range(H)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs():
    q = deque()
    q.append([sx, sy])
    dist[sx][sy] = 0
    while q:
        p = q.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx and nx < H and 0 <= ny and ny < W:
                if c[nx][ny] != '#' and dist[nx][ny] == float('inf'):
                    q.append([nx, ny])
                    dist[nx][ny] = dist[p[0]][p[1]] + 1
    return dist[gx][gy]

sx, sy, gx, gy = 2, 0, 0, 4
print(bfs())
ans = []
for i in range(H):
    for j in range(W):
        sx, sy = i, j
        for k in range(H):
            for l in range(W):
                gx, gy = k, l
                ans.append(bfs())

# print(ans)
ans = [i for i in ans if i != float('inf')]
print(max(ans))

Submission status: Runtime Error

Solution code:
from collections import deque
import copy
import sys
sys.setrecursionlimit(410000)

INF = 10**6

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

def solve(sy,sx):
  d = [[INF]*w for _ in range(h)]
  que = deque()
  que.append([sx,sy])
  d[sy][sx]=0

  while len(que)>0:
    px,py = que.popleft()

    for dx,dy in ((-1,0),(0,1),(1,0),(0,-1)):
      nx = px + dx
      ny = py + dy

      if (0 <= nx and nx < w and 0<=ny and ny < h) \
          and maze[ny][nx] != '#' \
          and (d[ny][nx] == INF or d[ny][nx] > d[py][px] +1):              
        que.append((nx,ny))
        d[ny][nx] = d[py][px] +1

  return d


maze = copy.deepcopy(org_maze)
f = solve(0,0)

d79 = f[0][w-1]
d71 = f[2][0]
d73 = f[h-1][w-1]

maze = copy.deepcopy(org_maze)
f = solve(0,w-1)
d91 = f[h-1][0]
d93 = f[h-1][w-1]

maze = copy.deepcopy(org_maze)
f = solve(h-1,0)
d13 = f[h-1][w-1]

print(max(d79,d71,d73,d91,d93,d13))

Submission status: Runtime Error

Solution code:
from collections import deque

H, W = map(int, input().split())
S = [0]*H
for i in range(H):
    S[i] = input()
# print(H, W, S)


def is_inside(w, h, W, H):
    if w >= 0 and w < W and h >= 0 and h < H:
        return True
    return False

def solve(sh, sw):
    T = [[0]* W for h in range(H)]
    for i in range(H):
        for j in range(W):
            if S[i][j] == '#':
                T[i][j] = -1
    V = deque([(sh, sw)])
    T[sh][sw] = -2
    while len(V) != 0:
        v = V.popleft()
        h = v[0]
        w = v[1]
        # print(h, w)
        t = T[h][w]
        if t == -2:
            t = 0
        if is_inside(h - 1, w, H, W):
            if T[h - 1][w] == 0:
                T[h - 1][w] = t + 1
                V.append((h - 1, w))
        if is_inside(h + 1, w, H, W):
            if T[h + 1][w] == 0:
                T[h + 1][w] = t + 1
                V.append((h + 1, w))
        if is_inside(h, w - 1, H, W):
            if T[h][w - 1] == 0:
                T[h][w - 1] = t + 1
                V.append((h , w - 1))
        if is_inside(h, w + 1, H, W):
            if T[h][w + 1] == 0:
                T[h][w + 1] = t + 1
                V.append((h , w + 1))
    # print(sh, sw, T)
    return T


ans = 0

for h in range(H):
    for w in range(W):
        T = solve(h, w)
        distance = 0
        for i in range(H):
            for j in range(H):
                d = T[i][j]
                distance = max(distance, d)
        ans = max(distance, ans)

print(ans)

Submission status: Runtime Error

Solution code:
from collections import deque
import copy
INF = 10**6

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

def solve(sy,sx):
  d = [[INF]*w for _ in range(h)]
  que = deque()
  que.append([sx,sy])
  d[sy][sx]=0

  while len(que)>0:
    px,py = que.popleft()

    for dx,dy in ((-1,0),(0,1),(1,0),(0,-1)):
      nx = px + dx
      ny = py + dy

      if (0 <= nx and nx < w and 0<=ny and ny < h) \
          and maze[ny][nx] != '#' \
          and (d[ny][nx] == INF or d[ny][nx] > d[py][px] +1):              
        que.append((nx,ny))
        d[ny][nx] = d[py][px] +1

  return d


maze = copy.deepcopy(org_maze)
f = solve(0,0)

d79 = f[0][w-1]
d71 = f[2][0]
d73 = f[h-1][w-1]

maze = copy.deepcopy(org_maze)
f = solve(0,w-1)
d91 = f[h-1][0]
d93 = f[h-1][w-1]

maze = copy.deepcopy(org_maze)
f = solve(h-1,0)
d13 = f[h-1][w-1]

print(max(d79,d71,d73,d91,d93,d13))

Submission status: Runtime Error

Solution code:
from collections import deque

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

def solve(s):
    bias = [(1, 0), (-1, 0), (0, 1), (0, -1)]

    visited = [[-1] * W for _ in range(H)]
    visited[0][0] = 0
    
    if visited[s[1]][s[0]] == "#":
        return visited

    q = deque()
    q.append(s)  # x, y, c

    while q:
        x, y, c = q.popleft()
        visited[y][x] = c

        for u, v in bias:
            if not (0 <= x + u < W) or not (0 <= y + v < H):
                continue

            if visited[y + v][x + u] > -1 or S[y + v][x + u] == "#":
                continue

            q.append((x + u, y + v, c + 1))
            
    return visited

ans_1 = (0, 0, 0)
for y, v in enumerate(solve((0, 1, 1))):
    for x, c in enumerate(v):
        if c >= ans_1[2]:
            ans_1 = (x, y, c)
        
ans_2 = (0, 0, 0)
for y, v in enumerate(solve((1, 0, 1))):
    for x, c in enumerate(v):
        if c >= ans_2[2]:
            ans_2 = (x, y, c)
        
if ans_1[0] == ans_2[0] and ans_1[1] == ans_2[1]:
    print(min(ans_1[2], ans_2[2]))
else:
    print(ans_1[2] + ans_2[2])