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:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import bisect

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

def LI(): return list(map(int, sys.stdin.readline().split()))

H,W = LI()
S = [[] for i in range(H)]
for i in range(H):
    S[i] = list(str(input()))

graph = [[] for i in range(H * W)]
moves = [[0,1], [1,0], [0,-1],[-1,0]]
for h in range(H):
    for w in range(W):
        if S[h][w] == ".":
            for move in moves:
                next_h = h + move[0]
                next_w = w + move[1]
                if -1 < next_h < H and -1 < next_w < W:
                    if S[next_h][next_w] == ".":
                        graph[h * W + w].append(next_h*W + next_w)

# print(graph)
N = H*W
dp = [[mod for i in range(N)] for j in range(N)]
for i in range(N):
    dp[i][i] = 0
for i in range(N):
    for edge in graph[i]:
        dp[i][edge] = 1
        dp[edge][i] = 1
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] != mod:
            ans = max(ans, dp[i][j])
print(ans)

Submission status: Accepted

Solution code:
import queue
h,w=map(int,input().split())
maze=[list(input()) for i in range(h)]
#print(maze)
dx=[1,0,-1,0]
dy=[0,1,0,-1]

def maze_long(sx,sy,maze):
  if maze[sy][sx]=='#':
    return -1
  else:
    ans=[[10**9]*w for i in range(h)]
    q=queue.Queue()

    q.put([sy,sx])
    ans[sy][sx]=0
    while q.qsize():
      p=q.get()
      for i in range(4):
        nx=p[1]+dx[i]
        ny=p[0]+dy[i]
        if 0<=nx<w and 0<=ny<h: 
          if maze[ny][nx]!='#' and ans[ny][nx]>10**8:
            q.put([ny,nx])
            ans[ny][nx]=ans[p[0]][p[1]]+1
    ans2=0
    for i in range(h):
      for j in range(w):
        if ans[i][j]>10**8:
          ans[i][j]=0
    #print(ans)
    for i in range(h):
      k=max(ans[i])
      if k>ans2:
        ans2=k
    return ans2

ans=0

for i in range(h):
  for j in range(w):
    sx=j
    sy=i
    l=maze_long(sx,sy,maze)
    if l>ans:
      ans=l
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def warshall_floyd(g, N):
    d = g
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]

    return d


@mt
def slv(H, W, S):
    ans = 0
    g = [[INF] *(H*W) for _ in range(H*W)]
    def idx(i, j):
        return i*W + j
    for i in range(H):
        for j in range(W):
            if S[i][j] != '.':
                continue
            if i > 0 and S[i-1][j] == '.':
                g[idx(i, j)][idx(i-1, j)] = 1

            if i < H-1 and S[i+1][j] == '.':
                g[idx(i, j)][idx(i+1, j)] = 1

            if j > 0 and S[i][j-1] == '.':
                g[idx(i, j)][idx(i, j-1)] = 1

            if j < W-1 and S[i][j+1] == '.':
                g[idx(i, j)][idx(i, j+1)] = 1

    d = warshall_floyd(g, W*H)
    ans = 0
    for i, r in enumerate(d):
        for j, v in enumerate(r):
            if v != INF and i != j:
                ans = max(ans, v)
    return ans


def main():
    H, W = read_int_n()
    S = [read_str() for _ in range(H)]


    # H = 20
    # W = 20
    # S = ['.'*W]*H
    print(slv(H, W, S))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import copy
input = sys.stdin.readline
from collections import deque
H, W = [int(x) for x in input().split()]
S = []
for _ in range(H):
    S.append(list(input().rstrip()))
can = []
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            can.append([i, j])
ans = []
for u in can:
    S_ = copy.deepcopy(S)
    D = {}
    queue = deque([u])
    def bfs(u, S):
        S_2 = S[:]
        D[tuple(u)] = 0
        while queue:
            v = queue.popleft()
            S_2[v[0]][v[1]] = "#"
            x, y = v
            next_ = [[x + 1, y], [x - 1, y], [x, y + 1], [x, y - 1]]
            for r in next_:
                if 0 <= r[0] < H and 0 <= r[1] < W:
                    if S_2[r[0]][r[1]] == ".":
                        S_2[r[0]][r[1]] = "#"
                        D[tuple(r)] = D[tuple(v)] + 1
                        queue.append(r)
        return max(D.values())
    ans.append(bfs(u, S_))
