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:
from collections import deque


# (sx, sy) から (gx, gy) への最短距離を求める
# 辿り着けないと INF
def bfs():
    # すべての点を INF で初期化
    d = [[float("inf")] * m for i in range(n)]

    # 移動4方向のベクトル
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]



    # スタート地点をキューに入れ、その点の距離を0にする
    que = deque([])
    que.append((sx, sy))
    d[sx][sy] = 0

    # キューが空になるまでループ
    while que:
        # キューの先頭を取り出す
        p = que.popleft()
        # 取り出してきた状態がゴールなら探索をやめる
        if p[0] == gx and p[1] == gy:
            break
        # 移動4方向をループ
        for i in range(4):
            # 移動した後の点を (nx, ny) とする
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

            # 移動が可能かの判定とすでに訪れたことがあるかの判定
            # d[nx][ny] != INF なら訪れたことがある
            if 0 <= nx < n and 0 <= ny < m and maze[nx][ny] != "#" and d[nx][ny] == float("inf"):
                # 移動できるならキューに入れ、その点の距離を p からの距離 +1 で確定する
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    return d[gx][gy]


n, m = map(int, input().split())
maze = [list(input()) for i in range(n)]
ans = 0
for sx in range(n):
    for sy in range(m):
        for gx in range(n):
            for gy in range(m):
                if maze[sx][sy] == '.' and maze[gx][gy] == '.' and not (sx == gx and sy == gy):
                    if bfs() != float('inf'):
                        ans = max(ans,bfs())
print(ans)

Submission status: Time Limit Exceeded

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

d_max = 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

    while que:
        p = que.popleft()
        if p[0] == gx and p[1] == gy:
            break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]

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

    if d[gx][gy] == float("inf"):
        return 0
    else:
        return d[gx][gy]

for i in range(h):
    for j in range(w):
        for k in range(h):
            for l in range(w):
                d_min = bfs(i,j,k,l)
                if d_max < d_min:
                    d_max = d_min
print(d_max)

Submission status: Time Limit Exceeded

Solution code:
import queue

def solve(maze, start):
    if maze[start[0]][start[1]] == '#':
        return 0

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

    h = len(maze)
    w = len(maze[0])

    memo = [[False] * w for _ in range(h)]

    ans = 0

    while not q.empty():
        p, i = q.get()

        if not memo[p[0]][p[1]]:
            memo[p[0]][p[1]] = True
            ans = i
        else:
            continue

        if p[0] < h-1 and maze[p[0] + 1][p[1]] == '.':
            q.put(((p[0] + 1, p[1]), i + 1))

        if p[0] > 0 and maze[p[0] - 1][p[1]] == '.':
            q.put(((p[0] - 1, p[1]), i + 1))

        if p[1] < w-1 and maze[p[0]][p[1] + 1] == '.':
            q.put(((p[0], p[1] + 1), i + 1))

        if p[1] > 0 and maze[p[0]][p[1] - 1] == '.':
            q.put(((p[0], p[1] - 1), i + 1))

    return ans


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

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

ans = 0
for i in range(h):
    for j in range(w):
        ans = max(ans, solve(maze, (i, j)))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
h,w = map(int, input().split())
s = [input() for _ in range(h)]

if h==1 and w==1:
    print(0)
    exit()

def solve(sh,sw,gh,gw):
    if s[sh][sw]=="#" or s[gh][gw]=="#":
        return -1

    visited = [[False for _ in range(w)] for _ in range(h)]
    visited[sh][sw] = True
    q = [(sh,sw,0)]
    while len(q)>0:
        hi,wi,r = q.pop(0)
        for dh,dw in [[1,0],[0,1],[-1,0],[0,-1]]:
            if hi+dh>=0 and hi+dh<h and wi+dw>=0 and wi+dw<w and s[hi+dh][wi+dw]==".":
                if hi+dh==gh and wi+dw==gw:
                    return r+1
                elif not visited[hi+dh][wi+dw]:
                    visited[hi+dh][wi+dw] = True
                    q.append((hi+dh,wi+dw,r+1))

    return -1

