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())
grid = [input() for _ in range(h)]

ans = 0

for i in range(h):
    for j in range(w):
        if grid[i][j] == ".":
            q = [(i, j)]
            dist = [[-1]*w for _ in range(h)]
            dist[i][j] = 0
            while q:
                x, y = q.pop(0)
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nx, ny = x+dx, y+dy
                    if not (nx in range(h) and ny in range(w)):
                        continue
                    if grid[nx][ny] == "#":
                        continue
                    if dist[nx][ny] == -1:
                        dist[nx][ny] = dist[x][y] + 1
                        q.append((nx, ny))
            ans = max(ans, max([max([j for j in i]) for i in dist]))

print(ans)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
grid = [input() for _ in [0]*h]

ans = 0

for i in range(h):
    for j in range(w):
        if grid[i][j] == ".":
            q = [(i, j)]
            dist = [[-1]*w for _ in [0]*h]
            dist[i][j] = 0
            while q:
                x, y = q.pop(0)
                for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    nx, ny = x+dx, y+dy
                    if not (nx in range(h) and ny in range(w)):
                        continue
                    if grid[nx][ny] == "#":
                        continue
                    if dist[nx][ny] == -1:
                        dist[nx][ny] = dist[x][y] + 1
                        q.append((nx, ny))
            ans = max(ans, max([max([j for j in i]) for i in dist]))

print(ans)

Submission status: Accepted

Solution code:
h, w = map(int, input().split())
lmap = [[0] * w for i in range(h)]
inf = 2**31-1
for i in range(h):
    s = input()
    for j in range(w):
        if s[j] == "#":
            lmap[i][j] = 1
        else:
            lmap[i][j] = 0


def bfs(i, j):
    que = []
    que.append([i, j])
    dmap = [[inf] * w for i in range(h)]
    dmap[i][j] = 0
    dmax = 0

    vec = [[-1, 0], [1, 0], [0, -1], [0, 1]]

    while len(que) > 0:
        pt = que.pop(0)
        # print(pt)
        for v in vec:
            y = pt[0] + v[0]
            x = pt[1] + v[1]
            if x >= 0 and x < w and y >= 0 and y < h and lmap[y][x] == 0 and dmap[y][x] == inf:
                que.append([y, x])
                d = dmap[pt[0]][pt[1]] + 1
                dmax = max(dmax, d)
                dmap[y][x] = d

    # print(dmap)
    return dmax


ans = 0
for i in range(h):
    for j in range(w):
        if lmap[i][j] == 0:
            r = bfs(i, j)
            # print(r)
            ans = max(r, ans)

print(ans)

Submission status: Accepted

Solution code:
import collections

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


def bfs(i, j):
    global h, w, r
    f = [-1 for _ in range(h * w)]
    que = [[] for _ in range(h * w)]
    que[0].append([i, j])
    for k in range(h * w):
        if que[k]:
            res = k
            for i, j in que[k]:
                f[i * w + j] = k
                for sr in r:
                    ti = i + sr[0]
                    tj = j + sr[1]
                    if ti >= 0 and tj >= 0 and ti < h and tj < w:
                        if s[ti][tj] == ".":
                            if f[ti * w + tj] == -1:
                                que[k + 1].append([ti, tj])
    return res


fl = 0
for i in range(h):
    if "#" in s[i]:
        fl = 1
        break
if fl == 0:
    print(h + w - 2)
else:
    res = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] == ".":
                res = max(res, bfs(i, j))
    print(res)

Submission status: Accepted

Solution code:
from collections import deque
import copy