print(max(ans))

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
State = []
for i in range(H):
    State.append(input())
starts = [(i%H,i//H) for i in range(H*W)]
goals = [(i%H,i//H) for i in range(H*W)]
from collections import deque
def min_dist(start):
    visited = [[False for i in range(W)] for j in range(H)]
    dists = [[float('inf') for i in range(W)] for j in range(H)]
    dists[start[0]][start[1]]=0
    diffs = [(0,1),(1,0),(0,-1),(-1,0)]
    Q = deque([start])
    while Q:
        current_pos = Q.pop()
        for diff in diffs:
            next_pos = (current_pos[0]-diff[0],current_pos[1]-diff[1])
            if next_pos[0] < H and next_pos[0] >= 0 and next_pos[1] < W and next_pos[1] >= 0:
                if State[next_pos[0]][next_pos[1]] == '.':
                    dists[next_pos[0]][next_pos[1]] = min(dists[current_pos[0]][current_pos[1]]+1,dists[next_pos[0]][next_pos[1]])
                    if not visited[next_pos[0]][next_pos[1]]:
                        visited[next_pos[0]][next_pos[1]] = True
                        Q.appendleft(next_pos)
    return dists
max_dist = -100000
for start in starts:
    if State[start[0]][start[1]] == '.':
        dists = min_dist(start)
        local_max_dist = -1000000
        for i in range(W):
            for j in range(H):
                if dists[j][i] != float('inf'):
                    if local_max_dist < dists[j][i]:
                        local_max_dist = dists[j][i]
        if local_max_dist > max_dist:
            max_dist = local_max_dist
print(max_dist)

Submission status: Accepted

Solution code:
from collections import deque
r,c=map(int,input().split())
ko =[list(input()) for i in range(r)]
d=[(-1,0),(1,0),(0,-1),(0,1)]


ans = 0
for sy in range(r):
    for sx in range(c):
        if ko[sy][sx] == "." :
            #print(sy,sx, "やります")
            dist = [[r*(2*c) for i in range(c)] for i in range(r)]
            H = deque()
            H.append((sy,sx))
            dist[sy][sx]=0


            while H:
                y,x=H.popleft()
                #print(y,x)
                for i in d:
                    if 0<=y+i[0]< r and 0<=x+i[1]< c and ko[y+i[0]][x+i[1]]=="." and dist[y+i[0]][x+i[1]]>dist[y][x]+1:
                        dist[y+i[0]][x+i[1]] = dist[y][x]+1
                        H.append((y+i[0],x+i[1]))

            #print(dist)
            maxnow = 0
            for i in range(r):
                for j in range(c):
                    if dist[i][j] > maxnow and dist[i][j] != r*2*c:
                        maxnow = dist[i][j]
            if maxnow > ans :
                ans = maxnow

print(ans)

Submission status: Accepted

Solution code:
import copy

H,W=map(int,input().split())
s=[['#']*(W+2)]
for i in range(H):
    s.append(['#']+list(input())+['#'])
s.append(['#']*(W+2))
#print(s)

c=copy.deepcopy(s)

L=[]
for i in range(H+2):
    for j in range(W+2):
        if c[i][j]!='#':
            L.append([i+1,j+1])

#print(L)

from collections import deque

def move(yxc):
    global Q
    y,x,cost=yxc[0],yxc[1],yxc[2]
    if c[y+1][x]=='.':
        c[y+1][x]=cost+1
        Q.append([y+1,x,cost+1])
    if c[y-1][x]=='.':
        c[y-1][x]=cost+1
        Q.append([y-1,x,cost+1])
    if c[y][x+1]=='.':
        c[y][x+1]=cost+1
        Q.append([y,x+1,cost+1])
    if c[y][x-1]=='.':
        c[y][x-1]=cost+1
        Q.append([y,x-1,cost+1])

ans=0
for i in range(len(L)):
    sx,sy=L[i][1],L[i][0]
    c=copy.deepcopy(s)
    Q=deque([[sy-1,sx-1,0]])
    c[sy-1][sx-1]='S'
    u=0
    while len(Q)>0:
        q=Q.popleft()
        move(q)
        u=max(q[2],u)
#    print(sx,sy)
#    print(c)
#    print(u)
    ans=max(ans,u)

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

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()
    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:
  visited=[[-INF]*(w+2) for i in range(h+2)]
  bfs(maze,visited,i,j)
  for i in range(1,h+1):
    for j in range(1,w+1):
      ans=max(ans,visited[i][j])

    
    
print(ans)

Submission status: Accepted

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def MI(): return map(int, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YN = ['No', 'Yes']
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']


show_flg = True
show_flg = False


def main():
    BLACK = '#'
    WHITE = '.'
    H, W = MI()
    graph = [[0 for i in range(W)] for i in range(H)]
    ans = 0
    options = [(-1, 0), (0, 1), (1, 0), (0, -1)]

    for i in range(H):
        S = input()

        for j in range(W):
            graph[i][j] = S[j]

    if H == 1 and W == 1:
        print(0)
        return

    if (H == 2 and W == 1) or (H == 1 and W == 2):
        print(1)
        return

    # H = 2
    # W = 2
    # graph = [['.' for i in range(W)] for i in range(H)]

    ans = 0
    for h in range(H):
        for w in range(W):
            if graph[h][w] == BLACK:
                continue

            visited = [[False for i in range(W)] for i in range(H)]
            q = deque()
            q.append(((h, w), 0))
            arr = []
            while len(q) != 0:
                p, c = q.popleft()
                # print(ans, n)

                for d in options:
                    i = p[0] + d[0]
                    j = p[1] + d[1]

                    if i >= 0 and i < H and j >= 0 and j < W and not visited[i][j] and graph[i][j] == WHITE:
                        visited[i][j] = True
                        q.append(((i, j), c+1))
                        # print((i, j), c+1)
                    else:
                        arr.append(c)
            # print(h, w, arr, max(arr))
            ans = max(ans, max(arr))

    print(ans)



if __name__ == '__main__':
    main()

Submission status: Accepted

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


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


def f(sx, sy):
    q = collections.deque()
    q.append((sx, sy))
    dist = [[float("inf") for w in range(W)] for h in range(H)]
    dist[sx][sy] = 0
    dx = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while q:
        h, w = q.popleft()
        d = dist[h][w]
        for x, y in dx:
            h2 = h + y
            w2 = w + x
            if h2 >= 0 and h2 < H and w2 >= 0 and w2 < W:
                if S[h2][w2] == "." and dist[h2][w2] == float("inf"):
                    dist[h2][w2] = d+1
                    q.append((h2, w2))
    ma = 0
    for d in dist:
        for i in d:
            if i != float("inf"):
                ma = max(ma, i)
    return ma


def main():
    ans = 0
    for y in range(H):
        for x in range(W):
            if S[y][x] == ".":
                ans = max(ans, (f(y, x)))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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] == "#":
            continue
        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:
                        continue
                    elif grid[next_h][next_w] == "#":
                        continue
                    elif grid[next_h][next_w] == ".":
                        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: Accepted

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

for i in range(H):
    S[i]=input()
    
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

n=H*W
inf=10**9

d = [[inf]*n for _ in range(n)] 
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(H):
    for j in range(W):
        if S[i][j]==".":
            if j+1<W:
                if S[i][j+1]==".":
                    d[i*W+j][i*W+j+1]=1
                    d[i*W+j+1][i*W+j]=1
            if i+1<H:
                if S[i+1][j]==".":
                    d[i*W+j][(i+1)*W+j]=1
                    d[(i+1)*W+j][i*W+j]=1
    
        
for i in range(n):
    d[i][i] = 0 #自身のところに行くコストは０
ans=0

warshall_floyd(d)

for i in range(n):
    for j in range(n):
        if d[i][j]>=ans and d[i][j]<=inf-10:
            ans=d[i][j]

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
grid = [list(input()) for _ in range(h)]

#四方向の移動用
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]


def bfs(sx, sy):
    d = [[-1]*w for i in range(h)]
    que = deque([])
    que.append((sx, sy))
    d[sy][sx] = 0

    while que:
        p = que.popleft()

        for i in range(4):
            nx = p[0]+dx[i]
            ny = p[1]+dy[i]

            if (0 <= nx < w) and (0 <= ny < h) and (grid[ny][nx] != "#") and (d[ny][nx] == -1):
                que.append((nx, ny))
                d[ny][nx] = d[p[1]][p[0]] + 1

    return max(sum(d, []))


ans = 0
for sy in range(h):
    for sx in range(w):
        if grid[sy][sx] != "#":
            temp = bfs(sx, sy)
            if ans < temp:
                ans = temp
print(ans)

Submission status: Accepted

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

from collections import deque
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]

ans = 0
for i in range(H):
    for j in range(W):
        if l[i][j] == '#':
            continue
        ll = [[0] * W for _ in range(H)]
        q = deque([(i, j)])
        while q:
            y, x = q.popleft()
            for dy, dx in d:
                if 0 <= y+dy < H and 0 <= x+dx < W and l[y+dy][x+dx] == '.' and (y+dy, x+dx) != (i, j):
                    n = ll[y][x] + 1
                    if ll[y+dy][x+dx] == 0 or ll[y+dy][x+dx] > n:
                        ll[y+dy][x+dx] = n
                        q.append((y+dy, x+dx))
                        if ans < n:
                            ans = n

print(ans)

Submission status: Accepted

Solution code:
import copy

def check(ss, l):
    ns = []
    for s in ss:
        for i in range(4):
            if nmaze[s[0]+move[i][0]][s[1]+move[i][1]] == '.':
                nmaze[s[0]+move[i][0]][s[1]+move[i][1]] = l
                ns.append([s[0]+move[i][0], s[1]+move[i][1]])
    if len(ns) > 0:
        return check(ns, l+1)
    else:
        return l

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

move = [[-1, 0], [1, 0], [0, -1], [0, 1]]
ans = 0
for i in range(1, H+1):
    for j in range(1, W+1):
        if maze[i][j] == '.':
            nmaze = copy.deepcopy(maze)
            nmaze[i][j] = 0
            l = check([[i, j]], 0)
            if ans < l:
                ans = l
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H,W = map(int,input().split())
S = [["#"]*(W+2)] +[list("#"+input()+"#") for _ in range(H)]+[["#"]*(W+2)]
lis = [[0]*(W+2) for _ in range(H+2)]
q = deque()
ans = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        lis = [[0]*(W+2) for _ in range(H+2)]
        q = deque()
        if S[i][j] == ".":
            q.append([i,j,0])
        else:
            continue
        se = set()
        while q:
            n = q.popleft()
            if lis[n[0]][n[1]]:
                continue
            else:
                lis[n[0]][n[1]] = 1
            #se = se | set([n[0],n[1]])
            ans = max(ans,n[2])
            if S[n[0]][n[1]-1] == ".":
                q.append([n[0],n[1]-1,n[2]+1])
            if S[n[0]][n[1]+1] == ".":
                q.append([n[0],n[1]+1,n[2]+1])
            if S[n[0]-1][n[1]] == ".":
                q.append([n[0]-1,n[1],n[2]+1])
            if S[n[0]+1][n[1]] == ".":
                q.append([n[0]+1,n[1],n[2]+1])
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from collections import deque

INF = float("inf")

XX = [1, -1, 0, 0]
YY = [0, 0, 1, -1]


def main():

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

    dist = [[-1]*W for _ in range(H)]

    ans = 0
    for h in range(H):
        for w in range(W):
            # スタート位置 (h, w)
            if S[h][w] == "#":
                continue
            # 距離
            dist = [[INF]*W for _ in range(H)]

            dist[h][w] = 0
            q = deque([(h, w, 0)])
            while len(q) > 0:
                y, x, p = q.popleft()
                # 上下左右に移動可能ならば、移動して更新する
                for dx, dy in zip(XX, YY):
                    if y + dy < 0 or y + dy >= H:
                        continue
                    if x + dx < 0 or x + dx >= W:
                        continue
                    if S[y+dy][x+dx] == "#":
                        continue
                    if p + 1 < dist[y+dy][x+dx]:
                        dist[y+dy][x+dx] = p+1
                        q.append((y+dy, x+dx, p+1))

            # 一番遠く
            toku = -1
            I, J = -1, -1
            for i in range(H):
                for j in range(W):
                    if dist[i][j] != INF:
                        if dist[i][j] >= toku:
                            I, J = i, j
                        toku = max(dist[i][j], toku)
            if toku >= ans:
                ans = max(toku, ans)
                # print("start: ", h, w, " goal: ", I, J, " dist: ", toku)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#幅優先探索


from queue import Queue

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

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

mat=[]
mat.append([False]*(W+2))
for i in range(H):
  line=input()
  row=[False]
  for j in line:
    if j=="#":
      row.append(False)
    else:
      row.append(True)
  row.append(False)
  mat.append(row)
mat.append([False]*(W+2))
#print(mat)

max_depth=0
for i in range(1,H+1):
  for j in range(1,W+1):
    if not mat[i][j]:
      continue
    
    bfs_mat=[]
    for ii in range(H+1):
      bfs_mat.append([99]*(W+1))
      
    #print(bfs_mat)
    max_dist=0
    bfs_queue=[(i,j,0)]
    while(len(bfs_queue)>0):
      new_queue=set()
      for (ii,jj,dist) in bfs_queue:
        #print((ii,jj,dist))
        bfs_mat[ii][jj]=dist
        max_dist=dist
        if mat[ii-1][jj] and bfs_mat[ii-1][jj]==99:
          new_queue.add((ii-1,jj,dist+1))
        if mat[ii+1][jj] and bfs_mat[ii+1][jj]==99:
          new_queue.add((ii+1,jj,dist+1))
        if mat[ii][jj-1] and bfs_mat[ii][jj-1]==99:
          new_queue.add((ii,jj-1,dist+1))
        if mat[ii][jj+1] and bfs_mat[ii][jj+1]==99:
          new_queue.add((ii,jj+1,dist+1))

      bfs_queue=new_queue
      #print(bfs_queue)

    #print((i,j,max_dist))
    if max_dist>max_depth:
      max_pos=(i,j)
      max_depth=max_dist

#print(max_pos)
print(max_depth)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]

def main():
    inf=1000
    h,w=MI()
    ss=[[c=="#" for c in input()] for _ in range(h)]
    mx=0
    for si in range(h):
        for sj in range(w):
            if ss[si][sj]:continue
            bfs={}
            bfs[si,sj]=0
            vis=[[False]*w for _ in range(h)]
            vis[si][sj]=True
            while bfs:
                nxt={}
                for (i,j),d in bfs.items():
                    if d>mx:mx=d
                    for ni, nj in [(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)]:
                        if ni<0 or nj<0 or ni>=h or nj>=w:continue
                        if ss[ni][nj]:continue
                        if vis[ni][nj]:continue
                        vis[ni][nj]=True
                        nxt[ni,nj]=d+1
                bfs=nxt
    print(mx)

main()

Submission status: Accepted

Solution code:
import math
import sys
sys.setrecursionlimit(10**9)
H,W = map(int,input().split())

S = []
for h in range(H):
    s = input()
    t = []
    for ss in s:
        if ss==".":
            t.append(True)
        else:
            t.append(False)
    S.append(t)

# print(S)

V = H*W

d = [[float("inf") for i in range(V)] for j in range(V)]

for h in range(H):
    for w in range(W):
        i = h*W+w
        if S[h][w]:
            if 0<=h<=H-2 and S[h+1][w]:
                j = (h+1)*W+w
                d[i][j], d[j][i] = 1,1
            if 1<=h<=H-1 and S[h-1][w]:
                j = (h-1)*W+w
                d[i][j], d[j][i] = 1,1
            if 0<=w<=W-2 and S[h][w+1]:
                j = h*W+(w+1)
                d[i][j], d[j][i] = 1,1
            if 1<=w<=W-1 and S[h][w-1]:
                j = h*W+(w-1)
                d[i][j], d[j][i] = 1,1

# print(d)

def warshall_floyd(d, V): 
    # dd = [[float("inf") for i in range(V)] for j in range(V)]
    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[i][j]に頂点i, j間の最短距離を格納

# 例一個作ってみる．
dd = warshall_floyd(d, V)

# print(dd)
mx = 0
for i,ddd in enumerate(dd):
    for j,n in enumerate(ddd):
        if math.isfinite(n) and i!=j:
            mx = max(mx, n)

print(mx)

# 6 4
# #...
# #.#.
# #...
# #.#.
# #.#.
# #.#.

# 2 1
# .
# .

Submission status: Accepted

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

n_list = []
v_table = {}
for y in range(H):
	for x in range(W):
		n = (x, y)
		n_list.append(n)
		v_table[n] = []

prev = None
ns = None
for y in range(H):
	cur = input()
	for x in range(W):
		if cur[x] == ".":
			nc = (x, y)
			ns = nc
			if y > 0 and prev[x] == ".":
				np = (x, (y - 1))
				v_table[np].append(nc)
				v_table[nc].append(np)
			if x > 0 and cur[x - 1] == ".":
				np = (x - 1, y)
				v_table[np].append(nc)
				v_table[nc].append(np)
	prev = cur

def calc_dists(x, n_list, edges):
	dists = { x: 0 }
	queue = [ x ]
	
	while queue:
		cur = queue.pop(0)
		dist = dists[cur] + 1
		for v2 in edges[cur]:
			if (not v2 in dists) or (dists[v2] > dist):
				dists[v2] = dist
				queue.append(v2)
	
	return dists

max_dist = 0
for n in n_list:
	dists = calc_dists(n, n_list, v_table)
	for n2, dist in dists.items():
		if dist > max_dist:
			max_dist = dist
print(max_dist)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[list(input())for i in range(h)]
e=0
for i in range(h):
    for j in range(w):
        if s[i][j]==".":
            p=[i,j]
            q=[p]
            t=[[1]*w for j in range(h)]
            t[p[0]][p[1]]=0
            g=0
            while q:
                c=[]
                for i,j in q:
                    a=[1,-1,0,0]
                    b=[0,0,1,-1]
                    for d in range(4):
                        if 0<=i+a[d]<h and 0<=j+b[d]<w:
                            if s[i+a[d]][j+b[d]]==".":
                                if t[i+a[d]][j+b[d]]:
                                    t[i+a[d]][j+b[d]]=0
                                    c.append([i+a[d],j+b[d]])
                if len(c)==0:
                    break
                else:
                    g+=1
                    q=c[::]
            e=max(e,g)
print(e)

Submission status: Accepted

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

INF = 10 ** 18

ans = 0
for h in range(H):
    for w in range(W):
        if grid[h][w] == '#':
            continue
        dist = [[INF] * W for _ in range(H)]
        dist[h][w] = 0
        q = [(h,w)]
        d = 1
        while q:
            qq = []
            for y,x in q:
                for dy,dx in [(-1,0),(1,0),(0,-1),(0,1)]:
                    yy,xx = y+dy, x+dx
                    if not (0 <= yy < H and 0 <= xx < W):
                        continue
                    if grid[yy][xx] == '#':
                        continue
                    if dist[yy][xx] != INF:
                        continue
                    dist[yy][xx] = d
                    qq.append((yy,xx))
            q = qq
            d += 1
        for i in range(H):
            for j in range(W):
                if dist[i][j] != INF:
                    ans = max(ans,dist[i][j])

print(ans)