res = -1
for shi in range(h):
    for swi in range(w):
        if s[shi][swi]=="#":
            continue
        for ghi in range(h):
            for gwi in range(w):
                if shi>=ghi and swi>=gwi:
                    continue
                r = solve(shi,swi,ghi,gwi)
                res = max(res, r)

print(res)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())

INF = 10 ** 18
grid = [input() for _ in range(h)]

ans = 0
for sy in range(h):
    for sx in range(w):
        if grid[sy][sx] == ".":
            for gy in range(h):
                for gx in range(w):
                    if sx == gx and sy == gy:
                        continue
                    if grid[gy][gx] == ".":

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

print(ans)

Submission status: Time Limit Exceeded

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

g = []
for i in range(w * h):
    g.append([10000000] * (w * h))

for i in range(w * h):
    g[i][i] = 0

for i in range(h):
    for j in range(w):
        if maze[i][j] == '#':
            continue
        if maze[i][j] == '.':
            if i > 0 and maze[i-1][j] != '#':
                g[i * w + j][(i-1) * w + j] = 1
                g[(i-1) * w + j][i * w + j] = 1
            if i < h-1 and maze[i+1][j] != '#':
                g[i * w + j][(i+1) * w + j] = 1
                g[(i+1) * w + j][i * w + j] = 1
            if j > 0 and maze[i][j-1] != '#':
                g[i * w + j][i * w + j-1] = 1
                g[i * w + j-1][i * w + j] = 1
            if j < w-1 and maze[i][j+1] != '#':
                g[i * w + j][i * w + j+1] = 1
                g[i * w + j+1][i * w + j] = 1

def floyed(g, h, w):
    for k in range(h*w):
        for i in range(h*w):
            for j in range(h*w):
                if i == j or i == k or k == j:
                    continue
                if g[i][j] > g[i][k] + g[k][j]:
                    g[i][j] = g[i][k] + g[k][j]

floyed(g,h,w)
result = 0

for i in range(w*h):
    for j in range(w*h):
        if g[i][j] < 10000000:
            if g[i][j] > result:
                result = g[i][j]

print(result)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import queue
import copy


def calc_dist(S, points, p_s, p_e):
    h, w = len(S), len(S[0])
    distance = {p: -1 for p in points}
    que = queue.Queue()
    que.put((p_s, 0))
    while not que.empty():
        p, d = que.get()
        y, x = p

        if not (0 <= x < w and 0 <= y < h):
            continue
        if S[y][x] == '#':
            continue

        if distance[p] != -1:
            continue

        distance[p] = d
        if p == p_e:
            break

        que.put(((y, x - 1), d + 1))
        que.put(((y, x + 1), d + 1))
        que.put(((y - 1, x), d + 1))
        que.put(((y + 1, x), d + 1))
    
    # print(p_s, p_e, distance[p_e])
    # Svis = copy.deepcopy(S)
    # Svis[p_s[0]][p_s[1]] = 'S'
    # Svis[p_e[0]][p_e[1]] = 'E'
    # for e in Svis:
    #     print(''.join(e))
    return distance[p_e]


def main():
    h, w = map(int, input().split())

    S = list()
    for y in range(h):
        S.append(list(input()))
    points = [(y, x) for y, x in itertools.product(range(h), range(w)) if S[y][x] == '.']

    # print(calc_dist(S, points, (0, 2), (1, 0)))
    distance = list()
    for p_s, p_e in itertools.combinations(points, 2):
        d = calc_dist(S, points, p_s, p_e)
        distance.append(d)

    print(max(distance))


main()

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 solve(maze, st_tuple, g_tuple):
    st_row, st_col = st_tuple
    g_row, g_col = g_tuple
    W, H = len(maze[0]), len(maze)
    visited = [[0 for _ in range(W)] for __ in range(H)]
    q = deque()
    q.append((st_row, st_col, 0))
    while q:
        cur_row, cur_col, count = q.popleft()
        if cur_row == g_row and cur_col == g_col:
            return count
        for dr, dc in zip(DR, DC):
            next_row = cur_row + dr
            next_col = cur_col + dc
            if 0 <= next_row < H and 0 <= next_col < W:
                pass
            else:
                continue
            if maze[next_row][next_col] == '#':
                continue
            if visited[next_row][next_col]:
                continue
            q.append((next_row, next_col, count + 1))
            visited[next_row][next_col] = 1
    return -1

