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:
h,w=map(int,input().split())
inf=10**3
d=((-1,0),(1,0),(0,-1),(0,1))
S=[["#"]*(w+2)]
S.extend([["#"]+[s for s in input()]+["#"] for _ in range(h)])
S.append(["#"]*(w+2))
import collections
def dist(a,b):
  D=[[inf]*(w+2) for _ in range(h+2)]
  D[a][b]=0
  Visit=collections.deque()
  Visit.append(100*a+b)
  while Visit:
    v=Visit.popleft()
    va,vb=v//100,v%100
    for dx,dy in d:
      if S[va+dx][vb+dy]=="." and D[va+dx][vb+dy]==inf:
        Visit.append((va+dx)*100+(vb+dy))
        D[va+dx][vb+dy]=D[va][vb]+1
  ret=0
  for i in range(h):
    for j in range(w):
      if D[i+1][j+1]<inf:
        ret=max(ret,D[i+1][j+1])
  return ret
ans=0
for i in range(h):
  for j in range(w):
    if S[i+1][j+1]==".":
      ans=max(dist(i+1,j+1),ans)
print(ans)

Submission status: Accepted

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

#from queue import Queue
from collections import deque

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

sum_sharp = sum([A[i].count('#') for i in range(H)])

fin_d_max = 1

for s_i in range(H):
    for s_j in range(W):
        #print(s_i,s_j)
        d_max = 0
        #q_i = Queue()
        q_i = deque()
        #q_j = Queue()
        q_j = deque()
        D = [[-1]*W for i in range(H)]
        #flag = [[0]*W for i in range(H)]
        flag = 1

        if A[s_i][s_j] == '.':
            D[s_i][s_j] = 0
            #q_i.put(s_i)
            q_i.append(s_i)
            #q_j.put(s_j)
            q_j.append(s_j)
            #while sum(map(sum, flag)) != W*H - sum_sharp:
            #while flag < W*H - sum_sharp:
            #while q_i.empty() == False:
            while len(q_i)!=0:
            #for a in range(W*H):
                #i = q_i.get()
                i = q_i.popleft()
                #j = q_j.get()
                j = q_j.popleft()
                for x in range(4):
                    ni = i+di[x]
                    nj = j+dj[x]
                    #if ni<0 or ni>=H or nj<0 or nj>=W or A[ni][nj]== '#' or 0<=D[ni][nj]<D[i][j]+1:
                    if ni<0 or ni>=H or nj<0 or nj>=W or A[ni][nj]== '#' or D[ni][nj]!=-1:
                    #if ni<0 or ni>=H or nj<0 or nj>=W:
                        continue
                    #elif A[ni][nj]== '#' or D[ni][nj] < D[i][j]+1:
                        #flag[ni][nj] = 1
                        #continue
                    else:
                        #if D[ni][nj] == -1:
                            #print(flag)
                        flag += 1
                        D[ni][nj] = D[i][j]+1
                        d_max = max(d_max, D[ni][nj])
                        #q_i.put(ni)
                        q_i.append(ni)
                        q_j.append(nj)
                        #q_j.put(nj)
        fin_d_max = max(fin_d_max, d_max)
                
print(fin_d_max)

Submission status: Accepted

Solution code:
from collections import deque
INF = 1001001001
di = [-1, 0, 1, 0]
dj = [ 0,-1, 0, 1]

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

ans = 0
for si in range(H):
    for sj in range(W):
        if S[si][sj] == '#': continue
        dist = [[INF] * W for _ in range(H)]
        dist[si][sj] = 0
        q = deque([(si, sj)])
        while q:
            i, j = q.popleft()
            for dir in range(4):
                ni = i + di[dir]
                nj = j + dj[dir]
                if (ni<0 or ni>=H or nj<0 or nj>=W): continue
                if S[ni][nj] == '#': continue
                if dist[ni][nj] != INF: continue
                dist[ni][nj] = dist[i][j] + 1
                q.append([ni, nj])
        for i in range(H):
            for j in range(W):
                if dist[i][j] == INF: continue
                ans = max(ans, dist[i][j])
print(ans)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
inf=10**3
d=((-1,0),(1,0),(0,-1),(0,1))
S=[["#"]*(w+2)]
S.extend([["#"]+[s for s in input()]+["#"] for _ in range(h)])
S.append(["#"]*(w+2))
import heapq

