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:
def num():
    return int(input())
def nums():
    return list(map(int,input().split()))

import itertools as iter
import math
import fractions
from functools import reduce

def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

H,W = nums()
meiro = [[1] + [int(n == "#") for n in list(input())] + [1] for _ in range(H)]
meiro.insert(0,[1 for _ in range(W+2)])
meiro.insert(len(meiro),[1 for _ in range(W+2)])



import math

class MazeNode:
    def __init__(self,x,y,st,cond):
        self.x = x
        self.y = y
        self.state = st
        self.cond = cond
        self.parent = None
        self.fs = 0
        self.hs = 0
        self.gs = 0

    def calc_hs(self,gx,gy):
        dx = self.x - gx
        dy = self.y - gy
        self.hs = math.sqrt(dx ** 2 + dy ** 2)
    
    def update_gs(self):
        self.gs = self.fs - self.hs

    def set_gs(self,val):
        self.gs = val

    def set_cond(self,cond):
        if cond == "open" or cond == "close":
            self.cond = cond
        else:
            ##print("cond set error")
            pass
    
    # debug
    def show_pos(self):
        pass
        ##print("(%d:%d) %d %s" % (self.x,self.y,self.state,self.cond))

def get_min_fs_node(maze_nodes):
    # open_nodeのうちmin_fsのものを1つreturn
    res_node = None
    for row in maze_nodes:
        for node in row:
            if node.cond != "open":
                continue
            if not res_node:
                res_node = node
            elif node.fs < res_node.fs:
                res_node = node
    return res_node

def check_next_node(target_node,maze_nodes):
    # get next nods
    tx = target_node.x
    ty = target_node.y
    next_nodes = [
            maze_nodes[ty-1][tx  ],
            maze_nodes[ty  ][tx+1],
            maze_nodes[ty+1][tx  ],
            maze_nodes[ty  ][tx-1]
            ]

    # process next nodes
    target_node.update_gs()
    for node in next_nodes:
        if node.state == 1:
            continue
        f_dash = target_node.gs + node.hs + 1
        if node.cond == "none":
            node.set_cond("open")
            node.fs = f_dash
            node.parent = target_node
        elif node.cond == "open" and f_dash < node.fs:
            node.fs = f_dash
            node.parent = target_node
        elif node.cond == "close" and f_dash < node.fs:
            node.set_cond("open")
            node.fs = f_dash
            node.parent = target_node

def print_route(maze,fin_node):
    # make map data
    print()
    map = []
    for y in range(len(maze)):
        row = []
        for x in range(len(maze[0])):
            row.append("-" if maze[y][x] == 1 else " ")
        map.append(row)

    # make route data
    node = fin_node
    while node:
        map[node.y][node.x] = "x"
        node = node.parent

    # print route data
    for y in range(len(map)):
        for x in range(len(map[0])):
            print(map[y][x], end="")
        print("")

def make_route(fin_node):
    route = ""
    node = fin_node

    while node.parent:
        dx = node.x - node.parent.x
        dy = node.y - node.parent.y

        if dx == 1:
            route += "E"
        elif dx == -1:
            route += "W"
        elif dy == 1:
            route += "S"
        elif dy == -1:
            route += "N"
        
        node = node.parent

    return route[::-1]



def checkio(data,start,goal):
    maze = data
    maze_nodes = []

    goal_pos_x,goal_pos_y = goal

    for y in range(len(maze)):
        row = []
        for x in range(len(maze[0])):
            node = MazeNode(x,y,maze[y][x],"none")
            node.calc_hs(goal_pos_x,goal_pos_y)
            row.append(node)
        maze_nodes.append(row)

    start_node = maze_nodes[start[0]][start[1]]
    start_node.set_cond("open")
    start_node.set_gs(0)
    start_node.fs = start_node.hs

    while True: # step12:repeat
        # step3,4
        target_node = get_min_fs_node(maze_nodes)
        if not target_node:
            # step3
            #print("search fail")
            return "fail"
        elif target_node.x == goal_pos_x and target_node.y == goal_pos_y:
            #step5_finish
            #print("search finish")
            #print_route(maze,target_node)
            return len(make_route(target_node)) #step13
        else:
            # step5_continue
            target_node.set_cond("close")
            check_next_node(target_node,maze_nodes) #step6-11



    