def main():
    H, W = LI()
    maze = []
    for _ in range(H):
        maze.append(S())
    num = 0
    seen = set()
    for st_row in range(H):
        for st_col in range(W):
            for g_row in range(H):
                for g_col in range(W):
                    if maze[st_row][st_col] == '#' or maze[g_row][g_col] == '#':
                        continue
                    if ((st_row, st_col, g_row, g_col)) in seen:
                        continue
                    if ((g_row, g_col, st_row, st_col)) in seen:
                        continue
                    a = solve(maze, (st_row, st_col), (g_row, g_col))
                    seen.add((st_row, st_col, g_row, g_col))
                    num = max(num, a)

    print(num)
main()

Submission status: Time Limit Exceeded

Solution code:
def astar(start, goal, S, H, W):
  if S[start[0]][start[1]] == '#' or S[goal[0]][goal[1]] == '#':
    return -1
  else:
    INF = 10**9
    D = [[INF]*W for h in range(H)]
    D[start[0]][start[1]] = 0
    next_node = [start]
    while next_node:
      now_y, now_x = next_node.pop()
      d = D[now_y][now_x]
      for x, y in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
        if now_y+y<0 or now_y+y>=H or now_x+x<0 or now_x+x>=W:
          continue
        if S[now_y+y][now_x+x] == '.':
          if D[now_y+y][now_x+x] > d + 1:
            D[now_y+y][now_x+x] = D[now_y][now_x] + 1
            next_node.append([now_y+y, now_x+x])
    
    if D[goal[0]][goal[1]] < INF:
      return D[goal[0]][goal[1]]
    else:
      return -1


H, W = map(int, input().split())
nodes = []
for h in range(H):
  for w in range(W):
    nodes.append([h, w])

S = []
for h in range(H):
  S.append(list(input()))

ans = 0
num_nodes = len(nodes)
for i in range(num_nodes):
  for j in range(i+1, num_nodes):
    ans = max(ans, astar(nodes[i], nodes[j], S, H, W))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline

H, W = map(int, readline().split())
S = tuple(read().split())


def bfs(grid, start):
    distance = [[0] * W for _ in range(H)]
    queue = deque([start])
    visited = set()
    while queue:
        x, y = queue.popleft()
        visited.add((x, y))

        for i, j in ([1, 0], [-1, 0], [0, 1], [0, -1]):
            new_y, new_x = y + j, x + i
            if 0 <= new_y < W and 0 <= new_x < H:
                if grid[new_x][new_y] == '.' and (new_x, new_y) not in visited:
                    distance[new_x][new_y] = distance[x][y] + 1
                    queue.append((new_x, new_y))
    return distance


answer = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == '#':
            continue
        tmp = max(map(max, bfs(S, (i, j))))
        if tmp > answer:
            answer = tmp

print(answer)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
s = ['#'*(w+2)]
for i in range(h):
  s.append('#'+input()+'#')
s.append(['#'*(w+2)])

import queue

def search(x, y):
  p = [[-1]*(w+2) for _ in range(h+2)]
  q = queue.Queue()
  q.put([x,y,0])
  p[x][y] = 0
  
  while not q.empty():
    ijt = q.get()
    i = ijt[0]
    j = ijt[1]
    t = ijt[2]
    p[i][j] = t
    if i != 1:
      if s[i-1][j] != '#' and p[i-1][j] == -1:
        q.put([i-1,j,t+1])
    if i != h:
      if s[i+1][j] != '#' and p[i+1][j] == -1:
        q.put([i+1,j,t+1])
    if j != 1:
      if s[i][j-1] != '#' and p[i][j-1] == -1:
        q.put([i,j-1,t+1])
    if j != w:
      if s[i][j+1] != '#' and p[i][j+1] == -1:
        q.put([i,j+1,t+1])
  v = max([max(p[_]) for _ in range(len(p))])
  return v
    
  
