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: Time Limit Exceeded

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


def dfs(y, x):
    dist = [[-1]*w for _ in range(h)]
    if meiro[y][x] == '#':
        return 0
    dist[y][x] = 0

    pattern = [[-1, 0], [1, 0], [0, -1], [0, 1]]
    todo = []
    for dy, dx in pattern:
        ny, nx = y + dy, x + dx
        if 0 <= ny <= h-1 and 0 <= nx <= w-1:
            todo.append([ny, nx, 1])

    while todo:
        y, x, d = todo.pop()
        if meiro[y][x] == '#':
            continue
        if dist[y][x] != -1:
            if dist[y][x] <= d:
                continue

        dist[y][x] = d
        for dy, dx in pattern:
            ny, nx = y + dy, x + dx
            if 0 <= ny <= h - 1 and 0 <= nx <= w - 1:
                todo.append([ny, nx, d+1])

    res = 0
    for line in dist:
        res = max(max(line), res)

    return res


ans = []
for y in range(h):
    for x in range(w):
        ans.append(dfs(y, x))

print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
M = [[-1]*(W+2) for _ in range(H+2)]
X = []
for h in range(H):
    for w, c in enumerate(input()):
        if c=='.':
            M[h+1][w+1] = 0
            X.append((h+1, w+1))