def BFS(h,w,sy,sx,xy_list):
 dist=[[-1]*w for i in range(h)]
 dist[sy][sx]=0
 xy_list[sy][sx]='#'

 dq=deque()
 dq.append((sy,sx))

 while dq:
  y,x=dq.popleft()
  for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
   ny=y+dy
   nx=x+dx
   if 0<=ny<h and 0<=nx<w and xy_list[ny][nx]!='#':
    dq.append((ny,nx))
    xy_list[ny][nx]='#'
    dist[ny][nx]=dist[y][x]+1

 return dist

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

 ans=0
 for hh in range(h):
  for ww in range(w):
   if s[hh][ww]=='#':
    continue
   xy_list=copy.deepcopy(s)
   dist=BFS(h,w,hh,ww,xy_list)
   for d in dist:
    ans=max(ans,max(d))

 print(ans)

if __name__=="__main__":
  main()

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
S = [list(input()) for _ in range(h)]
INF = 10010001001
way = [[0, 1], [0, -1], [1, 0], [-1, 0]]

ans = 0
for sy in range(h):
    for sx in range(w):
        dist = [[INF] * w for _ in range(h)]
        dist[sy][sx] = 0
        if S[sy][sx] == '#':
            continue
        q = deque()
        q.append((sy, sx))
        while q:
            y, x = q.popleft()
            for dy, dx in way:
                ny, nx = y + dy, x + dx
                if 0 <= ny <= h - 1 and 0 <= nx <= w - 1 and S[ny][nx] == '.' and dist[ny][nx] == INF:
                    dist[ny][nx] = dist[y][x] + 1
                    ans = max(ans, dist[y][x] + 1)
                    q.append((ny, nx))
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline
H,W=map(int,input().rstrip().split())
maze=[list(input().rstrip()) for i in range(H)]
def resolve():
    seen=[[0 for i in range(W)] for j in range(H)]
    ans=0
    for i in range(H):
        for j in range(W):
            if maze[i][j]=="#":
                continue
            #maze[k][l]=1#end
            buf=bfs(maze,seen,i,j)
            ans=max(ans,buf)
            seen = [[0 for i in range(W)] for j in range(H)]
            #maze[k][l]="."
    print(ans)

def bfs(maze, seen, sh, sw): #sh,swはスタート
    stack = deque([[sh, sw]])
    seen[sh][sw] = 1
    expandcount=0#今のdepthに展開されたノードを親ノードとしたときの子ノードの数
    expanded=-1#今のdepthに展開されたノード数、最初は-1にする
    popcount=0#popした数、今のdepthでの探索回数
    depth=0#ルートからの深さ
    while stack:
        h, w = stack.popleft()
        popcount+=1
        
        for j, k in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_h, new_w = h+j, w+k
            if new_h < 0 or new_h >= H or new_w < 0 or new_w >= W:
                continue

            elif maze[new_h][new_w] != "#" and  seen[new_h][new_w] == 0:#未発見
                seen[new_h][new_w] = 1#発見済みにする
                stack.append([new_h, new_w])#隣接を探索予定に
                expandcount+=1

        if popcount==expanded or expanded==-1:#今のdepthが全て探索済みなら、下のdepthの探索に移る
            expanded=expandcount
            popcount=0
            expandcount=0
            depth+=1

    return depth-1
"""
    for i in range(H):
        for j in range(W):
            if(S[i][j]=="#"):
                for dir in range(4):
                    nx=j+dx[dir]
                    ny=i+dy[dir]

                    if(nx<0 or nx>=W):
                        continue
                    if(ny<0 or ny>=H):
                        continue

                    if(S[i][j]==S[ny][nx]):
                        break
                else:
                    print("No")
                    return
    print("Yes")
"""
import sys
from io import StringIO
import unittest

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)
    def test_入力例_1(self):
        input = """3 3
...
...
..."""
        output = """4"""
        self.assertIO(input, output)
    def test_入力例_2(self):
        input = """3 5
...#.
.#.#.
.#..."""
        output = """10"""
        self.assertIO(input, output)

if __name__ == "__main__":
    #unittest.main()
    resolve()

Submission status: Accepted

Solution code:
import queue
import sys

input = sys.stdin.readline