def dist(a,b):
  D=[[inf]*(w+2) for _ in range(h+2)]
  D[a][b]=0
  Visit=[100*a+b]
  heapq.heapify(Visit)
  while Visit:
    v=heapq.heappop(Visit)
    vd,va,vb=v//(10**4),(v%(10**4))//100,v%100
    for dx,dy in d:
      if S[va+dx][vb+dy]=="." and D[va+dx][vb+dy]==inf:
        heapq.heappush(Visit,(vd+1)*(10**4)+(va+dx)*(10**2)+vb+dy)
        D[va+dx][vb+dy]=vd+1
  ret=0
  for i in range(h):
    for j in range(w):
      if D[i+1][j+1]<inf:
        ret=max(ret,D[i+1][j+1])
  return ret
ans=0
for i in range(h):
  for j in range(w):
    if S[i+1][j+1]==".":
      ans=max(dist(i+1,j+1),ans)
print(ans)

Submission status: Accepted

Solution code:
def search(y, x):
    dy_list = [-1, 0, 1, 0]
    dx_list = [0, -1, 0, 1]

    queue = [(y, x)]
    dist = [[-1 for _ in range(w)] for _ in range(h)]
    dist[y][x] = 0
    while queue:
        # print('queue: ', queue)
        now_y, now_x = queue.pop(0)
        for dy, dx in zip(dy_list, dx_list):
            next_y = now_y+dy
            next_x = now_x+dx

            # 範囲外なら
            if not(0 <= next_y < h and 0 <= next_x < w):
                continue
            # 壁なら
            elif s_list[next_y][next_x] == '#':
                continue
            # 探索済なら
            elif dist[next_y][next_x] != -1:
                continue

            dist[next_y][next_x] = dist[now_y][now_x]+1
            # print((now_y, now_x), (next_y, next_x), dist[now_y][now_x]+1)
            # print(dist, '\n')
            queue.append((next_y, next_x))

    return max(max(d) for d in dist)


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

ans = 0
for i in range(h):
    for j in range(w):
        if s_list[i][j] == '.':
            ans = max(search(i, j), ans)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
INF = 1001001001
di = (-1, 0, 1, 0)
dj = ( 0,-1, 0, 1)

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

ans = 0
for si in range(h):
    for sj in range(w):
        if s[si][sj] == '#': continue
        dist = [[INF] * w for _ in range(h)]
        dist[si][sj] = 0
        q = deque([(si,sj)])
        while q:
            i,j = q.popleft()
            for dir in range(4):
                ni = i + di[dir]
                nj = j + dj[dir]
                if (ni<0 or ni>=h or nj<0 or nj>=w): continue
                if s[ni][nj] == '#': continue
                if dist[ni][nj] != INF: continue
                q.append((ni,nj))
                dist[ni][nj] = dist[i][j] + 1
        for i in range(h):
            for j in range(w):
                if dist[i][j] == INF: continue
                ans = max(ans, dist[i][j])
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from itertools import chain

H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]
inf = float('inf')


def flatten(list_of_lists):
    return chain.from_iterable(list_of_lists)


def bfs(start, end):
    distance = [[inf for _ in range(W)] for _ in range(H)]
    queue = deque([(end, start)])
    distance[end][start] = 0

    while queue:
        y, x = queue.pop()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
            if 0 <= nx < W and 0 <= ny < H and M[ny][nx] != '#' and distance[ny][nx] == inf:
                queue.appendleft((ny, nx))
                distance[ny][nx] = distance[y][x] + 1
    return distance


m = 0
for i in range(W):
    for j in range(H):
        if M[j][i] != "#":

            for length in list(flatten(bfs(i, j))):
                if length != inf and m < length:
                    m = length

print(m)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [input() for _ in range(H)]
from collections import deque
INF = 1001001001
di = [-1, 0, 1, 0]
dj = [ 0,-1, 0, 1]