ans = set()
goals = []
starts = []
for x in range(W+2):
    for y in range(H+2):
        goals.append((x,y))
for x in range(W):
    for y in range(H):
        starts.append((x,y))
for s in starts:
    for g in goals:
        try:
            r = checkio(meiro,s,g)
            if not r == "fail":ans.add(r)
        except:pass
print(max(ans)-1)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy
import numpy as np

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

maze = []
maze.append(["#" for i in range(W+2)])
for i in range(H):
    maze.append(list(input()))
    maze[i+1].insert(0,"#")
    maze[i+1].append("#")
maze.append(["#" for i in range(W+2)])

distance_template = np.array([[-1 for i in range(W+2)] for i in range(H+2)])

ans = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if maze[i][j] != "#":
            startx,starty = i,j
            distance = copy.deepcopy(distance_template)
            distance[startx][starty] = 0
            Q = queue.Queue()
            Q.put((startx, starty))
            while not Q.empty():
                x,y = Q.get()
                for k in range(0, 4):
                    nx, ny = x + [1, 0, -1, 0][k], y + [0, 1, 0, -1][k]
                    if (maze[nx][ny] != "#" and distance[nx][ny] == -1):
                        Q.put((nx, ny))
                        distance[nx][ny] = distance[x][y] + 1
            maxdistance = np.unravel_index(np.argmax(distance), distance.shape)
            if ans < distance[maxdistance[0]][maxdistance[1]]:
                ans = distance[maxdistance[0]][maxdistance[1]]
print(ans)

Submission status: Time Limit Exceeded

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

import copy
dp=[[1000 for i in range(w)]for i in range(h)]
for y,i in enumerate(field):
    for x,j in enumerate(i):
        if j=="#":
            dp[y][x]=9999

dydx=[[-1,0],[1,0],[0,-1],[0,1]]

maxi=0
for y,i in enumerate(field):
    for x,j in enumerate(i):
        if j==".":
            ndp=copy.deepcopy(dp)
            ndp[y][x]=0
            
            for _ in range(280):
                for y,i in enumerate(ndp):
                    for x,j in enumerate(i):
                        if j<1000:
                            for dy,dx in dydx:
                                ny,nx=y+dy,x+dx
                                if 0<=ny<=h-1 and 0<=nx<=w-1 and field[ny][nx]!="#" and ndp[ny][nx]>ndp[y][x]:
                                    ndp[ny][nx]=ndp[y][x]+1
            for y,i in enumerate(ndp):
                for x,j in enumerate(i):
                    if j==9999:
                        ndp[y][x]=0
                        continue
                    if j>maxi:
                        maxi=j
print(maxi)

Submission status: Time Limit Exceeded

Solution code:

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

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

ans = []
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue

        for k in range(i, h):
            for l in range(w):
                if s[k][l] == '#' or i == k and j == l:
                    continue
                start = (i, j)
                goal = (k, l)
                d = [[1<<10 for x in range(w)] for y in range(h)]

                stack = []
                stack.append((start[0], start[1]))
                d[start[0]][start[1]] = 0
                while stack:
                    y, x = stack.pop()
                    if y == goal[0] and x == goal[1]:
                        continue
                    if y > 0 and s[y-1][x] == '.' and d[y-1][x] > d[y][x]+1:
                        d[y-1][x] = d[y][x] + 1
                        stack.append((y-1, x))
                    if x < w-1 and s[y][x+1] == '.' and d[y][x+1] > d[y][x]+1:
                        d[y][x+1] = d[y][x] + 1
                        stack.append((y, x+1))
                    if y < h-1 and s[y+1][x] == '.' and d[y+1][x] > d[y][x]+1:
                        d[y+1][x] = d[y][x] + 1
                        stack.append((y+1, x))
                    if x > 0 and s[y][x-1] == '.' and d[y][x-1] > d[y][x]+1:
                        d[y][x-1] = d[y][x] + 1
                        stack.append((y, x-1))
                ans.append(d[goal[0]][goal[1]])
