Problem:


Score : 400 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 3
...
...
...

Sample Output 1

4

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

Sample Input 2

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

Sample Output 2

10

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



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


Sample output:
4

Submission status: Time Limit Exceeded

Solution code:
import math
import itertools
from collections import deque
import bisect
import heapq

def IN(): return int(input())
def sIN(): return input()
def lIN(): return list(input())
def MAP(): return map(int,input().split())
def LMAP(): return list(map(int,input().split()))
def TATE(n): return [input() for i in range(n)]
ans = 0

def bfs(sx,sy,gx,gy):
    d = [[float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sx, sy))#スタート座標の記録
    d[sx][sy] = 0#スタートからスタートへの最短距離は0

    while que:#中身がなくなるまで
        p = que.popleft()
        if p[0] == gx and p[1] == gy:#ゴールなら終わり
            break
        for m in range(4):#現在地から4方向の移動を考える
            nx = p[0] + dx[m]
            ny = p[1] + dy[m]

            if 0 <= nx < h and 0 <= ny < w:
              if maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                que.append((nx, ny))#↑格子点からでない＆壁でない＆まだ通ってない
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


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

for i in range(h):#sx座標指定0~h-1
  for j in range(w):#sy座標指定0~w-1
    if maze[i][j] == '#':
      continue
    else:
      for k in range(h):#gx座標指定
        for l in range(w):#gy座標指定
          if maze[k][l] == '.':
            ans = max(bfs(i,j,k,l),ans)
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
import itertools
from collections import deque
import bisect
import heapq

def IN(): return int(input())
def sIN(): return input()
def lIN(): return list(input())
def MAP(): return map(int,input().split())
def LMAP(): return list(map(int,input().split()))
def TATE(n): return [input() for i in range(n)]
ans = 0

def bfs(sx,sy,gx,gy):
    d = [[float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sx, sy))#スタート座標の記録
    d[sx][sy] = 0#スタートからスタートへの最短距離は0

    while que:#中身がなくなるまで
        p = que.popleft()
        if p[0] == gx and p[1] == gy:#ゴールなら終わり
            break
        for m in range(4):#現在地から4方向の移動を考える
            nx = p[0] + dx[m]
            ny = p[1] + dy[m]

            if 0 <= nx < h and 0 <= ny < w:
              if maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                que.append((nx, ny))#↑格子点からでない＆壁でない＆まだ通ってない
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


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

for i in range(h):#sx座標指定0~h-1
  for j in range(w):#sy座標指定0~w-1
    for k in range(h):#gx座標指定
      for l in range(w):#gy座標指定
        if maze[i][j] == '.' and maze[k][l] == '.':
          ans = max(bfs(i,j,k,l),ans)
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from scipy.sparse.csgraph import csgraph_from_dense, dijkstra
import numpy as np


def main():
    H, W = list(map(int, input().split()))
    N = H * W
    S = [[0 for line in range(W)] for row in range(H)]
    for i in range(H):
        row = input()
        for j, line in enumerate(row):
            S[i][j] = line

    dp = [[np.inf for j in range(N)] for i in range(N)]
    for i in range(H):
        for j in range(W):
            n = W*i + j
            if j < W-1 and S[i][j] == '.' and S[i][j+1] == '.':
                dp[n][n+1] = dp[n+1][n] = 1
            if i < H-1 and S[i][j] == '.' and S[i+1][j] == '.':
                dp[n][n+W] = dp[n+W][n] = 1

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


    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])
    
    answer = 0
    for i in range(N):
        for j in range(N):
            if answer < dp[i][j] and dp[i][j] != np.inf:
                answer = dp[i][j]
    print(answer)





def main_dijkstra(): # ダイクストラ法を全域に対して探索させた実装
    H, W = list(map(int, input().split()))
    N = H * W
    S = [[line for line in range(W)] for row in range(H)]
    for i in range(H):
        row = input()
        for j, line in enumerate(row):
            S[i][j] = line

    data = np.zeros([N, N])
    for i in range(H):
        for j in range(W):
            n = W * i + j
            if j<W-1 and S[i][j]=='.' and S[i][j+1]=='.':
                data[n][n+1] = data[n+1][n] = 1
            if i<H-1 and S[i][j]=='.' and S[i+1][j]=='.':
                data[n][n+W] = data[n+W][n] = 1

    G = csgraph_from_dense(data)
    answer = 0
    for n in range(N):
        result = dijkstra(G, indices=n)
        result = [x for x in result if x!=np.inf]
        answer = max(answer, max(result))
    print(int(answer))
    pass

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
H, W = map(int, input().split())
 
route = []
for _ in range(H):
  route.append(input())
  
wall = set()
start = set()
for y, r in enumerate(route):
  for x, w in enumerate(r):
    if w == '#':
      wall.add((x, y))
    else:
      start.add((x, y))