class Solution:
    def main(self):
        H, W = map(int, input().split())
        S = [list(input().rstrip()) for _ in range(H)]

        for i in range(H):
            S[i] = ["#"] + S[i] + ["#"]
        S = [["#"] * (W + 2)] + S + [["#"] * (W + 2)]

        ans = 0
        for i in range(1, H + 1):
            for j in range(1, W + 1):
                if S[i][j] == "#":
                    continue
                v = self.min_move(S, (i, j))
                ans = max(ans, v)
        print(ans)

    def min_move(self, map, start):
        moving_range = ((1, 0), (-1, 0), (0, 1), (0, -1))

        q = queue.Queue()
        q.put((start, 0))

        already = {start}
        ret = 0
        while not q.empty():
            pos, cnt = q.get()
            ret = max(ret, cnt)
            for move in moving_range:
                i, j = pos[0] + move[0], pos[1] + move[1]
                if (i, j) not in already and map[i][j] == ".":
                    q.put(((i, j), cnt + 1))
                    already.add((i, j))

        return ret


# Run main
if __name__ == '__main__':
    Solution().main()

Submission status: Accepted

Solution code:
from collections import deque
h, w = map(int, input().split())
S = [list(input()) for _ in range(h)]
INF = 10010001001
way = [[0, 1], [0, -1], [1, 0], [-1, 0]]

ans = 0
for sy in range(h):
    for sx in range(w):
        dist = [[INF] * w for _ in range(h)]
        dist[sy][sx] = 0
        if S[sy][sx] == '#':
            continue
        q = deque()
        q.append((sy, sx))
        while len(q):
            y, x = q.popleft()
            for dy, dx in way:
                ny, nx = y + dy, x + dx
                if not (0 <= ny <= h - 1 and 0 <= nx <= w - 1):
                    continue
                if S[ny][nx] == '#' or dist[ny][nx] != INF:
                    continue
                dist[ny][nx] = dist[y][x] + 1
                q.append((ny, nx))
        for yy in range(h):
            for xx in range(w):
                if dist[yy][xx] == INF:
                    continue
                else:
                    ans = max(ans, dist[yy][xx])
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import copy

def BFS(sy,sx,xy_list):
 dist=[[-1]*w for i in range(h)]
 dist[sy][sx]=0
 xy_list[sy][sx]='#'

 dq=deque()
 dq.append((sy,sx))

 while dq:
  y,x=dq.popleft()
  for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]:
   ny=y+dy
   nx=x+dx
   if 0<=ny<h and 0<=nx<w and xy_list[ny][nx]!='#':
    dq.append((ny,nx))
    xy_list[ny][nx]='#'
    dist[ny][nx]=dist[y][x]+1

 return dist

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

ans=0
for hh in range(h):
 for ww in range(w):
  if s[hh][ww]=='#':
   continue
  xy_list=copy.deepcopy(s)
  dist=BFS(hh,ww,xy_list)
  for d in dist:
   ans=max(ans,max(d))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

max = 0

tmp = []
tmp = list(map(int, input().split()))

w = tmp.pop()
h = tmp.pop()

maze = [["." for i in range(w)] for j in range(h)]

for i in range(h):
    maze[i] = list(input())

xq = deque()
yq = deque()
lq = deque()
    
for i in range(w):
    for j in range(h):

        flag = [[False for i in range(w)] for j in range(h)]
        #        print("{} {} {}".format(j,i, maze[j][i]))
        # start が壁でなければqueueにいれる
        if maze[j][i]==".":
            xq.appendleft(i)
            yq.appendleft(j)
            lq.appendleft(0)
            flag[j][i]=True

        while not len(xq)==0:
            x = xq.pop() #現在地 x
            y = yq.pop() #現在地 y
            l = lq.pop() #距離 l

            if max < l:
                max = l
            
            #行ける方向をチェックしてqueueにつむ、訪問済みにする
            #行ける方向 = 上下左右隣接、
            # なおかつ、壁じゃない、迷路の外じゃない、すでに訪問済みじゃない

            # チェックするのは4方向
            if ((x-1) >= 0 ):
                if (flag[y][x-1]==False) and (maze[y][x-1])==".":
                    xq.appendleft(x-1)
                    yq.appendleft(y)
                    lq.appendleft(l+1)
                    flag[y][x-1]=True
                
            if ((x+1) < w ):