ans.sort()
print(ans[-1])

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
from collections import defaultdict
input = sys.stdin.readline
H, W = map(int, input().split())
C = [list(input()) for i in range(H)]

INF = 10 ** 9
n = H * W
d =[[INF for _ in range(n)] for _ in range(n)]
go = [[1, 0], [0, 1], [-1, 0], [0, -1]]
for x in range(W):
    for y in range(H):
        for temp in go:
            gx,gy = temp
            nx = x + gx
            ny = y + gy
            if 0<= nx < W and 0<= ny < H and C[ny][nx] != "#":
                d[ny * W + nx][y * W + x] = 1
                d[y * W + x] [ny * W + nx]= 1
for i in range(n):
    d[i][i] = 0
    #d[i][j]: iからjへの最短距離
for k in range(n):
    for i in range(n):
        for j in range(n):
            if C[i//W][i%W] != "#" and C[j//W][j%W] != "#" and C[k//W][k%W] != "#":
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
ans = d
# print(ans)
x  = 0
for temp in ans:
    for k in temp:
        if k != INF:
            if k > x:
                x = k
print(x)

Submission status: Time Limit Exceeded

Solution code:
import copy

H, W = map(int, input().split())
S = [[0 if c == '.' else 1 for c in input()] for _ in range(H)]

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

def bfs(y, x):
    q = [[y,x,0]]
    ST = copy.deepcopy(S)
    res = -1
    while len(q):
        ST[y][x] = 1
        y, x, d = q.pop(0);
        res = max(res, d)
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if not (0 <= ny <= H-1 and 0 <= nx <= W-1): continue
            if ST[ny][nx] == 1: continue
            q.append([ny,nx,d+1])
    return res

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import queue
H, W = map(int, input().split())
S = [input() for _ in range(H)]
reach = [[False] * W for i in range(H)]
step = np.ones((H, W)) * (-1)
m = 0
q = queue.Queue()

for sh in range(H):
    for sw in range(W):
        if S[sh][sw] == '#':
            pass
        else:
            reach = [[False] * W for i in range(H)]
            step = np.ones((H, W)) * (-1)
            #dfs(sw, sh, 0)
            q.put((sw, sh, 0))
            while not q.empty():
                x, y, s = q.get()
                if x < 0 or W <= x or y < 0 or H <= y:
                    pass
                elif reach[y][x]:
                    pass
                elif S[y][x] == '#':
                    pass
                else:
                    reach[y][x] = True
                    step[y, x] = min(s, step[y, x]) if step[y, x] != -1 else s
    
                    q.put((x+1, y, s+1))
                    q.put((x-1, y, s+1))
                    q.put((x, y-1, s+1))
                    q.put((x, y+1, s+1))
    
            m = max(m, np.max(step))

print(int(m))

Submission status: Time Limit Exceeded

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

Map = []
Map.append(list('@'*(W+2)))
for i in range(H):
  s = list('@'+input()+'@')
  Map.append(s)
Map.append(list('@'*(W+2)))
  
#400*400 = 160000 = 1.6*10**5
#スタートとゴール用
select = []
for i in range(H+2):
 if((i != 0)and(i != H+1)):
  for j in range(W+2):
   if((j != 0)and(j != W+1)):
    for k in range(H+2):
     if((k != 0)and(k != H+1)):
      for l in range(W+2):
       if((l != 0)and(l != W+1)):
         select.append([i,j,k,l])

          
#print(len(select))          
#幅優先探索
def bfs(sy,sx,gy,gx,Map):
  qy,qx = queue.Queue(),queue.Queue()
  qy.put(sy),qx.put(sx)
  ans = 0
  while(1):
    if(qx.empty() == True): return ans
    #座標の取り出し
    y,x = qy.get(),qx.get()
    if((y == gy)and(x == gx)): #ゴールなら終了
      ans = Map[y][x]
      #for i in range(H+2):
      #   print(Map[i])
      #print('______________')
      return ans
    
    #次に進むところ
    vec_y = [0,0,1,-1]
    vec_x = [1,-1,0,0]
    for i in range(4):
      if(Map[y+vec_y[i]][x+vec_x[i]] == '.'):
        Map[y+vec_y[i]][x+vec_x[i]] = Map[y][x] + 1
        qy.put(y+vec_y[i]),qx.put(x+vec_x[i])
           
ans = 0 
for s in range(len(select)):
  sy,sx = select[s][0], select[s][1] 
  gy,gx = select[s][2], select[s][3]
  Map2 = copy.deepcopy(Map)

  #スタートとゴールの設置
  if((Map2[sy][sx] == '.')and(Map2[gy][gx] == '.')):
   Map2[sy][sx] = 0
   #幅優先探索
   tmp_ans = bfs(sy,sx,gy,gx,Map2)
   #print(sy,sx,gy,gx)
   #print(tmp_ans)
   ans = max(ans,tmp_ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy
 
def ngoin(bo,now):
    return 0 <= now[0] and now[0] < len(bo) and 0 <= now[1] and now[1] < len(bo[0])
 
def minido(bo,si,sj,ei,ej):
    tb = [[False for i in range(len(bo[0]))] for j in range(len(bo))]
    q = queue.Queue()
    q.put([si,sj,0])
    while not q.empty():
        now = q.get()
        if now[0] == ei and now[1] == ej:
            return now[2]
        if tb[now[0]][now[1]]:
            continue
        tb[now[0]][now[1]] = True
        if ngoin(bo,[now[0]-1,now[1]]):
            if bo[now[0]-1][now[1]]:
                q.put([now[0]-1,now[1],now[2]+1])
        if ngoin(bo,[now[0],now[1]+1]):
            if bo[now[0]][now[1]+1]:
                q.put([now[0],now[1]+1,now[2]+1])
        if ngoin(bo,[now[0]+1,now[1]]):
            if bo[now[0]+1][now[1]]:
                q.put([now[0]+1,now[1],now[2]+1])
        if ngoin(bo,[now[0],now[1]-1]):
            if bo[now[0]][now[1]-1]:
                q.put([now[0],now[1]-1,now[2]+1])
            
            
 
h,w = map(int,input().split())
bo = [[True if x == '.' else False for x in input()] for i in range(h)]
grap = [[float('inf') for i in range(h*w)] for j in range(h*w)]
ans = 0
for i in range(h*w):
    grap[i][i] = 0
for si in range(h):
    for sj in range(w):
        if not bo[si][sj]:
            continue
        now = [si,sj]
        if ngoin(bo,[now[0]-1,now[1]]):
            if bo[now[0]-1][now[1]]:
                grap[now[0]*w+now[1]][(now[0]-1)*w+now[1]] = 1
        if ngoin(bo,[now[0],now[1]+1]):
            if bo[now[0]][now[1]+1]:
                grap[now[0]*w+now[1]][1+now[0]*w+now[1]] = 1
        if ngoin(bo,[now[0]+1,now[1]]):
            if bo[now[0]+1][now[1]]:
                grap[now[0]*w+now[1]][(now[0]+1)*w+now[1]] = 1
        if ngoin(bo,[now[0],now[1]-1]):
            if bo[now[0]][now[1]-1]:
                grap[now[0]*w+now[1]][now[0]*w-1+now[1]] = 1
                
for k in range(w*h):
    for i in range(w*h):
        for j in range(w*h):
            if grap[i][j] > grap[i][k] + grap[k][j]:
                grap[i][j] = grap[i][k] + grap[k][j]

ans = 0
for i in range(w*h):
    for j in range(w*h):
        if grap[i][j] == float('inf'):
            continue
        ans = max(grap[i][j],ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
# sx, sy = map(int, input().split())
# gx, gy = map(int, input().split())
# sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1
c = [input() for i in range(H)]
INF = 10**9
def bfs():
    dist = [[INF for i in range(W)] for j in range(H)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    q = deque()
    q.append([sx, sy])
    dist[sx][sy] = 0
    while q:
        p = q.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 and nx < H and 0 <= ny and ny < W:
                if c[nx][ny] != '#' and dist[nx][ny] == INF:
                    q.append([nx, ny])
                    dist[nx][ny] = dist[p[0]][p[1]] + 1
    return dist[gx][gy]

ans = []
for i in range(H):
    for j in range(W):
        for k in range(H):
            for l in range(W):
                sx, sy = i, j
                gx, gy = k, l
                if c[sx][sy] == '#' or c[gx][gy] == '#':
                    continue
                ans.append(bfs())
                
ans = [i for i in ans if i != INF]
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
maze = []
for i in range(H):
    s = input()
    m = []
    for j in range(W):
        m.append(s[j])
    maze.append(m)
d = [[10**9 for i in range(W*H)] for i in range(W*H)]
dx = [0,0,1,-1]
dy = [1,-1,0,0]
for i in range(W*H):
    h = i//W
    w = i%W
    if maze[h][w] == '#':
        continue
    for j in range(4):
        x = w + dx[j]
        y = h + dy[j]
        k = x + y*W
        if 0<=x<=W-1:
            if 0<=y<=H-1:
                if maze[y][x] == '.':
                    d[i][k] = 1
                    d[k][i] = 1
for i in range(W*H):
    d[i][i] = 0
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(W*H):
        for i in range(W*H):
            for j in range(W*H):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d
warshall_floyd(d)
ans = 0
for i in range(W*H):
    for j in range(W*H):
        if d[i][j] < 10**9:
            ans = max(ans,d[i][j])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000)
from collections import deque

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

    return d[gx][gy]

h,w=map(int,input().split())
s = [list(input()) for i in range(h)]
ans=0
memo=[[0] * w for i in range(h)]
for i in range(h):
    for j in range(w):
        if s[i][j]=='.':
            if j != w:
                for m in range(j+1,w):
                    if s[i][m]=='.':
                        ans = max(ans,bfs(i,j,i,m))
            for k in range(i+1,h):
                for l in range(w):
                    if s[k][l]=='.':
                        ans = max(ans,bfs(i,j,k,l))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h,w = map(int,input().split())
raw = []
for _ in range(h):
  tmp = input()
  add = []
  for j in range(w):
    if tmp[j] == '.':
      add.append(0)
    else:
      add.append(2)
  raw.append(add)
nex = [[0,1],[0,-1],[1,0],[-1,0]]
can = []
from copy import deepcopy as dc
for a in range(h):
  for b in range(w):
    if raw[a][b] == 2:
      continue
    last = dc(raw)
    last[a][b] = 1
    ans = 0
    while True:
      now = dc(last)
      ans += 1
      for i in range(h):
        for j in range(w):
          if last[i][j] == 0:
            for x in nex:
              if 0 <= i+x[0] < h and 0 <= j+x[1] < w:
                if last[i+x[0]][j+x[1]] == 1:
                  now[i][j] = 1
                  break
      check = 1
      for i in range(h):
        for j in range(w):
          check *= now[i][j]
      if check > 0:
        can.append(ans)
        break
      last = dc(now)
print(max(can))

Submission status: Time Limit Exceeded

Solution code:
#import sys
MOD = 10 ** 9 + 7
#input = sys.stdin.readline
import math

import itertools

#import bisect

import copy


def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

#    h,w,a,b = map(int, input().split())
#    c = [[0 for j in range(n)] for i in range(n)]
def main():
    h,w=map(int,input().split())
    s=[input() for i in range(h)]
    for i in range(h):
        s[i]=list(s[i])
    for i in range(h):
        for j in range(w):
            if s[i][j]==".":
                s[i][j]=1000
            else:
                s[i][j]=9999
 #   print(s)
    start=[0,0]
    for i in range(h):
        start[1]=s[i].index(min(s[i]))
        if min(s[i]) >= 1111:
            continue
        else:
            start[0]=i
            break
 #   print(start)
    s[start[0]][start[1]]=0

    for kk in range(10000):

        for i in range(h):
            for j in range(w):
                if s[i][j]>1000:
                    continue
                if i+1<h:
                    if s[i][j]>s[i+1][j] and s[i+1][j]<1000:
                            s[i][j]=s[i+1][j]+1
                if i-1>=0:
                    if s[i][j] > s[i - 1][j] and s[i - 1][j] < 1000:
                            s[i][j] = s[i - 1][j] + 1
                if j+1<w:
                    if s[i][j] > s[i][j+1] and s[i][j+1] < 1000:
                            s[i][j] = s[i][j+1] + 1
                if j-1>=0:
                    if s[i][j] > s[i][j - 1] and s[i][j - 1] < 1000:
                            s[i][j] = s[i][j - 1] + 1

 #   print(s)

    temp=[0,0]
    tempm=0
    for i in range(h):
        for j in range(w):
            if s[i][j]>tempm and s[i][j]<9999:
                tempm=s[i][j]
                temp=[i,j]
            if s[i][j]<9999:
                s[i][j]=1000
    start=[temp[0],temp[1]]
    s[start[0]][start[1]]=0

    for kk in range(10000):

        for i in range(h):
            for j in range(w):
                if s[i][j]>1000:
                    continue
                if i+1<h:
                    if s[i][j]>s[i+1][j] and s[i+1][j]<1000:
                            s[i][j]=s[i+1][j]+1
                if i-1>=0:
                    if s[i][j] > s[i - 1][j] and s[i - 1][j] < 1000:
                            s[i][j] = s[i - 1][j] + 1
                if j+1<w:
                    if s[i][j] > s[i][j+1] and s[i][j+1] < 1000:
                            s[i][j] = s[i][j+1] + 1
                if j-1>=0:
                    if s[i][j] > s[i][j - 1] and s[i][j - 1] < 1000:
                            s[i][j] = s[i][j - 1] + 1

#    print(s)
#    for i in range(h):
#        print(s[i])

    temp = [0, 0]
    tempm = 0
    for i in range(h):
        for j in range(w):
            if s[i][j] > tempm and s[i][j] < 9999:
                tempm = s[i][j]
                temp = [i, j]
            if s[i][j] < 9999:
                s[i][j] = 1000

    print(tempm)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import copy
dp=[[1000 for i in range(w)]for i in range(h)]
for y,i in enumerate(field):
    for x,j in enumerate(i):
        if j=="#":
            dp[y][x]=9999

dydx=[[-1,0],[1,0],[0,-1],[0,1]]

maxi=0
for y,i in enumerate(field):
    for x,j in enumerate(i):
        if j==".":
            ndp=copy.deepcopy(dp)
            ndp[y][x]=0
            
            for _ in range(400):
                for y,i in enumerate(ndp):
                    for x,j in enumerate(i):
                        if j<1000:
                            for dy,dx in dydx:
                                ny,nx=y+dy,x+dx
                                if 0<=ny<=h-1 and 0<=nx<=w-1 and field[ny][nx]!="#" and ndp[ny][nx]>ndp[y][x]:
                                    ndp[ny][nx]=ndp[y][x]+1
            for y,i in enumerate(ndp):
                for x,j in enumerate(i):
                    if j==9999:
                        ndp[y][x]=0
                        continue
                    if j>maxi:
                        maxi=j
print(maxi)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import sys
from collections import defaultdict
input = sys.stdin.readline
H, W = map(int, input().split())
C = [list(input()) for i in range(H)]

INF = 10 ** 9
n = H * W
d =[[INF for _ in range(n)] for _ in range(n)]
go = [[1, 0], [0, 1], [-1, 0], [0, -1]]
for x in range(W):
    for y in range(H):
        for temp in go:
            gx,gy = temp
            nx = x + gx
            ny = y + gy
            if 0<= nx < W and 0<= ny < H and C[ny][nx] != "#":
                d[ny * W + nx][y * W + x] = 1
                d[y * W + x] [ny * W + nx]= 1
for i in range(n):
    d[i][i] = 0
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if C[i//W][i%W] != "#" and C[j//W][j%W] != "#" and C[k//W][k%W] != "#":
                    d[i][j] = min(d[i][j],d[i][k] + d[k][j])
ans = d
# print(ans)
x  = 0
for temp in ans:
    for k in temp:
        if k != INF:
            if k > x:
                x = k
print(x)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
import sys
input = sys.stdin.readline

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

ans = 0

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


def bfs(x, y):
    m = np.full((H, W), -1, dtype=np.int)

    q = deque()
    q.append([y, x, 0])
    maximus = 0

    while q:
        j, i, v = q.popleft()
        m[j][i] = v
        for dd in d:
            dj = j + dd[0]
            di = i + dd[1]
            if 0 <= dj < H and 0 <= di < W and m[dj][di] == -1 and S[dj][di] == ".":
                q.append([dj, di, v+1])
                if maximus < v+1:
                    maximus = v+1

    return maximus


for j in range(H):
    for i in range(W):
        if S[j][i] != ".":
            continue
        ans = max(ans, bfs(i, j))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
C = [['#' for j in range(W + 2)] for i in range(H + 2)]

for i in range(H):
    s = input()
    for j in range(W):
        C[i + 1][j + 1] = s[j]
ans = 0

SS = set([])
for sy in range(1, H + 1):
    for sx in range(1, W + 1):
        for gy in range(1, H + 1):
            for gx in range(1, W + 1):
                if (sy,sx, gy, gx) in SS:
                    continue
                else:
                    SS.add((gy, gx, sy, sx))
                q = deque()
                q.append((sy, sx, 0))
                S = set([])
                r = 0
                while len(q) > 0:
                    t = q.popleft()
                    y, x, d = t[0], t[1], t[2]
                    if C[y][x] == '#':
                        continue
                    if (y, x) in S:
                        continue
                    else:
                        S.add((y, x))

                    if (y, x) == (gy, gx):
                        r = d
                        break
                    q.append((y + 1, x , d + 1))
                    q.append((y - 1, x, d + 1))
                    q.append((y, x + 1, d + 1))
                    q.append((y, x - 1, d + 1))

                ans = max(ans, r)


print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from itertools import product
import sys

input = sys.stdin.readline

INF = float('inf')

def floyd_warshall(V, E):
    dist = {u: {v: INF for v in V} for u in V}
    for v in V:
        dist[v][v] = 0
        for (i, j) in E[v]: dist[v][(i, j)] = 1
    for k in V:
        for i, j in product(V, repeat=2):
            if dist[i][j] > dist[i][k] + dist[k][j]:
                dist[i][j] = dist[i][k] + dist[k][j]
    for v in V:
        if dist[v][v] < 0: return None
    return dist


H, W = map(int, input().split())
maze = [input() for _ in range(H)]
V = []
E = defaultdict(list)
for i, j in product(range(H), range(W)):
    if maze[i][j] == '#': continue
    V += [(i, j)]
    check = [(i+dx, j+dy) for dx, dy in [(1, 0), (0, 1)] if i+dx <= H-1 and j+dy <= W-1]
    for x, y in check:
        if maze[x][y] == '.': E[(i, j)].append((x, y)); E[(x, y)].append((i, j))
dist = floyd_warshall(V, E)
ans = 0
for D in dist.values():
    for d in D.values():
        if d != INF:
            ans = max(d, ans)
print(ans)