score = -1
ssize = [(-1,0),(0,-1),(1,0),(0,1)]
for xy in start:
  d = deque()
  d.append((xy+(0,)))
  step = 0
  already = copy.deepcopy(wall)
  while len(d) > 0:
    now = d.popleft()
    already.add(now[:-1])
    step = now[2]
    for xs, ys in ssize:
      nxt = (now[0]+xs, now[1]+ys)
      if nxt not in already and nxt in start:
        d.append(nxt+(step+1,))
  score = max(step, score)
  
print(score)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
 
route = []
for _ in range(H):
  route.append(input())
  
wall = set()
start = []
for y, r in enumerate(route):
  for x, w in enumerate(r):
    if w == '#':
      wall.add((x, y))
    else:
      start.append((x, y))

score = -1
ssize = [(-1,0),(0,-1),(1,0),(0,1)]
for xy in start:
  d = deque()
  d.append((xy[0],xy[1],0))
  step = 0
  already = set() | wall
  while len(d) > 0:
    now = d.popleft()
    already.add(now[:-1])
    step = now[2]+1
    for xs, ys in ssize:
      x,y = now[0]+xs, now[1]+ys
      if (x, y) not in already and 0 <= x < W and 0 <= y < H:
        d.append((x, y, step))
  score = max(step-1, score)
  
print(score)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
 
route = []
for _ in range(H):
  route.append(input())
  
wall = set()
start = []
for y, r in enumerate(route):
  for x, w in enumerate(r):
    if w == '#':
      wall.add((x, H-y-1))
    else:
      start.append((x, H-y-1))

score = -1
for xy in start:
  d = deque()
  d.append((xy[0],xy[1],0))
  step = 0
  already = set() | wall
  while len(d) > 0:
    now = d.popleft()
    already.add(now[:-1])
    step = now[2]+1
    x,y = now[0]-1, now[1]
    if (x, y) not in already and x >= 0:
      d.append((x, y, step))
    x, y = x+1, y-1
    if (x, y) not in already and y >= 0:
      d.append((x, y, step))
    x, y = x+1, y+1
    if (x, y) not in already and x < W:
      d.append((x, y, step))
    x, y = x-1, y+1
    if (x, y) not in already and y < H:
      d.append((x, y, step))
  score = max(step-1, score)
  
print(score)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())

route = []
for _ in range(H):
  route.append(input())
  
dp = [[0 for _ in range(W)] for __ in range(H)]

wall = set()
start_list = []
for y, r in enumerate(route):
  for x, w in enumerate(r):
    if w == '#':
      wall.add((x, H-y-1))
    else:
      start_list.append((x, H-y-1))

score = -1
for xy in start_list:
  d = deque()
  d.append((xy[0],xy[1],0))
  step = 0
  already = set() | wall
  while len(d) > 0:
    now = d.popleft()
    already.add(now[:-1])
    step = now[2]+1
    x,y = now[0]-1, now[1]
    if (x, y) not in already and x >= 0:
      d.append((x, y, step))
    x, y = x+1, y-1
    if (x, y) not in already and y >= 0:
      d.append((x, y, step))
    x, y = x+1, y+1
    if (x, y) not in already and x < W:
      d.append((x, y, step))
    x, y = x-1, y+1
    if (x, y) not in already and y < H:
      d.append((x, y, step))
  score = max(step-1, score)
  
print(score)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

from collections import deque
def bfs(start, H, W):
    INF = 10 ** 9
    visited = [False] * (H * W)
    q = deque([(start[0], start[1], 0)])
    max_d = 0
    while q:
        (i, j, d) = q.popleft()
        max_d = max(max_d, d)
        visited[i * W + j] = True
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0:
                    continue
                if dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.append((i + dy, j + dx, d + 1))
    return max_d

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

from collections import deque
def bfs(start, H, W):
    visited = [False] * (H * W)
    q = deque([])
    q.append((start[0], start[1], 0))
    max_dist = 0
    while q:
        (i, j, dist) = q.popleft()
        max_dist = max(dist, max_dist)
        visited[i * W + j] = True 
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.append((i + dy, j + dx, dist + 1))
    return max_dist

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

import queue
def bfs(start, H, W):
    visited = [False] * (H * W)
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    max_dist = 0
    while not q.empty():
        (i, j, dist) = q.get()
        max_dist = max(dist, max_dist)
        visited[i * W + j] = True 
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return max_dist

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

def bfs(start, H, W):
    visited = [False] * (H * W)
    import queue
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    max_dist = 0
    while not q.empty():
        (i, j, dist) = q.get()
        max_dist = max(dist, max_dist)
        visited[i * W + j] = True 
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return max_dist