mark = 0
ans = 0
for ist, st in enumerate(X):
    for gl in X[ist+1:]:
        mark += 1
        turn = 0
        f = False
        queue = [st]
        while queue and not f:
            queue_new = []
            for qx, qy in queue:
                if (qx, qy)==gl:
                    f = True
                    break
                    
                for dx, dy in ((+1,0),(-1,0),(0,+1),(0,-1)):
                    x = qx+dx
                    y = qy+dy
                    m = M[x][y] 
                    if m!=-1 and m!=mark:
                        M[x][y] = mark
                        queue_new.append((x,y))
                    
            queue = queue_new
            turn += 1

        ans = max(ans, turn-1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


# (sx, sy) から (gx, gy) への最短距離を求める
# 辿り着けないと INF
def bfs():
    # すべての点を INF で初期化
    #d = [[10 ** 12] * w for i in range(h)]
    d = []
    for i in range(h):
        d.append([10 ** 12] * w)

    # 移動4方向のベクトル
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    # スタート地点をキューに入れ、その点の距離を0にする
    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    # キューが空になるまでループ
    while que:
        # キューの先頭を取り出す
        p = que.popleft()
        # 取り出してきた状態がゴールなら探索をやめる
        if p[0] == gx and p[1] == gy:
            break
        # 移動4方向をループ
        for i in range(4):
            # 移動した後の点を (nx, ny) とする
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            # 移動が可能かの判定とすでに訪れたことがあるかの判定
            # d[nx][ny] != INF なら訪れたことがある
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == 10 ** 12:
                # 移動できるならキューに入れ、その点の距離を p からの距離 +1 で確定する
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


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

ans = 0
for sx in range(h):
    for sy in range(w):
        if maze[sx][sy] == ".":
            for gx in range(h):
                for gy in range(w):
                    if maze[gx][gy] == ".":
                        ans = max(ans, bfs())

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

INF = -1

sizeI, sizeJ = map(int, input().split())
a = [input().rstrip() for _ in range(sizeI)]

def bfs(startI, startJ, targetI, targetJ):
    dist = [[INF for _ in range(sizeJ)] for _ in range(sizeI)]
    dist[startI][startJ] = 0
    q = deque([(startI, startJ)])
    while q:
        i, j = q.pop()
        curDist = dist[i][j]
        if (i, j) == (targetI, targetJ):
            return curDist
        for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            ni, nj = i + di, j + dj
            if 0 <= ni < sizeI and 0 <= nj < sizeJ and dist[ni][nj] == INF and a[ni][nj] == '.':
                dist[ni][nj] = 1 + curDist
                q.appendleft((ni, nj))
    raise Exception

points = []
for i in range(sizeI):
    for j in range(sizeJ):
        if a[i][j] == '.':
            points.append((i, j))
ret = 0
for i in range(len(points) - 1):
    for j in range(i + 1, len(points)):
        ret = max(ret, bfs(points[i][0], points[i][1], points[j][0], points[j][1]))
print(ret)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import deque


def main():
    H, W = [int(x) for x in input().split()]
    A = [["" for i in range(W)] for j in range(H)]

    for j in range(H):
        S = input().strip()
        for i, s in enumerate(list(S)):
            A[j][i] = s


    ma = 0

    dj = [1, 0, -1, 0]
    di = [0, 1, 0, -1]

    for sj in range(H):
        for si in range(W):
            for gj in range(H):
                for gi in range(W):
                    d = [[-1] * W for i in range(H)]
                    q = deque([])
                    q.append((sj, si))
                    d[sj][si] = 0

                    while q:
                        p = q.popleft()
                        if p[0] == gj and p[1] == gi:
                            break
                        for i in range(4):
                            nj = p[0] + dj[i]
                            ni = p[1] + di[i]

                            if 0 <= nj < H and 0 <= ni < W and A[nj][ni] != "#" and d[nj][ni] == -1:
                                q.append((nj, ni))
                                d[nj][ni] = d[p[0]][p[1]] + 1

                    ma = max(ma, d[gj][gi])



    print(ma)





    


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#ライブラリインポート
from collections import defaultdict
import queue

#入力受け取り
def getlist():
	return list(map(int, input().split()))

INF = float("inf")

def BFS(H, W, L, start):
	dist = [[INF for i in range(W)] for j in range(H)]
	sy, sx = start
	dist[sy][sx] = 0
	Q = queue.Queue()
	Q.put([sy, sx])
	while not Q.empty():
		y, x = Q.get()
		if y - 1 >= 0:
			if L[y - 1][x] == "." and dist[y - 1][x] > dist[y][x] + 1:
				dist[y - 1][x] = dist[y][x] + 1
				Q.put([y - 1, x])
		if y + 1 <= H - 1:
			if L[y + 1][x] == "." and dist[y + 1][x] > dist[y][x] + 1:
				dist[y + 1][x] = dist[y][x] + 1
				Q.put([y + 1, x])
		if x - 1 >= 0:
			if L[y][x - 1] == "." and dist[y][x - 1] > dist[y][x] + 1:
				dist[y][x - 1] = dist[y][x] + 1
				Q.put([y, x - 1])
		if x + 1 <= W - 1:
			if L[y][x + 1] == "." and dist[y][x + 1] > dist[y][x] + 1:
				dist[y][x + 1] = dist[y][x] + 1
				Q.put([y, x + 1])

	return dist

#処理内容
def main():
	H, W = getlist()
	L = []
	for i in range(H):
		l = list(input())
		L.append(l)
	SG = []
	for i in range(H):
		for j in range(W):
			if L[i][j] == ".":
				SG.append([i, j])

	N = len(SG)
	ans = 0
	for i in range(N):
		for j in range(i + 1, N):
			start = [SG[i][0] , SG[i][1]]
			goal = [SG[j][0] , SG[j][1]]
			BF = BFS(H, W, L, start)
			val = BF[goal[0]][goal[1]]
			ans = max(ans, val)
	print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

INF = 10000

H, W = map(int, input().split())
Sss = ['#'*(W+2)] + ['#'+input()+'#' for _ in range(H)] + ['#'*(W+2)]

poss = []
for i in range(1, H+1):
    for j in range(1, W+1):
        if Sss[i][j] == '.':
            poss.append((i, j))

def bfsGridGraph(Sss, xSt, ySt, xEn, yEn, INF):
    dxys = [(-1,0), (1,0), (0,-1), (0,1)]
    distss = [[(INF if S != '#' else -1) for S in Ss] for Ss in Sss]
    distss[xSt][ySt] = 0
    Q = deque([(xSt, ySt)])
    while Q:
        x, y = Q.popleft()
        if (x, y) == (xEn, yEn): break
        dist = distss[x][y]
        for dx, dy in dxys:
            x2, y2 = x+dx, y+dy
            if distss[x2][y2] == INF:
                distss[x2][y2] = dist + 1
                Q.append((x2, y2))
    return distss

N = len(poss)
ans = 0
for i in range(N):
    xSt, ySt = poss[i]
    for j in range(i+1, N):
        xEn, yEn = poss[j]
        distss = bfsGridGraph(Sss, xSt, ySt, xEn, yEn, INF)
        dist = distss[xEn][yEn]
        ans = max(ans, dist)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import *
INF = 500000
mod = 10**9+7

H, W = map(int, input().split())
f = [input() for i in range(H)]
es = defaultdict(lambda : INF)
for i in range(H):
    for j in range(W-1):
        if f[i][j] == '.' and f[i][j+1] == '.':
            es[((i, j), (i, j+1))] = 1
            es[((i, j+1), (i, j))] = 1
for i in range(H-1):
    for j in range(W):
        if f[i][j] == '.' and f[i+1][j] == '.':
            es[((i, j), (i+1, j))] = 1
            es[((i+1, j), (i, j))] = 1
V = []
for i in range(H):
    for j in range(W):
        if f[i][j] == '.':
            es[((i, j), (i, j))] = 0
            V.append((i, j))
for k in V:
    for i in V:
        for j in V:
            tmp = es[(i, k)] + es[(k, j)]
            if tmp < es[(i, j)]:
                es[(i, j)] = tmp
ans = 0
for i in V:
    for j in V:
        if ans < es[(i, j)]:
            ans = es[(i, j)]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

INF = 10000

H, W = map(int, input().split())
Sss = ['#'*(W+2)] + ['#'+input()+'#' for _ in range(H)] + ['#'*(W+2)]

poss = []
for i in range(1, H+1):
    for j in range(1, W+1):
        if Sss[i][j] == '.':
            poss.append((i, j))

def bfsGridGraph(Sss, xSt, ySt, xEn, yEn, INF):
    dxys = [(-1,0), (1,0), (0,-1), (0,1)]
    distss = [[(INF if S != '#' else -1) for S in Ss] for Ss in Sss]
    distss[xSt][ySt] = 0
    Q = deque([(xSt, ySt)])
    while Q:
        x, y = Q.popleft()
        dist = distss[x][y]
        for dx, dy in dxys:
            x2, y2 = x+dx, y+dy
            if distss[x2][y2] == INF:
                distss[x2][y2] = dist + 1
                Q.append((x2, y2))
    return distss

N = len(poss)
ans = 0
for i in range(N):
    xSt, ySt = poss[i]
    for j in range(i+1, N):
        xEn, yEn = poss[j]
        distss = bfsGridGraph(Sss, xSt, ySt, xEn, yEn, INF)
        dist = distss[xEn][yEn]
        ans = max(ans, dist)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


# (sx, sy) から (gx, gy) への最短距離を求める
# 辿り着けないと INF
def bfs():
    # すべての点を INF で初期化
    d = [[float("inf")] * w for i in range(h)]

    # 移動4方向のベクトル
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]

    # スタート地点をキューに入れ、その点の距離を0にする
    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    # キューが空になるまでループ
    while que:
        # キューの先頭を取り出す
        p = que.popleft()
        # 取り出してきた状態がゴールなら探索をやめる
        if p[0] == gx and p[1] == gy:
            break
        # 移動4方向をループ
        for i in range(4):
            # 移動した後の点を (nx, ny) とする
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            # 移動が可能かの判定とすでに訪れたことがあるかの判定
            # d[nx][ny] != INF なら訪れたことがある
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                # 移動できるならキューに入れ、その点の距離を p からの距離 +1 で確定する
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


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

