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:
H, W = map(int, input().split())
mss=[]
for i in range(H):
    mss.append([])
    for j in input():
        mss[i].append(j)
movable_list = []
for h in range(H):
    movable_list.append([])
    for w in range(W):
        movable_list[h].append([])
        if mss[h][w] != "#":
            if h-1 >= 0:
                if mss[h-1][w] != "#":
                    movable_list[h][w].append([h-1,w])
            if h+1 <=H-1:
                if mss[h+1][w] != "#":
                    movable_list[h][w].append([h+1, w])
            if w-1 >=0:
                if mss[h][w-1] != "#":
                    movable_list[h][w].append([h, w-1])
            if w+1 <= W-1:
                if mss[h][w+1] != "#":
                    movable_list[h][w].append([h, w+1])

max_list = [0]*(H*W)
for h in range(H):
    for w in range(W):
        canmove = movable_list[h][w]    
        pass_list = []
        if mss[h][w] != "#":
            pass_list.append([h,w])
            judge = True
            while judge:
                judge = False
                temp=[]
                for i in canmove:
                    if i not in pass_list: 
                        judge = True
                        pass_list.append(i)
                        temp.extend(movable_list[i[0]][i[1]])
                if judge:
                    max_list[h*W+w] += 1
                canmove = temp
                        
print(max(max_list))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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


def successors(x, y):
    locations = []
    # 下に行けるかの判定
    if (x + 1 < H) and (maze[x + 1][y] != '#'):
        locations.append((x + 1, y))
    # 上に行けるかの判定
    if (x - 1 >= 0) and (maze[x - 1][y] != '#'):
        locations.append((x - 1, y))
    # 右に行けるかの判定
    if (y + 1 < W) and (maze[x][y + 1] != '#'):
        locations.append((x, y + 1))
    # 左に行けるかの判定
    if (y - 1 >= 0) and (maze[x][y - 1] != '#'):
        locations.append((x, y - 1))
    return locations


def bfs(initial, successors):
    # goal判定はなく、一番遠いところで返す
    frontier = deque()
    frontier.append((initial, None))
    # tuple
    explored = {initial}
    while len(frontier):
        current_node = frontier.pop()
        current_state = current_node[0]
        for child in successors(*current_state):
            if str(child) in [str(i) for i in explored]:
                continue
            explored.add(child)
            frontier.appendleft((child, current_node))
    return current_node


def node_to_path_count(node):
    counter = 0
    while node[1] is not None:
        counter += 1
        node = node[1]
    return counter


ans = 0
for x in range(H):
    for y in range(W):
        if maze[x][y] == '.':
            solution = bfs((x, y), successors)
            counter = node_to_path_count(solution)
            if ans < counter:
                ans = counter

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
from collections import deque
H, W = map(int, input().split())
INF = -1
maze = []
for i in range(H):
    tmp = list(input())
    maze.append(tmp[:])

def bfs(sx, sy):
    visited = [[INF for _ in range(W)] for _ in range(H)]
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    q = deque()
    q.append([sx, sy])
    visited[sx][sy] = 0
    while q:
        p = q.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < H and 0 <= ny < W:
                if maze[nx][ny] != "#" and visited[nx][ny] == INF:
                    q.append([nx, ny])
                    visited[nx][ny] = visited[p[0]][p[1]] + 1
        dist = -1
        for i in range(H):
            dist = max(dist, max(visited[i]))
    return dist

ans = -1
for x in range(H):
    for y in range(W):
        if maze[x][y] == "#":
            continue
        ans = max(ans, bfs(x, y))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
H, W = map(int, input().split())
maze = [list(input()) for i in range(H)]
S = []
for i in range(H):
  for j in range(W):
    if maze[i][j] == ".":
      maze[i][j] = float("inf")
      S.append([i, j])
    else:
      maze[i][j] = -1