ans = 0
for i in range(H * W):
    start = (i // W, i % W)
    if S[start[0]][start[1]] == '#':
        continue
    ans = max(ans, bfs(start, H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

def bfs(start, H, W):
    visited = [False for _ in range(H * W)]
    import queue
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    max_dist = 0
    while not q.empty():
        (i, j, dist) = q.get()
        max_dist = max(dist, max_dist)
        visited[i * W + j] = True 
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return max_dist

ans = 0
for i in range(H * W):
    start = (i // W, i % W)
    if S[start[0]][start[1]] == '#':
        continue
    ans = max(ans, bfs(start, H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

def bfs(start, goal, H, W):
    visited = [False for _ in range(H * W)]
    import queue
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    while not q.empty():
        (i, j, dist) = q.get()
        if (i, j) == goal:
            return dist
        visited[i * W + j] = True 
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return -1

ans = 0
s = set()
for i in range(H * W):
    start = (i // W, i % W)
    if S[start[0]][start[1]] == '#':
        continue
    for j in range(H * W):
        goal = (j // W, j % W)
        if S[goal[0]][goal[1]] == '#':
            continue
        if start == goal:
            continue
        if (goal, start) in s:
            continue
        ans = max(ans, bfs(start, goal, H, W))
        s.add((start, goal))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

def bfs(start, goal, H, W):
    visited = [False for _ in range(H * W)]
    import queue
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    while not q.empty():
        (i, j, dist) = q.get()
        if (i, j) == goal:
            return dist
        visited[i * W + j] = True 
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return -1

ans = 0
for i in range(H * W):
    start = (i // W, i % W)
    if S[start[0]][start[1]] == '#':
        continue
    for j in range(H * W):
        goal = (j // W, j % W)
        if S[goal[0]][goal[1]] == '#':
            continue
        if start == goal:
            continue
        ans = max(ans, bfs(start, goal, H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

def bfs(start, goal, H, W):
    visited = [False for _ in range(H * W)]
    import queue
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    while not q.empty():
        (i, j, dist) = q.get()
        if (i, j) == goal:
            return dist
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return -1

ans = 0
for i in range(H * W):
    start = (i // W, i % W)
    if S[start[0]][start[1]] == '#':
        continue
    for j in range(H * W):
        goal = (j // W, j % W)
        if S[goal[0]][goal[1]] == '#':
            continue
        if start == goal:
            continue
        ans = max(ans, bfs(start, goal, H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
 
 
from functools import reduce
# from math import *
from fractions import *
H, W = map(int, readline().split())
S = [0 for i in range(H)]
for i in range(H):
    S[i] = readline().decode().strip()

# adj = [[] for _ in range(H * W)]
# for i in range(H):
#     for j in range(W):
#         v = i * W + j
#         if S[i][j] == '.':
#             for dx in range(-1, 2):
#                 for dy in range(-1, 2):
#                     if dx * dy != 0 or dx == dy:
#                         continue
#                     if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
#                         continue
#                     if S[i + dy][j + dx] == '#':
#                         continue
#                     u = (i + dy) * W + j + dx
#                     adj[v].append(u)
# print(adj)



def bfs(start, goal, H, W):
    visited = [False for _ in range(H * W)]
    import queue
    q = queue.Queue()
    q.put((start[0], start[1], 0))
    while not q.empty():
        (i, j, dist) = q.get()
        if (i, j) == goal:
            return dist
        for dy in range(-1, 2):
            for dx in range(-1, 2):
                if dx * dy != 0 or dx == dy:
                    continue
                if i + dy < 0 or i + dy >= H or j + dx < 0 or j + dx >= W:
                    continue
                if S[i + dy][j + dx] == '#':
                    continue
                if visited[(i + dy) * W + j + dx]:
                    continue
                q.put((i + dy, j + dx, dist + 1))
    return -1

ans = 0
for i in range(H * W):
    start = (i // W, i % W)
    if S[start[0]][start[1]] == '#':
        continue
    for j in range(H * W):
        goal = (j // W, j % W)
        if S[goal[0]][goal[1]] == '#':
            continue
        if start == goal:
            continue
        ans = max(ans, bfs(start, goal, H, W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
maze = []
from collections import deque
for _ in range(H):
    s = list(input())
    maze.append(s)
direction = [[1,0],[0,1],[-1,0],[0,-1]]
ans = -1
for row in range(H):
    for col in range(W):
        if maze[row][col] == "#":
            continue
        distance = [[-1 for _ in range(W)] for _ in range(H)]
        d = deque([[row,col]])
        distance[row][col] = 0
        while(len(d)>0):
            nowrow, nowcol = d.popleft()
            for subrow, subcol in direction:
                subrow += nowrow
                subcol += nowcol
                if subrow < 0 or subrow >= H or subcol < 0 or subcol >= W:
                    continue
                if maze[subrow][subcol] == "#":
                    continue
                if distance[subrow][subcol] != -1:
                    continue
                d.append([subrow, subcol])
                distance[subrow][subcol] = distance[nowrow][nowcol] + 1
            ans = max(ans,max([max(maxrow) for maxrow in distance]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    H, W = LI()
    s = []
    for _ in range(H):
        s.append(S())
    ans = 0
    def bfs(sr, sc, gr, gc):
        q = deque([(sr, sc, 0)])
        visited = set()
        while q:
            cr, cc, dist = q.popleft()
            if s[cr][cc] == '#':
                continue
            if cr == gr and cc == gc:
                return dist
            visited.add((cr, cc))
            for dr, dc in zip(DR, DC):
                nr = cr + dr
                nc = cc + dc
                if not (0 <= nr < H and 0 <= nc < W):
                    continue
                if (nr, nc) in visited:
                    continue
                q.append((nr, nc, dist+1))


    for row in range(H):
        for col in range(W):
            for row2 in range(H):
                for col2 in range(W):
                    sr, sc = row, col
                    gr, gc = row2, col2
                    if s[sr][sc] == '.' and s[gr][gc] == '.':
                        ans = max(ans, bfs(sr,sc,gr,gc))
    print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
S = [input() for i in range(H)]
l = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            l.append((i, j))

m = -1
N = len(l)
for i in range(N-1):
    for j in range(i+1, N):
        start = l[i]
        goal = l[j]
        visited = [[-1]*W for i in range(H)]
        d = deque()
        d.appendleft(start)
        visited[start[0]][start[1]] = 0
        while d:
            now = d.pop()
            for direction in directions:
                next = (now[0]+direction[0], now[1]+direction[1])
                if not (next[0] in range(H) and next[1] in range(W)):
                    continue
                if visited[next[0]][next[1]] != -1:
                    continue
                if S[next[0]][next[1]] == '.':
                    visited[next[0]][next[1]] = visited[now[0]][now[1]] + 1
                    d.appendleft(next)

        m = max(visited[goal[0]][goal[1]], m)

print(m)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
S = [input() for i in range(H)]
l = []
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

for i in range(H):
    for j in range(W):
        if S[i][j] == '.':
            l.append((i, j))

m = -1
for start in l:
    for goal in l:
        visited = [[-1]*W for i in range(H)]
        d = deque()
        d.appendleft(start)
        visited[start[0]][start[1]] = 0
        while d:
            now = d.pop()
            for direction in directions:
                next = (now[0]+direction[0], now[1]+direction[1])
                if not (next[0] in range(H) and next[1] in range(W)):
                    continue
                if visited[next[0]][next[1]] != -1:
                    continue
                if S[next[0]][next[1]] == '.':
                    visited[next[0]][next[1]] = visited[now[0]][now[1]] + 1
                    d.appendleft(next)

        m = max(visited[goal[0]][goal[1]], m)

print(m)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
h,w = map(int,input().split())
origin = []
dx = [1,-1,0,0]
dy = [0,0,1,-1]
ans = 0
for i in range(h):
    origin.append(list(input()))
for i in range(h):
    for j in range(w):
        if origin[i][j] == ".":
            d = [[0 for j in range(w)] for i in range(h)]
            maze = copy.deepcopy(origin)
            dq = deque([(j,i)])
            while dq:
                x,y = dq.popleft()
                for k in range(4):
                    nx = x + dx[k]
                    ny = y + dy[k]
                    if 0<=nx<=w-1 and 0<=ny<=h-1 and maze[ny][nx] != "#":
                        dq.append((nx,ny))
                        d[ny][nx] = d[y][x]+1
                        ans = max(ans,d[ny][nx])
                maze[y][x] = "#"
            #print(maze)
print(ans)

Submission status: Time Limit Exceeded

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

M = []
for i in range(H):
    M.append(list(input()))

from collections import deque

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

for sx in range(0,W):
    for gx in range(0,W):
        for sy in range(0,H):
            for gy in range(0,H):
                if M[sy][sx]=="#":
                    continue
                if (sx==gx)and(sy==gy):
                    continue
                d = [[10**4] * W for i in range(H)]
                que = deque([])
                que.append((sy, sx))
                d[sy][sx] = 0
                while que:
                    p = que.popleft()
                    if p[0] == gy and p[1] == gx:
                        break
                    for i in range(4):
                        ny = p[0] + dy[i]
                        nx = p[1] + dx[i]
                        if (0<=nx<W)and(0<=ny<H)and(M[ny][nx]!="#")and(d[ny][nx]==10**4):
                            que.append((ny, nx))
                            d[ny][nx] = d[p[0]][p[1]] + 1
                if out < d[gy][gx] and M[gy][gx]!="#":
                    out=d[gy][gx]
print(out)