Problem:


Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

H W
S_{11}...S_{1W}
:
S_{H1}...S_{HW}

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.



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


Sample output:
4

Submission status: Accepted

Solution code:
INF = 10**18

H,W = map(int,input().split())
S = [input() for _ in range(H)]
N = H*W
cost = [[INF]*N for _ in range(N)]
for k in range(N):
    cost[k][k] = 0

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

for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        k = i*W+j
        for d in range(4):
            if not(0<=i+dx[d]<H and 0<=j+dy[d]<W):
                continue
            if S[i+dx[d]][j+dy[d]] == '.':
                cost[k][(i+dx[d])*W+(j+dy[d])] = 1

for k in range(N):
    for i in range(N):
        for j in range(N):
            if cost[i][k]!=INF and cost[k][j]!=INF:
                cost[i][j] = min(cost[i][j],cost[i][k]+cost[k][j])

ans = 0

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

print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
M = [list('#' * (W+2))]
M += [['#'] + list(input()) + ['#'] for _ in range(H)]
M += [list('#' * (W+2))]

n = 0
ans = 0
for y in range(1, H+1):
    for x in range(1, W+1):
        if M[y][x] == '#':
            continue
        n += 1
        M[y][x] = n
        q = set([(y, x)])
        count = -1
        while q:
            count += 1
            nq = set()
            for w, z in q:
                M[w][z] = n
                if M[w-1][z] != '#' and M[w-1][z] != n:
                    nq.add((w-1, z))
                if M[w+1][z] != '#' and M[w+1][z] != n:
                    nq.add((w+1, z))
                if M[w][z-1] != '#' and M[w][z-1] != n:
                    nq.add((w, z-1))
                if M[w][z+1] != '#' and M[w][z+1] != n:
                    nq.add((w, z+1))
            q = nq
        ans = ans if ans > count else count
print(ans)

Submission status: Accepted

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

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

m = h*w

N = [[float("inf")]* m for i in range(m)]

for i in range(m):
    N[i][i] = 0

for i in range(h):
    for j in range(w):
        t=w*i+j
        if S[i][j] != "#":
            for dt in [[-1,0],[1,0],[0,1],[0,-1]]:
                di = dt[0]
                dj=dt[1]
                ni = i+di
                nj = j+dj
                if 0 <= ni < h and 0 <= nj < w and S[ni][nj] == ".":
                    N[t][w*ni+nj] = 1

# print(N)

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

N = floyd_warshall(N)


for i in range(m):
    for j in range(m):
        if N[i][j] == float("inf"):
            N[i][j] = -1
ans = 0
# print(N)
for i in range(m):
    ans = max(ans, max(N[i]))
print(int(ans))

Submission status: Accepted

Solution code:
from collections import deque
H,W = map(int,input().split())
S = list(list(input())for _ in range(H))
ans = 0
for sh in range(H):
    for sw in range(W):
        if S[sh][sw] == "#":
            continue
        queue = deque([[sh,sw]])
        cost = [[10000]*W for i in range(H)]
        cost[sh][sw] = 0
        while queue:
            h,w = queue.popleft()
            for nh,nw in [[h-1,w],[h,w-1],[h+1,w],[h,w+1]]:
                if not (0 <= nh < H and 0 <= nw < W):
                    continue
                if S[nh][nw] == '.' and cost[nh][nw] > cost[h][w]+1:
                    cost[nh][nw] = cost[h][w]+1
                    queue.append([nh,nw])
                    ans = max(ans,cost[nh][nw])
print(ans)

Submission status: Accepted

Solution code:
def examA():
    C = SI()
    ans = chr(ord(C)+1)
    print(ans)
    return

def examB():
    N,K,M = LI()
    A = LI()
    ans = N*M-sum(A)
    if ans>K:
        ans = -1
    elif ans<0:
        ans = 0
    print(ans)
    return

def examC():
    N, M = LI()
    ansT = 0; ansP = 0
    d = defaultdict(bool)
    WA = [0]*(N+1)
    for i in range(M):
        S, P = LSI()
        S = int(S)
        if P=="WA":
            WA[S] +=1
        elif P=="AC":
            if d[S]:
                continue
            else:
                d[S] = True
                ansT +=1
                ansP +=WA[S]
    print(ansT,ansP)
    return


def bfs_grid(h,w,s,maze):
    distance = [[-1]*w for _ in range(h)]
    def bfsg():
        queue = deque()
        queue.append(s)
        distance[s[0]][s[1]] = 0
        while len(queue):
            y, x = queue.popleft()
            for i in range(4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                if (0<= nx <w and 0<= ny <h and maze[ny][nx] != '#'):
                    if distance[ny][nx]<=distance[y][x]+1 and distance[ny][nx]!=-1:
                        continue
                    queue.append((ny, nx))
                    distance[ny][nx] = distance[y][x] + 1
        return distance
    return bfsg()
def examD():
    H,W = LI()
    S = [SI() for _ in range(H)]
    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j]=="#":
                continue
            D = bfs_grid(H, W, [i, j], S)