ans = 0
for i in range(1,h+1):
  for j in range(1,w+1):
    if s[i][j] == '.':
      v = search(i,j)
      ans = max(ans, v)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
H,W=map(int,input().split())
field=[input() for _ in range(H)]

def dfs(d,x,y,gx,gy,seen):
  global dist
  if x==gx and y==gy:
    dist=min(dist,d)
  else:
    if x>=W or x<0 or y>=H or y<0:
      pass
    elif field[y][x]=="#":
      pass
    else:
      dx=[1,0,-1,0]
      dy=[0,1,0,-1]
      for i in range(4):
        if [x+dx[i],y+dy[i]] not in seen:
          seen.append([x+dx[i],y+dy[i]])
          dfs(d+1,x+dx[i],y+dy[i],gx,gy,seen)
          seen.remove([x+dx[i],y+dy[i]])

ans=-1
for i in range(H):
  for j in range(W):
    if field[i][j]=="#":
      pass
    else:
      for k in range(H):
        for l in range(W):
          if field[k][l]=="#":
            pass
          if k==i and l==j:
            pass
          else:
            dist=float("inf")
            dfs(0,j,i,l,k,[[j,i]])
            ans=max(ans,dist)
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
"""
-1 -> not visited
else -> step count
"""
def bfs(maze, visited, sh, sw, gh, gw):
    stack = deque([[sh, sw]])
    visited[sh][sw] = 1
    while stack:
        h, w = stack.popleft()
        # ゴールの条件
        if h == gh and w == gw:
            break
        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 \
                visited[new_h][new_w] == -1:
                    visited[new_h][new_w] = visited[h][w] + 1
                    stack.append([new_h, new_w])
    
    return visited[gh][gw]

if __name__ == "__main__":
    H, W = map(int, input().split())
    maze = [input() for _ in range(H)]

    vd = [[[[0 for _ in range(W)] for _ in range(H)] for _ in range(W)] for _ in range(H)]
    ans = 0
    for sh in range(H):
        for sw in range(W):
            for gh in range(H):
                for gw in range(W):
                    if maze[sh][sw] != "#" and maze[gh][gw] != "#" and vd[sh][sw][gh][gw] == 0 and vd[gh][gw][sh][sw] == 0 and not (gh == sh and gw == sw):
                        vd[sh][sw][gh][gw] = 1
                        vd[gh][gw][sh][sw] = 1
                        visited = [[-1] * W for _ in range(H)]
                        step_cnt = bfs(maze, visited, sh, sw, gh, gw)
                        ans = max(ans, step_cnt)

    print(ans - 1)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
h, w = [int(x) for x in input().strip().split()]
m = [[0 for _ in range(w)] for _ in range(h)]
for hi in range(h):
    for wi, s in enumerate(input().strip()):
        m[hi][wi] = s

c = [[float('inf')] * (h*w) for _ in range(h*w)]
for i in range(h*w):
    c[i][i] = 0

for hi in range(h):
    for wi in range(w):
        #print(hi, wi)
        if m[hi][wi] == '#':
            continue
        for offset in [(0, 1), (-1, 0), (0, -1), (1, 0)]:
            if hi+offset[0] < 0 or hi+offset[0] == h:
                continue
            if wi+offset[1] < 0 or wi+offset[1] == w:
                continue
            if m[hi+offset[0]][wi+offset[1]] == '#':
                continue
            #print('offset = {}'.format(offset))
            #print('hi*w+wi = {}'.format(hi*w+wi), '(hi+offset[0])*w+(wi+offset[1]) = {}'.format((hi+offset[0])*w+(wi+offset[1])))
            c[hi*w+wi][(hi+offset[0])*w+(wi+offset[1])] = 1

#print('-- cost --')
#for ci in c:
#    print(ci)

for k in range(h*w):
    for i in range(h*w):
        for j in range(h*w):
            c[i][j] = min(c[i][j], c[i][k]+c[k][j])

ans = 0
#print('-- total cost --')
#for ci in c:
#    print(ci)

for ci in c:
    for cii in ci:
        if cii != 0 and cii != float('inf'):
            ans = max(ans, cii)