ans = 0
for si in range(H):
    for sj in range(W):
        if S[si][sj] == '#': continue
        dist = [[INF]*W for _ in range(H)]
        dist[si][sj] = 0
        q = deque([(si, sj)])
        while q:
            i, j = q.popleft()
            for dir in range(4):
                ni = i + di[dir]
                nj = j + dj[dir]
                if (ni<0 or ni>=H or nj<0 or nj>=W): continue
                if S[ni][nj] == '#': continue
                if dist[ni][nj] != INF: continue
                q.append([ni, nj])
                dist[ni][nj] = dist[i][j] + 1
        for i in range(H):
            for j in range(W):
                if dist[i][j] == INF: continue
                ans = max(ans, dist[i][j])
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from itertools import chain

H, W = map(int, input().split())
M = [list(input()) for _ in range(H)]
inf = float('inf')


def flatten(list_of_lists):
    return chain.from_iterable(list_of_lists)


def bfs(start, end):
    distance = [[inf for i in range(W)] for j in range(H)]
    queue = deque([(end, start)])
    distance[end][start] = 0

    while queue:
        y, x = queue.pop()
        for i in range(0, 4):
            nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
            if 0 <= nx < W and 0 <= ny < H and M[ny][nx] != '#' and distance[ny][nx] == inf:
                queue.appendleft((ny, nx))
                distance[ny][nx] = distance[y][x] + 1
    return distance


m = 0
for i in range(W):
    for j in range(H):
        if M[j][i] != "#":

            for length in list(flatten(bfs(i, j))):
                if length != inf and m < length:
                    m = length

print(m)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
def main():
    H, W = map(int, input().split())
    m = []
    for _ in range(H):
        l = input()
        m.append(l)
    edge = []
    v = H * W
    for i in range(H):
        for j in range(W):
            t = i * W + j
            edge.append([10 ** 9] * v)
            if m[i][j] == '.':
                if i > 0 and m[i-1][j] == '.':
                    edge[t][(i-1) * W + j] = 1
                if j > 0 and m[i][j -1] == '.':
                    edge[t][i * W + j - 1] = 1
                if i < H-1 and m[i+1][j] == '.':
                    edge[t][(i + 1)*W + j] = 1
                if j < W - 1 and m[i][j+1] == '.':
                    edge[t][i * W + j + 1] = 1
    G = csgraph_from_dense(edge, null_value=10**9)
    d = floyd_warshall(G)
    m = 0
    for i in range(v):
        for j in range(v):
            if d[i][j] != float('inf') and d[i][j] > m:
                m = d[i][j]
    print(int(m))
main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ in range(h)]
from collections import deque
di=[-1,0,1,0]
dj=[0,-1,0,1]
INF=1001001001
ans=0
for si in range(h):
    for sj in range(w):
        if s[si][sj]=='#': continue
        dist=[[INF]*w for _ in range(h)]
        dist[si][sj]=0
        q=deque([(si,sj)])
        while len(q)>0:
            i,j=q.popleft()
            for dir in range(4):
                ni=i+di[dir]
                nj=j+dj[dir]
                if(ni<0 or ni>=h or nj<0 or nj>=w): continue
                if(s[ni][nj]=='#'): continue
                if(dist[ni][nj]!=INF): continue
                q.append((ni,nj))
                dist[ni][nj]=dist[i][j]+1
        for i in range(h):
            for j in range(w):
                if dist[i][j]==INF: continue
                ans=max(ans,dist[i][j])
print(ans)

Submission status: Accepted

Solution code:
import queue

H, W = map(int, input().split(' '))
S = []

for h in range(H):
    row = input()
    S.append(row)

INF = 100100100

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

ans = 0

for si in range(H):
    for sj in range(W):
        # start地点を設定する
        s = S[si][sj]
        if s == '#':
            continue

        dist = [[INF] * W for i in range(H)]
        q = queue.Queue()

        def update(i, j, x):
            global dist
            global INF
            global q
            if dist[i][j] != INF:
                return
            dist[i][j] = x
            q.put((i, j))

        update(si, sj, 0)
        while not q.empty():
            p = q.get()
            i = p[0]
            j = p[1]
            for dn in range(4):
                ni = i + di[dn]
                nj = j + dj[dn]
                if ni < 0 or ni >= H or nj < 0 or nj >= W:
                    continue
                if S[ni][nj] == '#':
                    continue
                update(ni, nj, dist[i][j] + 1)

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

print(ans)

Submission status: Accepted