ans = 0
for sx in range(h):
    for sy in range(w):
        if maze[sx][sy] == ".":
            for gx in range(h):
                for gy in range(w):
                    if maze[gx][gy] == ".":
                        ans = max(ans, bfs())

print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, raw_input().split())
maze = [list(raw_input()) for i in xrange(h)]

INF = 10 ** 10
my = [-1, 0, 1, 0]
mx = [0, -1, 0, 1]
def bfs(sy, sx, ey, ex):
    q = [(sy, sx)]
    dp = [ [INF for j in xrange(w)] for i in xrange(h) ]
    dp[sy][sx] = 0
    while q:
        (y, x) = q.pop(0)
        if (y, x) == (ey, ex):
            break
        for (dy, dx) in zip(my, mx):
            ny = y + dy
            nx = x + dx
            if ny < 0 or nx < 0 or ny >= h or nx >= w:
                continue
            if maze[ny][nx] == '#':
                continue
            if dp[ny][nx] != INF:
                continue
            dp[ny][nx] = dp[y][x] + 1
            q.append((ny, nx))
    res = dp[ey][ex]
    assert res < INF
    return res

res = 0
for sy in xrange(h):
    for sx in xrange(w):
        if maze[sy][sx] == '#':
            continue
        for ey in xrange(h):
            for ex in xrange(w):
                if maze[ey][ex] == '#':
                    continue
                res = max(res, bfs(sy, sx, ey, ex))