print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
def astar(start, goal, S, H, W):
  if S[start[0]][start[1]] == '#' or S[goal[0]][goal[1]] == '#':
    return -1
  else:
    INF = 10**9
    D = [[INF]*W for h in range(H)]
    D[start[0]][start[1]] = 0
    next_node = [start]
    while next_node:
      now_y, now_x = next_node.pop()
      d = D[now_y][now_x]
      for x, y in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
        if now_y+y<0 or now_y+y>=H or now_x+x<0 or now_x+x>=W:
          continue
        if S[now_y+y][now_x+x] == '.':
          if D[now_y+y][now_x+x] > d + 1:
            D[now_y+y][now_x+x] = D[now_y][now_x] + 1
            next_node.append([now_y+y, now_x+x])
    
    if D[goal[0]][goal[1]] < INF:
      return D[goal[0]][goal[1]]
    else:
      return -1


H, W = map(int, input().split())
nodes = []
for h in range(H):
  for w in range(W):
    nodes.append([h, w])

S = []
for h in range(H):
  S.append(list(input()))

ans = 0
for start in nodes:
  for goal in nodes:
    ans = max(ans, astar(start, goal, S, H, W))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H,W = map(int,input().split())
S = [input().strip() for _ in range(H)]
cmax = 0
for i in range(H):
    for j in range(W):
            for k in range(H):
                for l in range(W):
                    if (i,j)!=(k,l) and S[i][j]=="." and S[k][l]==".":
                        que = deque([(i,j,0)])
                        hist = {(n,m):0 for n in range(H) for m in range(W)}
                        hist[(i,j)] = 1
                        while que:
                            x = que.popleft()
                            n,m,c = x[0],x[1],x[2]
                            if n==k and m==l:
                                cmax = max(cmax,c)
                                break
                            if m+1<W and S[n][m+1]=="." and hist[(n,m+1)]==0:
                                que.append((n,m+1,c+1))
                                hist[(n,m+1)] = 1
                            if m-1>-1 and S[n][m-1]=="." and hist[(n,m-1)]==0:
                                que.append((n,m-1,c+1))
                                hist[(n,m-1)] = 1
                            if n+1<H and S[n+1][m]=="." and hist[(n+1,m)]==0:
                                que.append((n+1,m,c+1))
                                hist[(n+1,m)] = 1
                            if n-1>-1 and S[n-1][m]=="." and hist[(n-1,m)]==0:
                                que.append((n-1,m,c+1))
                                hist[(n-1,m)] = 1
print(cmax)

Submission status: Time Limit Exceeded

Solution code:
adjust_list = ((0,1),(0,-1),(1,0),(-1,0))
h, w = [int(v) for v in input().split()]
field = [list(input()) for i in range(h)]

def bfs(s, t):
    si, sj = s
    ti, tj = t
    if field[si][sj] == "." and field[ti][tj] == ".":

        search_field = [ [ -1 for i in range(w) ] for j in range(h) ]
        search_list = [s]
        turn = 0
        search_field[si][sj] = turn
        
        
        while search_list:
            turn += 1
            new_search_list = []
            for p in search_list:
                pi, pj = p
                
                for q in adjust_list:
                    qi, qj = q
                    if 0 <= pi+qi < h and 0 <= pj+qj < w:
                        if search_field[pi+qi][pj+qj] == -1 and field[pi+qi][pj+qj] == ".":
                            new_search_list.append((pi+qi,pj+qj))
                            search_field[pi+qi][pj+qj] = turn
            search_list = new_search_list

        return search_field[ti][tj]
    else:
        return -1
    

ans = 0
coodinate = [ (i, j) for i in range(h) for j in range(w) ]
k = h*w

for i in range(k-1):
    for j in range(i+1, k):
        ans = max(ans, bfs(coodinate[i], coodinate[j]))
print(ans)

Submission status: Time Limit Exceeded

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