Solution code:
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path, csgraph_from_dense, floyd_warshall
def main():
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]
    m = [[0] * (W * H) for _ in range(W * H)]
    def loc(h, w):
        return h * W + w
    def con(h1, w1, h2, w2):
        m[loc(h1, w1)][loc(h2, w2)] = 1
        m[loc(h2, w2)][loc(h1, w1)] = 1

    for h in range(H):
        for w in range(W):
            if S[h][w] == '#':
                continue
            if h > 0:
                if S[h - 1][w] == '.':
                    con(h, w, h - 1, w)
            if h < H - 1:
                if S[h + 1][w] == '.':
                    con(h, w, h + 1, w)
            if w > 0:
                if S[h][w - 1] == '.':
                    con(h, w, h, w - 1)
            if w < W - 1 and S[h][w + 1] == '.':
                con(h, w, h, w + 1)
    g = csgraph_from_dense(m)
    EE = floyd_warshall(g)
    print(int(np.max(EE[~np.isinf(EE)])))


main()

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
S = [0 for j in range(H)]
for i in range(H):
    S[i] = list(str(input()))
TF = [[False for i in range(W)] for j in range(H)]
first = [0,0]
for j in range(H):
    for i in range(W):
        if S[j][i] == '#':
            TF[j][i] = True
        else:
            first = [j,i]
distance = [[0 for i in range(W)] for j in range(H)]
def bfs(s):
    Q = []
    TF[s[0]][s[1]] = True
    Q.append(s)
    while Q:
        v = Q.pop(0)
        next = [[v[0], v[1]+1], [v[0], v[1]-1],[v[0]+1, v[1]], [v[0]-1,v[1]]]
        for u in next:
            if u[0] >= 0 and u[0] <= H-1 and u[1] >= 0 and u[1] <= W-1:
                if TF[u[0]][u[1]] == False:
                    distance[u[0]][u[1]] = distance[v[0]][v[1]] + 1
                    TF[u[0]][u[1]] = True
                    Q.append(u)

maxd = 0
for k in range(H):
    for l in range(W):
        if S[k][l] == '.':
            first = [k,l]
            TF = [[False for i in range(W)] for j in range(H)]
            for j in range(H):
                for i in range(W):
                    if S[j][i] == '#':
                        TF[j][i] = True
            distance = [[0 for i in range(W)] for j in range(H)]
            bfs(first)
            #print(first)
            #print(distance)
            for j in range(H):
                for i in range(W):
                    maxd = max(maxd,distance[j][i])

print(maxd)

Submission status: Accepted

Solution code:
import unittest
import collections


class TestD(unittest.TestCase):
    def test_1(self):
        self.assertEqual(think(['...', '...', '...']), 4)

    def test_2(self):
        self.assertEqual(think(['...#.', '.#.#.', '.#...']), 10)


def solve():
    maze = read()
    result = think(maze)
    write(result)


def read():
    h, w = read_int(2)
    maze = []
    for _ in range(h):
        maze.append(read_line(n=w))
    return maze


def read_int(n):
    return read_type(int, n, sep=' ')


def read_float(n):
    return read_type(float, n, sep=' ')


def read_type(t, n, sep):
    return list(map(lambda x: t(x), read_line().split(sep)))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(maze):
    wall = '#'
    h, w = get_height_and_width_of(maze)
    longest_path_length = 0

    for y in range(h):
        for x in range(w):
            if maze[y][x] == wall:
                continue
            longest_path_length = max(longest_path_length, search(maze, x, y, wall))

    return longest_path_length


def write(result):
    print(result)


def get_height_and_width_of(maze):
    return len(maze), len(maze[0])


def search(maze, x, y, wall):
    h, w = get_height_and_width_of(maze)
    inf = h * w + 1

    dp = prepare_dp_table(h, w, inf)

    return bfs(maze, dp, w, h, x, y, wall)


def prepare_dp_table(h, w, inf):
    return [[inf for _ in range(w)] for _ in range(h)]


def bfs(maze, dp, w, h, x, y, wall):
    queue = collections.deque([])
    queue.append((x, y, 0))

    max_distance = 0

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

    while queue:
        xx, yy, distance = queue.popleft()
        if dp[yy][xx] <= distance:
            continue
        dp[yy][xx] = distance
        max_distance = max(max_distance, distance)

        for dx, dy in diff_xy:
            nx, ny = xx + dx, yy + dy
            if not in_range(w, h, nx, ny):
                continue
            if maze[ny][nx] == wall:
                continue
            if dp[ny][nx] <= distance + 1:
                continue
            queue.append((nx, ny, distance + 1))

    return max_distance