#                print("{} {} {}".format(x, y, l))
#                print(maze[x][y])
                if flag[y][x+1]==False and maze[y][x+1]==".":
                    xq.appendleft(x+1)
                    yq.appendleft(y)
                    lq.appendleft(l+1)
                    flag[y][x+1]=True
                
            if ((y-1) >= 0):
                if flag[y-1][x]==False and maze[y-1][x]==".":
                    xq.appendleft(x)
                    yq.appendleft(y-1)
                    lq.appendleft(l+1)
                    flag[y-1][x]=True

            if ((y+1) < h):
#                print("{} {} {}".format(x, y, l))
#                print(maze[x][y])
                if flag[y+1][x]==False and maze[y+1][x]==".":
                    xq.appendleft(x)
                    yq.appendleft(y+1)
                    lq.appendleft(l+1)
                    flag[y+1][x]=True
                

print(max)

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


@mt
def slv(H, W, S):
    def edges(v):
        i, j = v
        r = []
        if i > 0 and S[i-1][j] == '.':
            r.append((i-1, j))

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

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

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

        return r

    def bfs(s):
        q = deque([s])
        d = {s: 0}
        while q:
            u = q.popleft()
            for v in edges(u):
                if v not in d:
                    d[v] = d[u] + 1
                    q.append(v)
        return max(d.values())

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


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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque
def input(): return sys.stdin.readline().rstrip()

def main():
    H, W = map(int, input().split())
    S = [['#'] * (W+2)] + [['#'] + list(input()) + ['#'] for _ in range(H)] + [['#'] * (W+2)]
    direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]

    ans = 0
    for i in range(1, H + 1):
        for j in range(1, W + 1):
            if S[i][j] == '#':
                continue
            init = (i, j)
            que = deque()
            que.append(init)
            dist = [[-1 for _ in range(W+2)] for _ in range(H+2)]
            dist[i][j] = 0

            while que:
                qh, qw = que.popleft()
                for dh, dw in direction:
                    h = qh + dh
                    w = qw + dw
                    if S[h][w] == '#' or dist[h][w] >= 0:
                        continue
                    dist[h][w] = dist[qh][qw] + 1
                    que.append((h, w))
            ans = max(ans, max([max(i) for i in dist]))
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

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


def bfs(sy, sx):
    num_table = [[-1]*w for _ in range(h)]
    # start地点を0とする
    num_table[sy][sx] = 0
    # queueを定義する
    queue = deque([[sy, sx]])
    # queueに値が入っている間loopを回す
    while queue:
        # 左から一つづつ取り出す
        y, x = queue.popleft()
        for dy, dx in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            ny, nx = y + dy, x + dx
            if 0 <= ny < h and 0 <= nx < w and maze[ny][nx] == '.' and num_table[ny][nx] == -1:
                # チェックしたポイントは隣の数値+1する
                num_table[ny][nx] = num_table[y][x] + 1
                m = num_table[ny][nx]
                # 新規にqueueに追加する
                queue.append([ny, nx])
    return m


ans = 0
# start地点を全てのマスにおいてbfsする
for y in range(h):
    for x in range(w):
        if maze[y][x] == ".":
            ans = max(ans, bfs(y, x))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