def bfs(H, W, maze, S):
  ans = 0
  for sy, sx in S:
    maze1 = copy.deepcopy(maze)
    maze1[sy][sx] = 0
    q = deque()
    q.append([sy,sx])
    while len(q)>0:
      y, x = q.popleft()
      for i, j in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
        nexty = y+i
        nextx = x+j
        if nexty < 0 or nexty>=H or nextx < 0 or nextx>=W:
          continue
        if maze1[nexty][nextx] != -1:
          if maze1[nexty][nextx] > maze1[y][x]:
            maze1[nexty][nextx] = maze1[y][x] + 1
            q.append([nexty, nextx])
            ans = max(ans, maze1[nexty][nextx])
  print(ans)
bfs(H, W, maze, S)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
H, W = map(int, input().split())
maze = [list(input()) for i in range(H)]
S = []
for i in range(H):
  for j in range(W):
    if maze[i][j] == ".":
      maze[i][j] = float("inf")
      S.append([i, j])
    else:
      maze[i][j] = -1
def bfs(H, W, maze, S):
  ans = 0
  for sy, sx in S:
    maze1 = copy.deepcopy(maze)
    maze1[sy][sx] = 0
    q = deque()
    q.append([sy,sx])
    while len(q)>0:
      y, x = q.popleft()
      for i, j in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
        nexty = y+i
        nextx = x+j
        if nexty < 0 or nexty>=H or nextx < 0 or nextx>=W:
          continue
        if maze1[nexty][nextx] != -1:
          if maze1[nexty][nextx] > maze1[y][x]:
            maze1[nexty][nextx] = maze1[y][x] + 1
            q.append([nexty, nextx])
        ans = max(ans, maze1[nexty][nextx])
  print(ans)