def solve(h, w, a):
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]
    def bfs(x1, y1, x2, y2):
        visited = [[False] * w for _ in range(h)]
        cur = []
        visited[y1][x1] = True
        cur.append((x1, y1))
        cnt = 1
        while True:
            nex = []
            for x, y in cur:
                for i in range(4):
                    tx = x + dx[i]
                    ty = y + dy[i]
                    if 0 <= tx < w and 0 <= ty < h and a[ty][tx] != '#' and not visited[ty][tx]:
                        visited[ty][tx] = True
                        if tx == x2 and ty == y2:
                            return cnt
                        nex.append((tx, ty))
            if len(nex) > 0:
                cur = nex
            else:
                break
            cnt += 1
        return -1

    found = [[False] * (h * w) for _ in range(h * w)]
    ret = -1
    for i in range(h):
        for j in range(w):
            for i2 in range(h):
                for j2 in range(w):
                    if (not (i == i2 and j == j2)) and a[i][j] == '.' and a[i2][j2] == '.' and not found[w * i + j][w * i2 + j2]:
                        tmp = bfs(j, i, j2, i2)
                        ret = max(ret, tmp)
                        found[w * i + j][w * i2 + j2] = True
                        found[w * i2 + j2][w * i + j] = True
    print(ret)
    return

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

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
visited = [[0 for _ in range(w)] for _ in range(h)]
checkde = [[[[0 for _ in range(w)] for _ in range(h)] for _ in range(w)] for _ in range(h)]
# print(s)
for i in range(h):
    for j in range(w):
        if s[i][j] == "#":
            visited[i][j] = 1
import copy

ans = 0
for iS in range(h):
    for jS in range(w):
        for iG in range(h):
            for jG in range(w):
                if s[iS][jS] == "#" or s[iG][jG] == "#" or checkde[iG][jG][iS][jS]:
                    continue
                checkde[iS][jS][iG][jG] = 1
                checkde[iG][jG][iS][jS] = 1
                thisVisited = copy.deepcopy(visited)
                now = 0
                dis = 0
                next_point = [[iS, jS, dis]]
                thisVisited[iS][jS] = 1
                while now < len(next_point):
                    nowi = next_point[now][0]
                    nowj = next_point[now][1]
                    nowdis = next_point[now][2]
                    dis = max(nowdis, dis)
                    # print(nowi, nowj, iG, jG, nowdis)

                    if nowi == iG and nowj == jG:
                        ans = max(dis, ans)
                        break

                    if nowi != 0:
                        if thisVisited[nowi - 1][nowj] == 0:
                            next_point.append([nowi - 1, nowj, nowdis + 1])
                            thisVisited[nowi - 1][nowj] = 1

                    if nowi != h - 1:
                        if thisVisited[nowi + 1][nowj] == 0:
                            next_point.append([nowi + 1, nowj, nowdis + 1])
                            thisVisited[nowi + 1][nowj] = 1

                    if nowj != w - 1:
                        if thisVisited[nowi][nowj + 1] == 0:
                            next_point.append([nowi, nowj + 1, nowdis + 1])
                            thisVisited[nowi][nowj + 1] = 1

                    if nowj != 0:
                        if thisVisited[nowi][nowj - 1] == 0:
                            next_point.append([nowi, nowj - 1, nowdis + 1])
                            thisVisited[nowi][nowj - 1] = 1

                    now += 1
                # print(next_point)
# print(checkde)
print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
S = [list(input()) for _ in range(H)]
#print(S)
idx = 0
for i in range(H):
  for j in range(W):
    if S[i][j] == '.':
      S[i][j] = idx
      idx += 1
#print(S)
D = [[float('inf') for _ in range(idx)] for _ in range(idx)]
for i in range(H):
  for j in range(W):
    if S[i][j] == '#':
      continue
    for dy,dx in [(-1,0),(1,0),(0,-1),(0,1)]:
      if 0 <= i+dy < H and 0 <= j+dx < W and S[i+dy][j+dx] != '#':
        D[S[i][j]][S[i+dy][j+dx]] = 1
        D[S[i+dy][j+dx]][S[i][j]] = 1
for i in range(idx):
  D[i][i] = 0

for k in range(idx):
  for i in range(idx):
    for j in range(idx):
      D[i][j] = min(D[i][k]+D[k][j],D[i][j])
#print(D)
ans = 0
for d in D:
  ans = max(max(d),ans)
print(ans)