a = ['#' + input() + '#' for _ in range(h)]
b = ['#' * (w + 1)] * 2
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
a = ['#' + input() +  '#' for _ in range(h)]
b = ['#' * (w + 1)] * 2
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
a = [input() for _ in range(h)]
b = ['#' * (w + 1)] * 2
b[1: - 1] = [['#', '#'] for _ in range(h)]
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j - 1] == '.':
      for x, y in zip(a, b[1:]):
        y[1: -1] = x
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
import queue
import copy
D = ((0, -1), (0, 1), (-1, 0), (1, 0))

def bfs(S, s):
    M = copy.deepcopy(S)
    M[s[1]][s[0]] = '#'
    q = queue.Queue()
    q.put((s[0], s[1], 0))
    dis = 0

    while not q.empty():
        cur = q.get()

        for d in D:
            x = cur[0] + d[0]
            y = cur[1] + d[1]
            if M[y][x] != '#':
                M[y][x] = '#'
                q.put((x, y, cur[2]+1))
                dis = max(dis, cur[2]+1)

    return dis


H, W = map(int, input().split())
S = [None]*(H+2)

S[0] = ['#'] * (W + 2)
for h in range(1, H+1):
    S[h] = ['#'] + [c for c in input()] + ['#']
S[-1] = ['#'] * (W + 2)

ans = 0
for sy in range(1, H+1):
    for sx in range(1, W+1):
        if S[sy][sx] != '#':
            ans = max(ans, bfs(S, (sx, sy)))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
 
h, w = map(int, input().split())
a = ['#' + input() +  '#' for _ in range(h)]
b = ['#' * (w + 1)] * 2
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -1] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
from collections import deque
 
h, w = map(int, input().split())
a = ['#' * (w + 2)] * 2
a[1: 1] = ['#' + input() +  '#' for _ in range(h)]
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

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

INF = 10**9 + 7


def to_graph(maze):
    H, W = len(maze), len(maze[0])

    g = [[INF] * (H * W) for _ in range(H * W)]

    for i, line in enumerate(maze):
        for j, s in enumerate(line):
            if i == j:
                g[i * W + j][i * W + j] = 0
            if s == '.':
                for neigh in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                    px, py = i + neigh[0], j + neigh[1]
                    if maze[px][py] == '.':
                        g[i * W + j][px * W + py] = 1

    return g


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

    g = to_graph(maze)

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

    current_max = 0
    for i, line in enumerate(g):
        for j, v in enumerate(line):
            if i != j and v < INF and v > current_max:
                current_max = v

    print(current_max)


if __name__ == '__main__':
    main()

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
H,W=map(int,input().split())
S=[input() for i in range(H)]
ans=0
for i in range(H):
    for j in range(W):
        if S[i][j]=="#":
            continue
        st=(i,j)
        q=deque([st])
        dx=[1,-1,0,0]
        dy=[0,0,1,-1]
        dist=[[-1 for j in range(W)] for i in range(H)]
        dist[st[0]][st[1]]=0
        while(len(q)>0):
            r=q.popleft()
            x,y=r
            for k in range(4):
                nx=x+dx[k]
                ny=y+dy[k]
                if 0<=nx<H and 0<=ny<W:
                    if dist[nx][ny]==-1 and S[nx][ny]==".":
                        dist[nx][ny]=dist[x][y]+1
                        q.append((nx,ny))
        tmp=max([max(i) for i in dist])
        ans=max(tmp,ans)