def in_range(w, h, x, y):
    return 0 <= x < w and 0 <= y < h


if __name__ == '__main__':
    # unittest.main()
    solve()

Submission status: Accepted

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

def clear_maze(sx, sy, maze):
    INF = -float('infinity')
    field_x_length = len(maze)
    field_y_length = len(maze[0])
    distance = [[INF for i in range(field_y_length)] for j in range(field_x_length)]

    queue = deque([(sx, sy)])
    distance[sx][sy] = 0
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    while queue:
        x, y = queue.pop()
        # if x == gx and y == gy:
        #     break
        for i in range(0, 4):
            nx, ny = x + dx[i], y + dy[i]
            if (0 <= nx < field_x_length) and (0 <= ny < field_y_length):
                if maze[nx][ny] != '#' and distance[nx][ny] == INF:
                    queue.appendleft((nx, ny))
                    distance[nx][ny] = distance[x][y] + 1
    MAX = 0
    for row in range(field_x_length):
        for col in range(field_y_length):
            MAX = max(MAX, distance[row][col])
    return MAX
    # return distance[gx][gy]

pairs = []
for i in range(h):
    for j in range(w):
        if maze[i][j] == '.':
            pairs.append([i, j])

MAX = 0
for sx, sy in pairs:
    r = clear_maze(sx, sy, maze)
    MAX = max(MAX, r)
print(MAX)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


def calc_dist(s, start_i, start_j, h, w):
    from collections import deque

    result = 0
    # 待ち行列に相当する部分をキューで管理
    d = deque()
    # キューの初期化
    d.append((start_i, start_j))
    # 仮決めした始点からの距離を計算
    dist = [[0 for _ in range(w)] for _ in range(h)]
    # 迷路のマスを通ったかどうかを管理
    visited = [[False for _ in range(w)] for _ in range(h)]
    visited[start_i][start_j] = True
    # 4方向を移動する部分を配列でスマートに管理する
    dxy = [(1, 0), (-1, 0), (0, -1), (0, 1)]

    while d:
        hd, wd = d.popleft()

        # 上下左右の4方向に移動
        for dx, dy in dxy:
            nx = wd + dx
            ny = hd + dy

            # 迷路の範囲外
            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue

            # 壁
            if s[ny][nx] == '#':
                continue

            # 既に通過した
            # DEBUG: 本番では、ここがなくて計算量が爆発していた
            if visited[ny][nx]:
                continue

            visited[ny][nx] = True
            dist[ny][nx] = dist[hd][wd] + 1
            d.append((ny, nx))
            result = max(result, dist[ny][nx])

    return result


def main():
    h, w = map(int, input().split())
    s = [list(input()) for _ in range(h)]
    ans = 0

    # KeyInsight
    # 始点のみを全探索(終点は全探索する必要はない．終点の位置は、移動距離の最大値に相当)
    # 距離は幅優先探索BFSで計算
    # DEBUG: 終点を全探索するループさえなければACしていた
    for start_i in range(h):
        for start_j in range(w):
            # 始点が壁のときは、距離を計算しない
            if s[start_i][start_j] == '#':
                continue

            ans = max(ans, calc_dist(s, start_i, start_j, h, w))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
x,y=map(int,input().split())
lol=[]
for _ in range(x):
    lol.append(list(input()))
w=0
for i in range(x):
    for j in range(y):
        if lol[i][j]==".":
            yo=[]
            for k in lol:
                yo.append(k[:])
            
            s=[[i,j]]
            v=[0]
            while len(s)!=0:
                l=s.pop(0)
                k=v.pop(0)
                w=max(w,k)
                a=l[0]
                b=l[1]
                yo[a][b]="#"
                if 0<=a+1<x:
                    if yo[a+1][b]==".":
                        s.append([a+1,b])
                        v.append(k+1)
                        yo[a+1][b]="#"
                if 0<=a-1<x:
                    if yo[a-1][b]==".":
                        s.append([a-1,b])
                        v.append(k+1)
                        yo[a-1][b]="#"
                if 0<=b-1<y:
                    if yo[a][b-1]==".":
                        s.append([a,b-1])
                        v.append(k+1)
                        yo[a][b-1]="#"
                if 0<=b+1<y:
                    if yo[a][b+1]==".":
                        s.append([a,b+1])
                        v.append(k+1)
                        yo[a][b+1]="#"