#            print(D)
            cur = 0
            for d in D:
                cur = max(cur,max(d))
            ans = max(ans,cur)
    print(ans)
    return

def examE():
    N, K = LI()
    A = LI()

    return

def examF():
    return

import sys,copy,bisect,itertools,heapq,math
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
alphabet = [chr(ord('a') + i) for i in range(26)]

if __name__ == '__main__':
    examD()

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
S = ['#'*(W+2)]
white_num = 0
for _ in range(H):
    s = input()
    white_num += s.count('.')
    S.append('#'+s+'#')
S.append('#'*(W+2))

ans = 0
for h in range(1, H+1):
    for w in range(1, W+1):
        if S[h][w] == '#':
            continue
        C = [[-1]*(W+2) for _ in range(H+2)]
        C[h][w] = 0
        q = deque()
        q.append((h, w))
        xlist = [0, 0, 1, -1]
        ylist = [1, -1, 0, 0]
        while len(q) > 0:
            x, y = q.popleft()
            for i in range(4):
                mx = x + xlist[i]
                my = y + ylist[i]
                if S[mx][my] == '#' or C[mx][my] >= 0:
                    continue
                C[mx][my] = C[x][y] + 1
                q.append((mx, my))
        max_num = 0
        for i in C:
            max_num = max(max_num, max(i))
        ans = max(ans, max_num)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque as dq
input = sys.stdin.readline
H, W = map(int, input().split())
maze = [list(input())[: -1] for _ in range(H)]
#print(maze)
res = 0
d = [-1, 0, 1, 0]
for s in range(H * W):
  sy = s // W
  sx = s % W
  if maze[sy][sx] == "#": continue
  Q = dq([])
  Q.append(s)
  dist = [float("inf")] * (H * W)
  dist[s] = 0
  while len(Q):
    p = Q.popleft()
    py = p // W
    px = p % W
    for k in range(4):
      qy = py + d[k]
      qx = px + d[-1 - k]
      if 0 <= qy < H and (0 <= qx < W):
        if maze[qy][qx] == "#": continue
        if dist[qy * W + qx] > dist[p] + 1:
          Q.append(qy * W + qx)
          dist[qy * W + qx] = dist[p] + 1
  for x in dist:
    if x != float("inf"): res = max(res, x)
print(res)

Submission status: Accepted

Solution code:
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()

def main():
    H,W=map(int,input().split())
    S=[[] for _ in range(H+2)]
    S[0]=S[H+1]=['#']*(W+2)
    l=[]
    for i in range(1,H+1):
        S[i]=['#']+list(input())+['#']
        for j,x in enumerate(S[i]):
            if x=='.':
                l.append([i,j])
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    ans=0
    for start in l:
        d=[[INF]*(W+2) for _ in range(H+2)]
        queue=deque()
        queue.append(start)
        d[start[0]][start[1]]=0
        longest=0
        while queue:
            cell=queue.popleft()
            for k in range(4):
                if S[cell[0]+dy[k]][cell[1]+dx[k]]=='.' and d[cell[0]+dy[k]][cell[1]+dx[k]]==INF:
                    queue.append([cell[0]+dy[k],cell[1]+dx[k]])
                    d[cell[0]+dy[k]][cell[1]+dx[k]]=d[cell[0]][cell[1]]+1
                    longest=max(longest,d[cell[0]+dy[k]][cell[1]+dx[k]])
        ans=max(ans,longest)
    print(ans)
        

if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

ret = 0
for sy in range(H) :
  for sx in range(W) :
    if S[sy][sx] == '#' :
      continue
      
    cost = [[float('inf')] * W for _ in range(H)]
    cost[sy][sx] = 0
    
    q = deque([(sy, sx, 0)])
    while q :
      cy, cx, co = q.popleft()
      for dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)) :
        ny, nx = cy + dy, cx + dx
        if 0 <= ny < H and 0 <= nx < W and S[ny][nx] != '#' and co + 1 < cost[ny][nx] :
          q.append((ny, nx, co + 1))
          cost[ny][nx] = co + 1
          ret = max(ret, co + 1)
        
print(ret)