print res

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
import sys
import bisect
import math
import itertools
import string
import queue
import copy
# import numpy as np
# import scipy
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
 
def inp(): # n=1
    return int(input())
def inpm(): # x=1,y=2
    return map(int,input().split())
def inpl(): # a=[1,2,3,4,5,...,n]
    return list(map(int, input().split()))
def inpls(): # a=['1','2','3',...,'n']
    return list(input().split())
def inplm(n): # x=[] 複数行
    return list(int(input()) for _ in range(n))
def inpll(n): # [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
    return [list(map(int, input().split())) for _ in range(n)]


def main():
    h,w = inpm()
    maze = []
    for _ in range(h):
        s = list(input())
        maze.append(s)
    ans = 0
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    for sx in range(h):
        for sy in range(w):
            if maze[sx][sy] == '#':
                continue
            else:
                for gx in range(h):
                    for gy in range(w):
                        if sx==gx and sy==gy:
                            continue
                        else:
                            d = [[-1 for _ in range(w)] for _ in range(h)]
                            que = []
                            d[sx][sy] = 0
                            que.append([sx,sy])
                            while que:
                                [qx,qy]=que[0]
                                if qx==gx and qy==gy:
                                    break
                                que.pop(0)
                                for i in range(4):
                                    nx=qx+dx[i]
                                    ny=qy+dy[i]
                                    if nx>=0 and h>nx and ny>=0 and w>ny and maze[nx][ny]=="." and d[nx][ny]==-1:
                                        d[nx][ny]=d[qx][qy]+1
                                        que.append([nx,ny])
                            ans = max(ans,d[gx][gy])
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs(sx, sy, gx, gy):
    dist = [[-1]*W for _ in range(H)]
    dist[sx][sy] = 0
    q = deque([(sx, sy)])
    
    while q:
        cx, cy = q.popleft()
        
        for nx, ny in [(cx-1, cy), (cx+1, cy), (cx, cy-1), (cx, cy+1)]:
            if not (0<=nx<H and 0<=ny<W):
                continue
            
            if S[nx][ny]=='.' and dist[nx][ny]==-1:
                dist[nx][ny] = dist[cx][cy]+1
                q.append((nx, ny))
    
    return dist[gx][gy]

H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]
ans = -10**18

for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                if S[i][j]!='#' and S[k][l]!='#':
                    ans = max(ans, bfs(i, j, k, l))

print(ans)

Submission status: Accepted