print(w)

Submission status: Accepted

Solution code:
from collections import deque
INF = 1001001001
di = [-1, 0, 1, 0]
dj = [ 0,-1, 0, 1]

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

ans = 0
for si in range(H):
    for sj in range(W):
        if (S[si][sj] == '#'): continue
        dist = [[INF]*W for _ in range(H)]
        dist[si][sj] = 0
        q = deque([(si, sj)])
        while len(q) > 0:
            i, j = q.popleft()
            for dir in range(4):
                ni = i + di[dir]
                nj = j + dj[dir]
                if (ni<0 or ni>=H or nj<0 or nj>=W): continue
                if (S[ni][nj] == '#'): continue
                if (dist[ni][nj] != INF): continue
                q.append((ni, nj))
                dist[ni][nj] = dist[i][j] + 1
        for i in range(H):
            for j in range(W):
                if dist[i][j] == INF: continue
                ans = max(ans, dist[i][j])
print(ans)

Submission status: Accepted

Solution code:
INF=10**9+7
H,W=map(int,input().split())
S=list()
q=list()

S.append(["#"]*(W+2))
for i in range(H):
  S.append(["#"]+list(input())+["#"])
S.append(["#"]*(W+2))


m=0
for y in range(1,H+1):
  for x in range(1,W+1):
    if S[y][x]=="#":
      continue
    D=[[INF]*(W+2) for _ in range(H+2)]
    D[y][x]=0
    q.clear()
    q.append([x,y])
    while len(q)>0:
      c=list(q.pop(0))
      for dx,dy in [[-1,0],[1,0],[0,-1],[0,1]]:
        ny,nx=c[1]+dy,c[0]+dx
        if S[ny][nx]=="." and D[ny][nx]==INF:
          D[ny][nx]=D[c[1]][c[0]]+1
          q.append([nx,ny])
          m=max(m,D[ny][nx])
print(m)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-


def calc_dist(s, start_i, start_j, h, w):
    from collections import deque

    result = 0
    d = deque()
    d.append((start_i, start_j))
    dist = [[0 for _ in range(w)] for _ in range(h)]
    visited = [[False for _ in range(w)] for _ in range(h)]
    visited[start_i][start_j] = True
    dxy = [(1, 0), (-1, 0), (0, -1), (0, 1)]

    while d:
        hd, wd = d.popleft()

        for dx, dy in dxy:
            nx = wd + dx
            ny = hd + dy

            if nx < 0 or nx >= w or ny < 0 or ny >= h:
                continue

            if s[ny][nx] == '#':
                continue

            if visited[ny][nx]:
                continue

            visited[ny][nx] = True
            dist[ny][nx] = dist[hd][wd] + 1
            d.append((ny, nx))
            result = max(result, dist[ny][nx])

    return result


def main():
    h, w = map(int, input().split())
    s = [list(input()) for _ in range(h)]
    ans = 0

    # KeyInsight
    # 始点のみを全探索(終点は全探索する必要はない)
    # 距離はBFSで計算
    for start_i in range(h):
        for start_j in range(w):
            if s[start_i][start_j] == '#':
                continue

            ans = max(ans, calc_dist(s, start_i, start_j, h, w))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

dX = [1, 0, -1, 0]
dY = [0, 1, 0, -1]

def bfs(m, c):
    q = []
    d = defaultdict(lambda: 0xffffffff)
    q.append(c)
    d[c] = 0
    while len(q) != 0:
        c = q.pop(0)
        for dx, dy in zip(dX, dY):
            nx = dx + c[0]
            ny = dy + c[1]
            if ny < 0 or ny >= len(m):
                continue
            if nx < 0 or nx >= len(m[0]):
                continue
            if m[ny][nx] == "#":
                continue
            if d[(nx, ny)] != 0xffffffff:
                continue
            d[(nx, ny)] = d[c] + 1
            q.append((nx, ny))
    return d

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