Submission status: Accepted

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):
    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)
        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 = 0
    for i in xrange(h):
        for j in xrange(w):
            if maze[i][j] != '#':
                res = max(res, dp[i][j])
    return res

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

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,hypot,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    H,W=MI()
    def is_inside(hw):
        h,w = hw
        return 0<=h<H and 0<=w<W
    grid=[[s for s in ST()] for _ in range(H)]
    ans = 0
    dxdy = [(1,0),(0,1),(-1,0),(0,-1)]
    for i in range(H*W):
        h = i//W
        w = i%W
        if grid[h][w] == "#":
            continue
        visited = set()
        q = [(h,w)]
        for cost in range(H*W+1):
            tmp = []
            if not q:
                ans = max(ans,cost-1)
                break
            while q:
                from_ = q.pop()
                if from_ in visited:
                    continue
                visited.add(from_)
                for dh,dw in dxdy:
                    to = (from_[0]+dh, from_[1]+dw)
                    if is_inside(to) and to not in visited and grid[to[0]][to[1]]==".":
                        tmp.append(to)
            q = tmp
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
g=[input() for _ in range(h)]
def search(y,x):
	q=[(y,x)]
	vis=[[-1]*w for _ in range(h)]
	vis[y][x]=0
	while q:
		cy,cx=q.pop(0)
		for dy,dx in ((1,0),(-1,0),(0,1),(0,-1)):
			ny,nx=cy+dy,cx+dx
			if 0<=ny<h and 0<=nx<w and g[ny][nx]=="." and vis[ny][nx]==-1:
				vis[ny][nx]=vis[cy][cx]+1
				q.append((ny,nx))
	return max(max(l) for l in vis)
ans=0
for i in range(h):
	for j in range(w):
		if g[i][j]==".":
			ans=max(search(i,j),ans)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
h,w = map(int, input().split())
l = [list(input()) for _ in range(h)]
ans = 0
def bfs(y,x,m):
  g = [[None if l[i][j] == '.' else -1 for j in range(w)] for i in range(h)]
  g[y][x] = 0
  q = deque()
  q.append((y,x))
  while q:
    i,j = q.popleft()
    for di,dj in ((0,1),(1,0),(-1,0),(0,-1)):
      ni = i+di; nj = j+dj
      if 0 <= ni < h and 0 <= nj < w and g[ni][nj] is None:
        g[ni][nj] = g[i][j] + 1
        q.append((ni,nj))
  return max(max(r) for r in g)

for i in range(h):
  for j in range(w):
    if l[i][j] == '.':
      d = bfs(i,j,l)
      if ans < d:
        ans = d
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

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

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

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

Submission status: Accepted

Solution code:
from collections import deque

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

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

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

S=[]

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

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

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

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

vi = 0 #時と場合によってここを変える
from collections import deque
N=H*W
def BFS(vi):
    Q = deque([vi])
    checked_list = [False for i in range(N)]
    checked_list[vi]=True
    min_path_list = [10**27 for i in range(N)] #問題によりここを変える
    min_path_list[vi] = 0
    while len(Q)>0:
        v = Q.pop()
        for v1 in e_list[v]:
            if not checked_list[v1]:
                checked_list[v1]=True
                Q.appendleft(v1)
                min_path_list[v1]=min(min_path_list[v1],min_path_list[v]+1) #問題によりここを変える
    max_d = 0
    for i in range(N):
        if min_path_list[i]<10**27:
            max_d = max(max_d,min_path_list[i])
    return max_d
ans = 0
for i in range(N):
    ans = max(BFS(i),ans)

print(ans)

Submission status: Accepted

Solution code:
from collections import deque


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

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


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

Submission status: Accepted

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

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

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

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

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

print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

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


    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

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

Submission status: Accepted

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

H,W = inpl()
inMAP = [['#']*(W+2)] + [['#']+list(input())+['#'] for y in range(H)] + [['#']*(W+2)]

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

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

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


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


print(ans)

Submission status: Accepted

Solution code:
import heapq
import sys

input = sys.stdin.readline

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


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

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

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


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

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

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

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

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

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


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

Submission status: Accepted

Solution code:
from collections import deque
dxdy = [(1, 0), (-1, 0), (0, 1), (0, -1)]
h, w = map(int, input().split())
s = [input() for _ in range(h)]
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue
        d = [[-1] * w for _ in range(h)]
        q = deque([(i, j)])
        d[i][j] = 0
        while q:
            y, x = q.popleft()
            for dx, dy in dxdy:
                if 0 <= x + dx < w and 0 <= y + dy < h and s[y + dy][x + dx] == '.' and d[y + dy][x + dx] == -1:
                    q.append((y + dy, x + dx))
                    d[y + dy][x + dx] = d[y][x] + 1
        for row in d:
            ans = max(ans, max(row))
print(ans)

Submission status: Accepted

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