print(ans)

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something : print(*something) if DEBUG else 0
DEBUG = False
def main(given = sys.stdin.readline):
    input = lambda : given().rstrip()
    LMIIS = lambda : list(map(int,input().split()))
    II = lambda : int(input())
    XLMIIS = lambda x : [LMIIS() for _ in range(x)]


    H,W = LMIIS()
    MOD = H*W
    S = [input() for _ in range(H)]

    from collections import deque
    def tansaku(S,V,length,q):
        if len(q) == 0:
            return length-1
        q2 = []
        for y,x in q:
            if  x >= 1 and S[y][x-1] == '.' and V[y][x-1]:
                V[y][x-1] = False
                q2.append((y,x-1))

            if x < W-1 and S[y][x+1] == '.' and V[y][x+1]:
                V[y][x+1] = False
                q2.append((y,x+1))

            if y >= 1 and S[y-1][x] == '.' and V[y-1][x]:
                V[y-1][x] = False
                q2.append((y-1,x))

            if y < H-1 and S[y+1][x] == '.' and V[y+1][x]:
                V[y+1][x] = False
                q2.append((y+1,x))

        return tansaku(S,V,length+1,q2)
    
    def getmax():
        max_length = 0
        for h in range(H):
            for w in range(W):
                V = [[True] * W for _ in range(H)]
                if S[h][w] == '.':
                    V[h][w] = False
                    max_length = max(tansaku(S,V,0,[(h,w)]),max_length)
        return max_length
    
    print(getmax())
   
    






if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
a = ['#' + input() +  '#' for _ in range(h)]
b = ['#' * (w + 2)] * 2
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i - 1][j] == '.':
      b[1: -2] = map(list, a)
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
a = ['#' * (w + 2)] * 2
a[1: 1] = ['#' + input() +  '#' for _ in range(h)]
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
from collections import deque

h, w = map(int, input().split())
a = ['#' * (w + 2)] * 2
a[1: 1] = ('#' + input() +  '#' for _ in range(h))
r = 0
for i in range(1, h + 1):
  for j in range(1, w + 1):
    if a[i][j] == '.':
      b = list(map(list, a))
      q = deque()
      b[i][j] = 0
      q.append((i, j))
      while(q):
        i, j = q.popleft()
        r = max(r, b[i][j])
        d = 0
        for i1 in range(i - 1, i + 2):
          for j1 in range(j - d, j + 2, 2):                
            if b[i1][j1] == '.':
              b[i1][j1] = b[i][j] + 1
              q.append((i1, j1))
          d ^= 1
print(r)

Submission status: Accepted

Solution code:
from collections import deque

def bfs(h, w):
    q = deque([[h, w]])
    dist[h][w] = 0

    while len(q) != 0:
        y, x = q.popleft()

        for step in steps:
            nx = x + step[0]
            ny = y + step[1]
            if nx < 0 or nx >= W or ny < 0 or ny >= H:
                continue
            if maze[ny][nx] == "#":
                continue
            if dist[ny][nx] != -1:
                continue
            dist[ny][nx] = dist[y][x] + 1
            q.append([ny, nx])


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

steps = [[1, 0], [0, 1], [-1, 0], [0, -1]]
max_dist = [[0]*W for _ in range(H)]

for h in range(H):
    for w in range(W):
        if maze[h][w] == "#":
            continue
        dist = [[-1]*W for _ in range(H)]
        bfs(h, w)
        for row in dist:
            for d in row:
                max_dist[h][w] = max(max_dist[h][w], d)

ans = 0
for row in max_dist:
    for d in row:
        ans = max(ans, d)

print(ans)

Submission status: Accepted

Solution code:
from collections import deque

H,W=map(int, input().split())
S=[list(input()) for i in range(H)]
INF=10**6
M=[[10**6]*W for i in range(H)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

def bfs(y,x):
  q=deque()
  q.append((y,x))
  
  while len(q):
    y,x=q.popleft()
    
    for i in range(4):
      ny=y+dy[i]
      nx=x+dx[i]
      if (0<=ny<H and 0<=nx<W and M[ny][nx]==INF and S[ny][nx]!='#'):
        q.append((ny, nx))
        M[ny][nx] = M[y][x]+1      
    
ans=0
for y in range(H):
  for x in range(W):
    if S[y][x]!='#':      
      M=[[10**6]*W for i in range(H)]
      M[y][x]=0
      bfs(y,x)
      for i in range(H):
        for j in range(W):
          if M[i][j]!=INF:
            ans=max(ans,M[i][j])
print(ans)