bfs(H, W, maze, S)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

        q = deque()
        q.append([i, j, 0])
        visited = [[False] * (w + 5) for _ in range(h + 5)]
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        while len(q) != 0:
            x, y, z = q.popleft()
            if ans < z: ans = z
            visited[x][y] = True
            for p in range(4):
                nx, ny = x + dirr[p][0], y + dirr[p][1]
                if 0 <= nx < h and 0 <= ny < w:
                    if not visited[nx][ny] and s[nx][ny] == '.':
                        q.append([nx, ny, z + 1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
H, W = map(int, input().split())
maze = [list(input()) for i in range(H)]
S = []
for i in range(H):
  for j in range(W):
    if maze[i][j] == ".":
      maze[i][j] = float("inf")
      S.append([i, j])
    else:
      maze[i][j] = -1
def bfs(H, W, maze, S):
  ans = 0
  for sy, sx in S:
    maze1 = copy.deepcopy(maze)
    maze1[sy][sx] = 0
    q = deque()
    q.append([sy,sx])
    while len(q)>0:
      y, x = q.popleft()
      for i, j in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
        nexty = y+i
        nextx = x+j
        if nexty < 0 or nexty>=H or nextx < 0 or nextx>=W:
          continue
        dist = maze1[nexty][nextx]
        if maze1[nexty][nextx] != -1:
          if dist > maze1[y][x]:
            maze1[nexty][nextx] = maze1[y][x] + 1
            q.append([nexty, nextx])
        ans = max(ans, maze1[nexty][nextx])
  print(ans)
bfs(H, W, maze, S)

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
maze = [list(input()) for j in range(H)]

def bfs(h,w):
  checked = [[False for i in range(W)] for j in range(H)]
  q = [(h,w,0)] if maze[h][w]=="." else []
  g_n = 0
  while q:
    h_,w_,n = q.pop(0)
    checked[h_][w_] = True
    g_n = max(n, g_n)
    for i,j in zip([0,0,-1,1],[-1,1,0,0]):
      if (0<=h_+i<H) and (0<=w_+j<W):
        if checked[h_+i][w_+j]: continue
        if maze[h_+i][w_+j]==".": q.append((h_+i,w_+j,n+1))
  return g_n

n = 0
for i in range(H):
  for j in range(W):
    n = max(n, bfs(i,j))
print(n)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
H, W = map(int, input().split())
maze = [list(input()) for i in range(H)]
S = []
for i in range(H):
  for j in range(W):
    if maze[i][j] == ".":
      maze[i][j] = float("inf")
      S.append([i, j])
    else:
      maze[i][j] = -1
def bfs(H, W, maze, S):
  ans = 0
  for sy, sx in S:
    maze1 = copy.deepcopy(maze)
    maze1[sy][sx] = 0
    q = deque()
    q.append([sy,sx])
    while len(q)>0:
      y, x = q.popleft()
      for i, j in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
        nexty = y+i
        nextx = x+j
        if nexty < 0 or nexty>=H or nextx < 0 or nextx>=W:
          continue
        dist = maze1[nexty][nextx]
        if maze1[nexty][nextx] != -1:
          if dist > maze1[y][x]:
            maze1[nexty][nextx] = maze1[y][x] + 1
            q.append([nexty, nextx])
    for i in range(len(maze1)):
      ans1 = max(maze1[i])
      ans = max(ans, ans1)
  print(ans)
bfs(H, W, maze, S)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = map(int,input().split())
maze = []
def mazecal(hs,ws):
    calmaze = [[-1 for _ in range(w)] for _ in range(h)]
    #step = 0
    que = deque([[hs,ws,0]])
    smax = 0
    while len(que)!=0:
        cur = que.popleft()
        calmaze[cur[0]][cur[1]] = cur[2]
        smax = max(smax,cur[2])
        if cur[0]>0   and maze[cur[0]-1][cur[1]]==0:
            if calmaze[cur[0]-1][cur[1]] ==-1 or calmaze[cur[0]-1][cur[1]] > cur[2]+1:
                 que.append([cur[0]-1,cur[1],  cur[2]+1])
        if cur[0]<h-1 and maze[cur[0]+1][cur[1]]==0:
            if calmaze[cur[0]+1][cur[1]] ==-1 or calmaze[cur[0]+1][cur[1]] > cur[2]+1:
                que.append([cur[0]+1,cur[1],  cur[2]+1])
        if cur[1]>0   and maze[cur[0]][cur[1]-1]==0:
            if calmaze[cur[0]][cur[1]-1] ==-1 or calmaze[cur[0]][cur[1]-1] > cur[2]+1:
                que.append([cur[0]  ,cur[1]-1,cur[2]+1])
        if cur[1]<w-1 and maze[cur[0]][cur[1]+1]==0:
            if calmaze[cur[0]][cur[1]+1] ==-1 or calmaze[cur[0]][cur[1]+1] > cur[2]+1:
                que.append([cur[0]  ,cur[1]+1,cur[2]+1])        
    return smax

for i in range(h):maze.append([0 if c=='.' else 1 for c in input()])
gmax = 0
for i in range(h):
    for j in range(w):
        if maze[i][j]==0:gmax = max(gmax,mazecal(i,j))
print(gmax)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
mss=[]
for i in range(H):
    mss.append([])
    for j in input():
        mss[i].append(j)
movable_list = []
for h in range(H):
    movable_list.append([])
    for w in range(W):
        movable_list[h].append([])
        if mss[h][w] != "#":
            if h-1 >= 0:
                if mss[h-1][w] != "#":
                    movable_list[h][w].append([h-1,w])
            if h+1 <=H-1:
                if mss[h+1][w] != "#":
                    movable_list[h][w].append([h+1, w])
            if w-1 >=0:
                if mss[h][w-1] != "#":
                    movable_list[h][w].append([h, w-1])
            if w+1 <= W-1:
                if mss[h][w+1] != "#":
                    movable_list[h][w].append([h, w+1])

max_list = [0]*(H*W)
for h in range(H):
    for w in range(W):
        canmove = movable_list[h][w]    
        pass_list = []
        if mss[h][w] != "#":
            pass_list.append([h,w])
            judge = True
            while judge:
                judge = False
                temp=[]
                for i in canmove:
                    if i not in pass_list: 
                        judge = True
                        pass_list.append(i)
                        for j in movable_list[i[0]][i[1]]:
                            if j not in pass_list:
                                temp.append(j)
                if judge:
                    max_list[h*W+w] += 1
                canmove = temp
                
                        
print(max(max_list))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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


def successors(x, y):
    locations = []
    # 下に行けるかの判定
    if (x + 1 < H) and (maze[x + 1][y] != '#'):
        locations.append((x + 1, y))
    # 上に行けるかの判定
    if (x - 1 >= 0) and (maze[x - 1][y] != '#'):
        locations.append((x - 1, y))
    # 右に行けるかの判定
    if (y + 1 < W) and (maze[x][y + 1] != '#'):
        locations.append((x, y + 1))
    # 左に行けるかの判定
    if (y - 1 >= 0) and (maze[x][y - 1] != '#'):
        locations.append((x, y - 1))
    return locations


def bfs(initial, successors):
    # goal判定はなく、一番遠いところで返す
    frontier = deque()
    frontier.append((initial, None))
    # tuple
    explored = {initial}

    while len(frontier):
        current_node = frontier.popleft()
        current_state = current_node[0]
        for child in successors(*current_state):
            if str(child) in [str(i) for i in explored]:
                continue
            explored.add(child)
            frontier.append((child, current_node))
    return current_node


def node_to_path_count(node):
    counter = 0
    while node[1] is not None:
        counter += 1
        node = node[1]
    return counter


ans = 0
for x in range(H):
    for y in range(W):
        if maze[x][y] == '.':
            solution = bfs((x, y), successors)
            counter = node_to_path_count(solution)
            if ans < counter:
                ans = counter

print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, W = map(int, input().split())
mss=[]
for i in range(H):
    mss.append([])
    for j in input():
        mss[i].append(j)
movable_list = []
for h in range(H):
    movable_list.append([])
    for w in range(W):
        movable_list[h].append([])
        if mss[h][w] != "#":
            if h-1 >= 0:
                if mss[h-1][w] != "#":
                    movable_list[h][w].append([h-1,w])
            if h+1 <=H-1:
                if mss[h+1][w] != "#":
                    movable_list[h][w].append([h+1, w])
            if w-1 >=0:
                if mss[h][w-1] != "#":
                    movable_list[h][w].append([h, w-1])
            if w+1 <= W-1:
                if mss[h][w+1] != "#":
                    movable_list[h][w].append([h, w+1])

max_list = [0]*(H*W)
for h in range(H):
    for w in range(W):
        canmove = movable_list[h][w]    
        pass_list = []
        if mss[h][w] != "#":
            pass_list.append([h,w])
            judge = True
            while judge:
                judge = False
                temp=[]
                for i in canmove:
                    if i not in pass_list: 
                        judge = True
                        pass_list.append(i)
                        for j in movable_list[i[0]][i[1]]:
                            temp.append(j)
                if judge:
                    max_list[h*W+w] += 1
                canmove = temp
                
                        
print(max(max_list))

Submission status: Time Limit Exceeded

Solution code:
H,W = map(int,input().split())
maze = [list(input()) for j in range(H)]

def bfs(h,w):
  checked = [(h,w)]
  q = [(h,w,0)] if maze[h][w]=="." else []
  g_n = 0
  while q:
    h_,w_,n = q.pop(0)
    g_n = max(n, g_n)
    for i,j in zip([0,0,-1,1],[-1,1,0,0]):
      if (0<=h_+i<H) and (0<=w_+j<W):
        pt = (h_+i,w_+j)
        if pt in checked: continue
        checked.append(pt)
        q = q + [pt+(n+1,)] if maze[pt[0]][pt[1]]=="." else q
  return g_n

n = 0
for i in range(H):
  for j in range(W):
    n = max(n, bfs(i,j))
print(n)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

        q = deque()
        q.append((i, j, 0))
        visited = [[False] * (w + 5) for _ in range(h + 5)]
        dirr = ([1, 0], [0, 1], [-1, 0], [0, -1])
        while len(q) != 0:
            x, y, z = q.popleft()
            ans = max(ans, z)
            visited[x][y] = True
            for p in range(4):
                nx, ny = x + dirr[p][0], y + dirr[p][1]
                if 0 <= nx < h and 0 <= ny < w:
                    if not visited[nx][ny] and s[nx][ny] == '.':
                        q.append((nx, ny, z + 1))
print(ans)

Submission status: Time Limit Exceeded

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





def BFS(sy,sx,gy,gx,Map):
    visited  = [[False for i in range(w)] for j in range(h)]
    q = deque()
    q.append((sy,sx,0))
    while q:
        y,x,cnt = q.popleft()
        if y<0 or h<=y or x<0 or w<=x or visited[y][x]==True:
            continue
        if y == gy and x == gx:
            return cnt
        if Map[y][x] == '#':
            visited[y][x] = True
            continue
        if Map[y][x] == '.' :
            
            cnt += 1
            visited[y][x] = True
            q.append((y+1,x,cnt))
            q.append((y-1,x,cnt))
            q.append((y,x+1,cnt))
            q.append((y,x-1,cnt))
            
    print('------------------')
    return 0




for i in range(h):
    for j in range(w):
        #print(i,j)
        if Map[i][j] != ('.'):
            continue
        start_y = i
        start_x = j
        for x in range(h-1,-1,-1):
            for y in range(w-1,-1,-1):
                
                if Map[x][y] != ('.'):
                    continue
                goal_y = x
                goal_x = y
                ans = max(ans,BFS(start_y,start_x,goal_y,goal_x,Map))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

h,w=map(int,input().split())
d=[]
for i in range(h):
    s=input()
    d.append(s)
x=h*w
p=[[x+1]*x for i in range(x)]
for i in range(x):
    for j in range(x):
        ih,iw=i//w,i%w
        jh,jw=j//w,j%w
        if "."==d[ih][iw]==d[jh][jw] and ih==jh and abs(iw-jw)==1:
            p[i][j]=1
            p[j][i]=1
        if "."==d[ih][iw]==d[jh][jw] and iw==jw and abs(ih-jh)==1:
            p[i][j]=1
            p[j][i]=1
        if i==j:
            p[i][j]=0
for i in range(x):
    for j in range(x):
        for k in range(x):
            ih,iw=i//w,i%w
            jh,jw=j//w,j%w
            kh,kw=k//w,k%w
            if d[ih][iw]==d[jh][jw]==d[kh][kw]==".":
                p[j][k]=min(p[j][k],p[j][i]+p[i][k])
ans=0
for i in p:
    for j in i:
        if j<x+1:
            ans=max(ans,j)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from collections import deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

H, W = map(int, readline().split())
S = np.array([list(readline().decode('utf-8').rstrip()) for _ in range(H)])


def adjacent_4(h, w):
    ret = []
    for (dh, dw) in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
        h_ = h + dh
        w_ = w + dw

        if (0 <= h_) & (h_ < H) & (0 <= w_) & (w_ < W):
            ret.append((h_, w_))
    return ret


def bfs(S, h, w):

    visited = np.full(S.shape, 10**9)
    visited[h][w] = 1

    que = deque()
    que.append((h, w))

    while len(que) != 0:
        pos = que.popleft()
        acc = visited[pos[0]][pos[1]]

        for adj in adjacent_4(pos[0], pos[1]):
            if S[adj[0]][adj[1]] == '#':
                continue
            acc_ = acc + 1
            if acc_ >= visited[adj[0]][adj[1]]:
                continue
            visited[adj[0]][adj[1]] = acc_
            que.append(adj)

    visited[visited == 10**9] = 0
    return visited.max() - 1


"""
ans = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            continue
        ans = max(ans, bfs(S, h, w))
"""
ans = max(bfs(S, h, w) for h in range(H) for w in range(W) if S[h][w] != '#')
print(int(ans))

Submission status: Time Limit Exceeded

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

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

ans = 0

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


def bfs(x, y):
    m = [[-1] * W for _ in range(H)]

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

    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 ans < v+1:
                    ans = v+1


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

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

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

        q = deque()
        q.append([i, j, 0])
        visited = [[False for _ in range(w + 5)] for _ in range(h + 5)]
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        while len(q) != 0:
            x, y, z = q.popleft()
            ans = max(ans, z)
            visited[x][y] = True
            for p in range(4):
                nx, ny = x + dirr[p][0], y + dirr[p][1]
                if 0 <= nx < h and 0 <= ny < w:
                    if not visited[nx][ny] and s[nx][ny] == '.':
                        q.append([nx, ny, z + 1])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = map(int,input().split())
maze = []
def mazecal(hs,ws):
    calmaze = [[-1 for _ in range(w)] for _ in range(h)]
    step = 0
    que = deque([[hs,ws,step]])
    while len(que)!=0:
        cur = que.popleft()
        #print('cur',cur)
        calmaze[cur[0]][cur[1]] = cur[2]
        if cur[0]>0   and maze[cur[0]-1][cur[1]]==0:
            if calmaze[cur[0]-1][cur[1]] ==-1 or calmaze[cur[0]-1][cur[1]] > cur[2]+1:
                 que.append([cur[0]-1,cur[1],  cur[2]+1])
        if cur[0]<h-1 and maze[cur[0]+1][cur[1]]==0:
            if calmaze[cur[0]+1][cur[1]] ==-1 or calmaze[cur[0]+1][cur[1]] > cur[2]+1:
                que.append([cur[0]+1,cur[1],  cur[2]+1])
        if cur[1]>0   and maze[cur[0]][cur[1]-1]==0:
            if calmaze[cur[0]][cur[1]-1] ==-1 or calmaze[cur[0]][cur[1]-1] > cur[2]+1:
                que.append([cur[0]  ,cur[1]-1,cur[2]+1])
        if cur[1]<w-1 and maze[cur[0]][cur[1]+1]==0:
            if calmaze[cur[0]][cur[1]+1] ==-1 or calmaze[cur[0]][cur[1]+1] > cur[2]+1:
                que.append([cur[0]  ,cur[1]+1,cur[2]+1])        
    smax = 0
    for i in range(h):smax = max(smax,max(calmaze[i]))
    return smax

for i in range(h):maze.append([0 if c=='.' else 1 for c in input()])
gmax = 0
for i in range(h):
    for j in range(w):
        if maze[i][j]==0:gmax = max(gmax,mazecal(i,j))
print(gmax)

Submission status: Time Limit Exceeded

Solution code:
import copy

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

S = ["#"] * (H+2)
S[0] = ["#"] * (W+2)
S[H+1] = ["#"] * (W+2)
for i in range(1,H+1):
    S[i] = ["#"]+ list(input()) + ["#"]

#print(S)
inf = 10 ** 3
data = [[[[inf for i in range(W+2)] for j in range(H+2)] for k in range(W+2)] for l in range(H+2)]

for i in range(1,H+1):
    for j in range(1,W+1):
        data[i][j][i][j] = 0

for m in range((H*W)//2):
    data_ = copy.copy(data)
    for i in range(1,H+1):
      for j in range(1,W+1):
        for k in range(1,H+1):
            for l in range(1,W+1):
                if S[i][j] == "#" or S[k][l] == "#":
                    continue
                data_[i][j][k][l] = min(data[i][j][k][l],data[i][j][k+1][l]+1,data[i][j][k-1][l]+1,data[i][j][k][l+1]+1,data[i][j][k][l-1]+1)

x = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        for k in range(1,H+1):
            for l in range(1,W+1):
                if x < data_[i][j][k][l] and data_[i][j][k][l] != inf:
                    x = data_[i][j][k][l]

print(x)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

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

visited = np.zeros((h + 5, w + 5), dtype = bool)
ans = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == '#': continue

        q = deque()
        q.append([i, j, 0])
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        while len(q) != 0:
            x, y, z = q[0]
            ans = max(ans, z)
            visited[x][y] = True
            for p in range(4):
                nx, ny = x + dirr[p][0], y + dirr[p][1]
                if 0 <= nx < h and 0 <= ny < w:
                    if not visited[nx][ny] and s[nx][ny] == '.':
                        q.append([nx, ny, z + 1])
            q.popleft()
        for a in range(h): 
            for b in range(w): 
                visited[a][b] = False
print(ans)

Submission status: Time Limit Exceeded

Solution code:
h, w = map(int, input().split())
n = h * w
INF = 1 << 30

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

dist = [[INF] * n for _ in range(n)]

for i in range(h):
    for j in range(w):
        if field[i][j] == '#':
            continue
        if j + 1 < w and field[i][j+1] != '#':
            dist[i * w + j][i * w + j + 1] = 1
            dist[i * w + j + 1][i * w + j] = 1
        if i + 1 < h and field[i+1][j] != '#':
            dist[i * w + j][(i+1) * w + j] = 1
            dist[(i+1) * w + j][i * w + j] = 1

# Warshall-Floyd 
for i in range(n):
    for j in range(n):
        for k in range(n):
            dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k])

ans = 0

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

print(ans)

Submission status: Time Limit Exceeded

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

move = [[0 for i in range(W)]for i in range(H)]

S = ["#" for i in range(H)]

M = 0

for i in range(H):
    S[i] = input()





def keisoku(sx,sy,ex,ey):
    global W
    global H
    end = False

    qx = queue.Queue()
    qy = queue.Queue()


    count = 1

    kyori = [[-1 for i in range(W)]for i in range(H)]
    kyori[ey][ex] == 0
    if ey < H-1:
        
        if S[ey+1][ex] == ".":
            kyori[ey+1][ex] = 1
            qx.put(ex)
            qy.put(ey+1)
    if ey >= 1:
        if S[ey-1][ex] == ".":
            kyori[ey-1][ex] = 1
            qx.put(ex)
            qy.put(ey-1)
    if ex < W -1:
            
        if S[ey][ex+1] == ".":
            kyori[ey][ex+1] = 1
            qx.put(ex+1)
            qy.put(ey)
    if ex >= 1:
        if S[ey][ex-1] == ".":
            kyori[ey][ex-1] = 1
            qx.put(ex-1)
            qy.put(ey)

    while(not end):
        x = qx.get()
        y = qy.get()
        
        if y < H -1:
                
            if S[y+1][x] == ".":
                qx.put(x)
                qy.put(y+1)
                kyori[y+1][x] = kyori[y][x]+1
        if y >= 1:
                
            if S[y-1][x] == ".":
                qx.put(x)
                qy.put(y-1)
                kyori[y-1][x] = kyori[y][x]+1
        if x < W -1:
                
            if S[y][x+1] == ".":
                qx.put(x+1)
                qy.put(y)
                kyori[y][x+1] =  kyori[y][x]+1

        if x >= 1:
                
            if S[y][x-1] == ".":
                qx.put(x-1)
                qy.put(y)
                kyori[y][x-1] = kyori[y][x]+1

        
        if kyori[sy][sx] != -1:
            end = True
    
    return kyori[sy][sx]
                    
for sx in range(W):
    for sy in range(H):
        for ex in range(W):
            for ey in range(H):
                if S[sy][sx] == "#" or S[ey][ex] == "#" or (sx == ex and sy == ey):
                    continue

                newmax = keisoku(sx,sy,ex,ey)
                if newmax > M:
                    M = newmax 

print(M)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque

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

ans = 0
for i in range(h):
    for j in range(w):
        q = deque()
        q.append([i, j, 0])
        if s[i][j] == '#': continue

        visited = np.zeros((h + 5, w + 5), dtype = bool)
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        mx = 0
        while len(q) != 0:
            x, y, z = q[0]
            ans = max(ans, z)
            visited[x][y] = True
            for p in range(4):
                nx, ny = x + dirr[p][0], y + dirr[p][1]
                if 0 <= nx < h and 0 <= ny < w:
                    if not visited[nx][ny] and s[nx][ny] == '.':
                        q.append([nx, ny, z + 1])
            q.popleft()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int,input().split())
S=[list(input()) for i in range(H)]
inf=float("inf")
d=[[1,0],[0,1],[-1,0],[0,-1]]
ans=0
for sx in range(H):
    for sy in range(W):
        for gx in range(H):
            for gy in range(W):
                if S[sx][sy]==S[gx][gy]==".":
                    data=[[inf]*W for i in range(H)]
                    que=[[sx,sy]]
                    data[sx][sy]=0
                    count=1
                    while que:
                        h=[]
                        for x,y in que:
                            for dx,dy in d:
                                nx,ny=x+dx,y+dy
                                if 0<=nx<H and 0<=ny<W and S[nx][ny]=="." and data[nx][ny]==inf:
                                    h.append([nx,ny])
                                    data[nx][ny]=count
                        que=h
                        count+=1
                    ans=max(ans,data[gx][gy])
print(ans)