Solution code:
import heapq

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

ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue

        q = [(0, (i, j))]
        mins = [[h * w for _ in range(w)] for _ in range(h)]
        visited = [[0 for _ in range(w)] for _ in range(h)]
        while len(q) > 0:
            c, (x, y) = heapq.heappop(q)
            ans = max(ans, c)
            if visited[x][y]:
                continue
            visited[x][y] = True
            for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
                if nx < 0 or nx >= h or ny < 0 or ny >= w or s[nx][ny] == '#':
                    continue
                if visited[nx][ny]:
                    continue
                if mins[nx][ny] > c + 1:
                    mins[nx][ny] = c + 1
                    heapq.heappush(q, (c + 1, (nx, ny)))

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
def main():
    from collections import deque
    import numpy as np

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

    move = ((0, 1), (0, -1), (1, 0), (-1, 0))
    seen = [[False] * W for _ in range(H)]
    ans = 0
    for sh in range(H):
        for sw in range(W):
            if S[sh][sw] == '#' or seen[sh][sw]:
                continue
            seen[sh][sw] = True
            queue = deque([(sh, sw)])
            # distance = np.zeros((H, W), dtype=np.int16)
            distance = np.full((H, W), -1, dtype=np.int16)
            distance[sh, sw] = 0
            while queue:
                h, w = queue.popleft()
                for dh, dw in move:
                    nh = h + dh
                    nw = w + dw
                    if (1
                            and 0 <= nh < H
                            and 0 <= nw < W
                            and S[nh][nw] == '.'
                            and distance[nh][nw] == -1):
                        distance[nh][nw] = distance[h][w] + 1
                        queue.append((nh, nw))
            ans = max(ans, distance.max())
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int,input().split())
maze = [[i for i in input()] for _ in range(h)] # h * w
move = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def bfs(i, j):
  dist = [[-1] * w for _ in range(h)]
  d = deque()
  d.append((i, j))
  dist[i][j] = 0
  ret = 0
  while d:
    x, y = d.popleft()
    for m in move:
      i = x + m[0]
      j = y + m[1]
      if i >=0 and i < h and j >= 0 and j < w:
        if maze[i][j] == "#":
          continue
        if dist[i][j] != -1:
          continue
        dist[i][j] = dist[x][y] + 1
        d.append((i, j))
  for i in range(h):
    for j in range(w):
      if ret < dist[i][j]:
        ret = dist[i][j]
  return ret

ans = 0
for i in range(h):
  for j in range(w):
    if maze[i][j] == "#":
      continue
    d = bfs(i, j)
    if ans < d:
      ans = d

print(ans)

Submission status: Accepted

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

for i in range(h):
    for j in range(w):
        if C[i][j] == '.':
            startls.append([i,j])
            
dy_dx = [[1,0],[0,1],[-1,0],[0,-1]]
ans = 0
for start in startls:
    visited = [[-1 for i in range(w)] for i in range(h)]
    visited[start[0]][start[1]] = 0
    cost = 0
    queue = [start]
    while len(queue) > 0:
        now = queue.pop(0)
        cost = visited[now[0]][now[1]]+1
        for i in range(4):
            y = now[0]+dy_dx[i][0]
            x = now[1]+dy_dx[i][1]
            if 0 <= y < h and 0 <= x < w:
                if C[y][x] != '#' and visited[y][x] == -1:
                    visited[y][x] = cost
                    queue.append([y,x])
                    ans = max(ans,cost)
print(ans)

Submission status: Accepted

Solution code:
from copy import deepcopy
from collections import deque
h,w = map(int,input().split())
s = [['#']*(w+2) for i in range(h+2)]
for i in range(h):
    x = input()
    for j in range(w):
        s[i+1][j+1] = x[j]
ans = 0
for i in range(1,h+1):
    for j in range(1,w+1):
        if s[i][j] != '#':
            maze = deepcopy(s)
            maze[i][j] = 0
            queue = deque([[i,j]])
            while queue:
                x,y = queue.popleft()
                for a,b in([0,-1],[0,1],[1,0],[-1,0]):
                    nh,nw = x+a,y+b
                    if maze[nh][nw] == '.':
                        maze[nh][nw] = maze[x][y] + 1
                        queue.append([nh,nw])
            l = 0
            for x in range(1,h+1):
                for y in range(1,w+1):
                    if maze[x][y] != '#':
                        l = max(l,maze[x][y])
            ans = max(ans,l)
print(ans)

Submission status: Accepted

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

def bfs(h, w):
    checked = [[False for i in range(W)] for j in range(H)]
    q = [(h, w, 0)] if s[h][w] == '.' else []
    checked[h][w] = True
    g_n = 0
    while q:
        h_, w_, n = q.pop(0)
        g_n = max(n, g_n)
        for i, j in zip([0,0,-1,1],[-1,1,0,0]):
            if (0 <= h_+i < H) and (0 <= w_+j < W):
                if checked[h_+i][w_+j]: continue
                checked[h_+i][w_+j] = True
                if s[h_+i][w_+j] == '.': q.append((h_+i, w_+j, n+1))
    return g_n