maxi = 0
for sx, sy in [(x, y) for x in range(0, W) for y in range(0, H)]:
    if S[sy][sx] == "#":
        continue
    d = bfs(S, (sx, sy))
    for x, y in [(x, y) for x in range(0, W) for y in range(0, H)]:
        if S[y][x] == "#":
            continue
        maxi = max(maxi, d[(x, y)])
print(maxi)

Submission status: Accepted

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

def is_kabe(v1, v2):
    if S[v1][v2] == '#':
        return True
    else:
        return False

def bfs(v1, v2):
    m = []
    for i in range(H):
        m.append([None]*W)

    m[v1][v2] = 0
    q = [[v1, v2]]
    while q:
        mass = q.pop(0)
        # print('mass', mass)
        # print('--', m)
        a = mass[0]
        b = mass[1]
        next_cost = m[a][b] + 1
        if a - 1 >= 0:
            up = m[a-1][b]
            if not is_kabe(a-1, b) and up is None:
                m[a-1][b] = next_cost
                q.append([a-1, b])
        if a + 1 < H:
            down = m[a+1][b]
            if not is_kabe(a+1, b) and down is None:
                m[a+1][b] = next_cost
                q.append([a+1, b])
        if b - 1 >= 0:
            left = m[a][b-1]
            if not is_kabe(a, b-1) and left is None:
                m[a][b-1] = next_cost
                q.append([a, b-1])
        if b + 1 < W:
            right = m[a][b+1]
            if not is_kabe(a, b+1) and right is None:
                m[a][b+1] = next_cost
                q.append([a, b+1])

    # print('---')
    # for i in range(H):
    #     for j in range(W):
    #         if m[i][j] is None:
    #             print('-', end=' ')
    #         else:
    #             print(m[i][j], end=' ')
    #     print()

    mx = 0
    for i in range(H):
        for j in range(W):
            cost = m[i][j]
            if cost is not None:
                mx = max(mx, cost)
    return mx


r = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        x = bfs(i, j)
        r = max(r, x)
print(r)

Submission status: Accepted

Solution code:
import heapq
H,W = map(int,input().split())
S = [0 for i in range(H)]
s = [0,0]
g = [0,0]
for i in range(H):
    S[i] = ["#"] + [j for j in input()] + ["#"]
S = [["#" for i in range(W+2)]] + S + [["#" for i in range(W+2)]]
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]
'''
枠を壁としているので，1 <= i <= H+1, 1<= j <= W+1
dp
'''
def search(x,y):
    if S[x+1][y+1] == "#" : return -1
    else :
        dp = [[-float("inf") for _ in range(W)] for p in range(H)]
        dp[x][y] = 0
        heap = []
        heapq.heapify(heap)
        heapq.heappush(heap,(0,x,y))
        m = 0
        while True :
            if len(heap) == 0 :
                break
            else:
                cost,a,b = heapq.heappop(heap)
                for i in range(4):
                    x_ = a + dx[i]
                    y_ = b + dy[i]
                    if S[x_+1][y_+1] == "#" :
                        continue
                    if dp[x_][y_] != -float("inf") :
                        continue
                    dp[x_][y_] = cost + 1
                    heapq.heappush(heap, (cost + 1, x_, y_))
                    if m < dp[x_][y_] : m = dp[x_][y_]
        return m
ans = 0
for i in range(H):
    for j in range(W):
        if ans < search(i,j):
            ans = search(i,j)
print(ans)

Submission status: Accepted

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

for y in range(H):
  for x in range(W):
    if S[y][x]=="#":
      continue
    D=[[400]*W for i in range(H)]
    D[y][x]=0
    q=[]
    q.append([x,y])
    while len(q)>0:
      c=list(q.pop(0))
      for dx,dy in [[-1,0],[1,0],[0,-1],[0,1]]:
        if c[1]+dy<0 or c[1]+dy>=H:
          continue
        if c[0]+dx<0 or c[0]+dx>=W:
          continue
        if S[c[1]+dy][c[0]+dx]==".":
          if D[c[1]+dy][c[0]+dx]>D[c[1]][c[0]]+1:
            D[c[1]+dy][c[0]+dx]=D[c[1]][c[0]]+1
            q.append([c[0]+dx,c[1]+dy])
    A=[[D[y][x] if D[y][x]!=400 else -1 for x in range(W)] for y in range(H)]
    for i in range(H):
      m=max(m,max(A[i]))
print(m)