n = 0
for i in range(H):
    for j in range(W):
        n = max(n, bfs(i,j))

print(n)

Submission status: Accepted

Solution code:
from collections import *
from copy import *
H,W = map(int,input().split())
S = [(W+2)*["#"]]+[["#"]+list(input())+["#"] for h in range(H)]+[(W+2)*["#"]]
D = [[1,0],[-1,0],[0,1],[0,-1]]
ans = 0
P = deque([])
Q = deque([])
 
for h in range(1,H+1):
  for w in range(1,W+1):
    if S[h][w]==".":
      P+=[[h,w]]
 
while P:
  T = deepcopy(S)
  sx,sy = P.popleft()
  T[sx][sy] = 0
  Q = deque([[sx,sy]])
  while Q:
    x,y = Q.popleft()
    for dx,dy in D:
      if T[x+dx][y+dy]==".":
        T[x+dx][y+dy] = T[x][y]+1
        Q+=[[x+dx,y+dy]]
        ans = max(ans,T[x+dx][y+dy])
 
print(ans)

Submission status: Accepted

Solution code:
# floyd_warshall
h,w = map(int,input().split())
l = [['#']*(w+2)]
for i in range(h):
    l.append(['#']+list(input())+['#'])
l.append(['#']*(w+2))

def id(x,y):
    return x*w+y

INF = 1<<29
dp = [[INF]*500 for _ in range(500)]
for i in range(500):
    dp[i][i] = 0


ans = 0
directions = [(1,0),(0,1),(-1,0),(0,-1)]

for i in range(1,h+1):
    for j in range(1,w+1):
        if l[i][j]=='#':
            continue
        for dir in directions:
            ni = i+dir[0]
            nj = j+dir[1]
            if l[ni][nj] == '#':
                continue
            dp[id(i-1,j-1)][id(ni-1,nj-1)] = 1
            dp[id(ni-1,nj-1)][id(i-1,j-1)] = 1

for k in range(h*w):
    for i in range(h*w):
        for j in range(h*w):
            dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j])

ans = 0
for si in range(h):
    for sj in range(w):
        if l[si+1][sj+1] == '#':
            continue
        for gi in range(h):
            for gj in range(w):
                if l[gi+1][gj+1] == '#':
                    continue
                ans = max(ans,dp[id(si,sj)][id(gi,gj)])
print(ans)

Submission status: Accepted

Solution code:
h,w = [int(i) for i in input().split()]
a = [[False for i in range(w)] for j in range(h)]
#print(a)

for i in range(h):
	v = input()
	for j in range(w):
		if v[j]=='.':
			a[i][j]=True
		else:
			a[i][j]=False

res = 0
ok = [[False for i in range(w)] for j in range(h)]
def bfs(x, y, d):
	q = []
	q.append((x,y,d))
	
	global res
	global ok

	while not len(q)==0:
		x, y, d = q[0]
		q.pop(0)

		if a[x][y] and not ok[x][y]:
			res = max(res, d)
			ok[x][y]=True

			if x-1>=0:
				q.append((x-1,y,d+1))
			if y-1>=0:
				q.append((x,y-1,d+1))
			if x+1<h:
				q.append((x+1,y, d+1))
			if y+1<w:
				q.append((x,y+1, d+1))


for i in range(h):
	for j in range(w):
		ok = [[False for i in range(w)] for j in range(h)]
		bfs(i,j,0)

print(res)

Submission status: Accepted

Solution code:
from collections import deque
import copy

h,w = map(int,input().split())
l = [['#']*(w+2)]
for i in range(h):
    l.append(['#']+list(input())+['#'])
l.append(['#']*(w+2))

ans = 0
directions = [(1,0),(0,1),(-1,0),(0,-1)]

for i in range(1,h+1):
    for j in range(1,w+1):
        visited = copy.deepcopy(l)
        if visited[i][j]=='.':
            visited[i][j] = 0
            que = deque([(i,j)])
            while que:
                v = que.popleft()
                for dir in directions:
                    nv = (v[0]+dir[0],v[1]+dir[1])
                    if visited[nv[0]][nv[1]] == '.':
                        times = visited[v[0]][v[1]]+1
                        visited[nv[0]][nv[1]] = times
                        que.append(nv)
                        ans = max(times,ans)
            # print((i,j),ans)

print(ans)

Submission status: Accepted

Solution code:
from copy import deepcopy
from collections import deque
from itertools import product
import numpy as np
class Grid:
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid]) + '\n'
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

def longest_path(grid, root):
    def restore_path(prev, p):
        A = deque()
        while p:
            A.appendleft(p)
            p = prev[p]
        return list(A)
    
    x, y = root
    prev = {root:None}
    grid[y, x] = '!'
    queue = deque([root])
    while queue:
        x, y = queue.popleft()
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            nx, ny = x+dx, y+dy
            if grid.is_valid_xy(nx, ny) and grid[ny, nx] in 'sg.':
                prev[nx, ny] = x, y
                queue.append((nx, ny))
                grid[ny, nx] = '!'
    return restore_path(prev, (x, y))

h, w = map(int, input().split())
grid = Grid([input() for s in range(h)])
ans = 0
for y, x in product(range(h), range(w)):
    if grid[y, x] == '.':
        path = longest_path(deepcopy(grid), (x, y))
        ans = max(ans, len(path)-1)
print(ans)

Submission status: Accepted

Solution code:
from copy import deepcopy
from collections import deque
from itertools import product
import numpy as np
class Grid:
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid]) + '\n'
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val

def longest_path(grid, root):
    def restore_route(prev, p):
        A = deque()
        while p:
            A.appendleft(p)
            p = prev[p]
        return list(A)
    
    x, y = root
    prev = {root:None}
    grid[y, x] = '!'
    queue = deque([root])
    while queue:
        x, y = queue.popleft()
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            nx, ny = x+dx, y+dy
            if grid.is_valid_xy(nx, ny) and grid[ny, nx] in 'sg.':
                prev[nx, ny] = x, y
                queue.append((nx, ny))
                grid[ny, nx] = '!'
    return restore_route(prev, (x, y))

h, w = map(int, input().split())
grid = Grid([input() for s in range(h)])
ans = 0
for y, x in product(range(h), range(w)):
    if grid[y, x] == '.':
        path = longest_path(deepcopy(grid), (x, y))
        ans = max(ans, len(path)-1)
print(ans)

Submission status: Accepted

Solution code:
import math , sys

H,W = list(map( int, input().split() ))
maze = []
for i in range(H):
    maze.append(input())
if H==1:
    print(W-1)
    sys.exit()
if W ==1:
    print(H-1)
    sys.exit()

di = [(-1,0),(1,0),(0,1),(0,-1)]
"""
def sol(s,g):
    h = s[0] ; w = s[1]
    gh, gw = g
    d = [[math.inf for _ in range(W)] for _ in range(H)]
    cand = []
    dis = 0
    while True:
        for each in di:
            dh , dw = each
            if h + dh>=0 and h + dh<H and w + dw>=0 and w + dw<W and maze[h+dh][w+dw]=="." and d[h+dh][w+dw]>dis+1:
                cand.append((h+dh, w+dw))
                d[h+dh][w+dw] = dis +1
        if len(cand)==0:
            break
        h , w =cand.pop(0)
        dis = d[h][w]
    return d[g[0]][g[1]]
"""
ans = 0
for h in range(H):
    for w in range(W):
        if maze[h][w]=="#":
            continue
        d = [[math.inf for _ in range(W)] for _ in range(H)]
        cand = []
        dis = 0
        while True:
            for each in di:
                dh , dw = each
                if h + dh>=0 and h + dh<H and w + dw>=0 and w + dw<W and maze[h+dh][w+dw]=="." and d[h+dh][w+dw]>dis+1:
                    cand.append((h+dh, w+dw))
                    d[h+dh][w+dw] = dis +1
                    ans = max(ans, dis+1)
            #print(h,w,cand, d,dis,ans)
            if len(cand)==0:
                break
            h , w =cand.pop(0)
            dis = d[h][w]

print(ans)