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
h, w = map(int, input().split())
s = [list(input()) for i in range(h)]
work = [[[] for j in range(w)] for i in range(h)]
result = 0
for i in range(h):
    for j in range(w):
        append = work[i][j].append
        if i<h-1 and s[i+1][j] == ".":
            append([i+1,j])
        if i>0 and s[i-1][j] == ".":
            append([i-1,j])
        if j<w-1 and s[i][j+1] == ".":
            append([i,j+1])
        if j>0 and s[i][j-1] == ".":
            append([i,j-1])
for i in range(h):
    for j in range(w):
        if s[i][j] != ".":
            continue
        q = deque([[i, j]])
        temp = [[i, j]]
        popleft = q.popleft
        append = q.append
        d = -1
        count = 1
        counter = 0
        for k in range(h*w):
            x, y = popleft()
            count -= 1
            for el in work[x][y]:
                if el not in temp:
                    counter += 1
                    append(el)
                    temp.append(el)
            if count == 0:
                d += 1
                count = counter
                counter = 0
            if len(q) == 0:
                break
        result = result if result>d else d
print(result)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product


def read():
    H, W = list(map(int, input().split()))
    S = ''
    S += ('#' * (W+2))
    for h in range(H):
        buf = input()
        S += '#' + buf + '#'
    S += ('#' * (W+2))
    return H, W, S


def bfs(yx, H, W, S):
    dirs = [1, W+2, -1, -W-2]
    visited = [False] * ((H+2) * (W+2))
    q = deque()
    q.appendleft((yx, 0))
    max_depth = 0
    while len(q) > 0:
        yx, depth = q.pop()
        visited[yx] = True
        max_depth = max(max_depth, depth)
        for dyx in dirs:
            nyx = yx + dyx
            if S[nyx] == '.' and not visited[nyx]:
                q.appendleft((nyx, depth+1))
    return max_depth


def solve(H, W, S):
    dist_max = 0
    for yx in range((H+2) * (W+2)):
        if S[yx] == '.':
            d = bfs(yx, H, W, S)
            dist_max = max(d, dist_max)
    return dist_max


if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product


def read():
    H, W = list(map(int, input().split()))
    S = ''
    S += ('#' * (W+2))
    for h in range(H):
        buf = input()
        S += '#' + buf + '#'
    S += ('#' * (W+2))
    return H, W, S


def bfs(yx, H, W, S):
    dirs = [1, W+2, -1, -W-2]
    visited = [False for i in range((H+2) * (W+2))]
    q = deque()
    q.appendleft((yx, 0))
    max_depth = 0
    while len(q) > 0:
        yx, depth = q.pop()
        visited[yx] = True
        max_depth = max(max_depth, depth)
        for dyx in dirs:
            nyx = yx + dyx
            if S[nyx] == '.' and not visited[nyx]:
                q.appendleft((nyx, depth+1))
    return max_depth


def solve(H, W, S):
    dist_max = 0
    for yx in range((H+2) * (W+2)):
        if S[yx] == '.':
            d = bfs(yx, H, W, S)
            dist_max = max(d, dist_max)
    return dist_max


if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product


def read():
    H, W = list(map(int, input().split()))
    S = list()
    S.append('#' * (W+2))
    for h in range(H):
        s = '#' + input() + '#'
        S.append(s)
    S.append('#' * (W+2))
    return H, W, S


def bfs(y, x, H, W, S):
    dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    visited = [[False for j in range(W+2)] for i in range(H+2)]
    q = deque()
    q.appendleft((y, x, 0))
    max_depth = 0
    while len(q) > 0:
        y, x, depth = q.pop()
        visited[y][x] = True
        max_depth = max(max_depth, depth)
        for dy, dx in dirs:
            ny, nx = y+dy, x+dx
            if S[ny][nx] == '.' and not visited[ny][nx]:
                q.appendleft((ny, nx, depth+1))
    return max_depth


def solve(H, W, S):
    dist_max = 0
    for i, j in product(range(1, H+1), range(1, W+1)):
        if S[i][j] == '.':
            d = bfs(i, j, H, W, S)
            dist_max = max(d, dist_max)
    return dist_max


if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from itertools import product


def read():
    H, W = list(map(int, input().split()))
    S = list()
    S.append(['#'] * (W+2))
    for h in range(H):
        s = list('#' + input() + '#')
        S.append(s)
    S.append(['#'] * (W+2))
    return H, W, S


def bfs(y, x, H, W, S):
    dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    visited = [[False for j in range(W+2)] for i in range(H+2)]
    q = deque()
    q.appendleft((y, x, 0))
    max_depth = 0
    while len(q) > 0:
        y, x, depth = q.pop()
        visited[y][x] = True
        max_depth = max(max_depth, depth)
        for dy, dx in dirs:
            ny, nx = y+dy, x+dx
            if S[ny][nx] == '.' and not visited[ny][nx]:
                q.appendleft((ny, nx, depth+1))
    return max_depth


def solve(H, W, S):
    dist_max = 0
    for i, j in product(range(1, H+1), range(1, W+1)):
        if S[i][j] == '.':
            d = bfs(i, j, H, W, S)
            dist_max = max(d, dist_max)
    return dist_max


if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


def read():
    H, W = list(map(int, input().split()))
    S = list()
    S.append(['#'] * (W+2))
    for h in range(H):
        s = list('#' + input() + '#')
        S.append(s)
    S.append(['#'] * (W+2))
    return H, W, S


def bfs(y, x, H, W, S):
    visited = [[False for j in range(W+2)] for i in range(H+2)]
    q = deque()
    q.appendleft((y, x, 0))
    max_depth = 0
    while len(q) > 0:
        y, x, depth = q.pop()
        visited[y][x] = True
        max_depth = max(max_depth, depth)
        for dy, dx in [(0,1), (1,0), (0,-1), (-1,0)]:
            ny, nx = y+dy, x+dx
            if S[ny][nx] == '.' and not visited[ny][nx]:
                q.appendleft((ny, nx, depth+1))
    return max_depth


def reset_depth(H, W, depth, S, INF=10**7):
    for i in range(H+2):
        for j in range(W+2):
            if S[i][j] == '#':
                depth[i][j] = -2
            else:
                depth[i][j] = -1


def solve(H, W, S):
    dist_max = 0
    for i in range(1, H+1):
        for j in range(1, W+1):
            if S[i][j] == '.':
                d = bfs(i, j, H, W, S)
                dist_max = max(d, dist_max)
    return dist_max


if __name__ == '__main__':
    inputs = read()
    print("{}".format(solve(*inputs)))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
INF = 1e9
dx = [-1, 0, 1, 0]
dy = [0, -1, 0, 1]


def bfs(sy, sx, gy, gx):
    if wall[sy][sx]=="#":
        return 0
    que = deque()
    que.append((sy, sx))
    d[sy][sx] = 0
    m = 0
    while len(que) > 0:
        y, x = que.popleft()

        for i in range(4):
            ny = y+dy[i]
            nx = x+dx[i]
            if 0 <= ny and ny < h and 0 <= nx and nx < w and wall[ny][nx] != "#" and d[ny][nx] <0:
                que.append((ny, nx))
                d[ny][nx] = d[y][x]+1
    return d[gy][gx]


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

ans = 0
for i in range(h):
    for j in range(w):
        for k in range(h):
            for l in range(w):
                d = [[-1]*w for _ in range(h)]
                a = bfs(i, j, k, l)
                ans = max(ans, a)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
from itertools import product

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

ans=-1

def dfs(start,goal):
    distance=[[-1]*H for j in range(W)]
    li_x=[1,-1,0,0]
    li_y=[0,0,1,-1]
    q = queue.Queue()
    q.put(start)
    distance[start[0]][start[1]]=0

    while not q.empty():
        hoge=q.get()
        x=hoge[0]
        y=hoge[1]
        dis=distance[x][y]

        for i in range(4):
            x1=x+li_x[i]
            y1=y+li_y[i]
            if (0 <=x1 < W and 0 <= y1 < H):
                if distance[x1][y1] == -1:
                    if S[y1][x1]=='.':
                        q.put([x1,y1])
                        distance[x1][y1]=dis+1

    return distance[goal[0]][goal[1]]

for sx,sy,gx,gy in product(range(W),range(H),range(W),range(H)):

                if S[sy][sx]=='.' and S[gy][gx]=='.':
                    re=dfs([sx,sy],[gx,gy])
                    if re > ans:
                        ans=re

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
H, W = map(int, input().split())
S= [input() for i in range(H)]

ans=-1

def dfs(start,goal):
    distance=[[-1]*H for j in range(W)]
    li_x=[1,-1,0,0]
    li_y=[0,0,1,-1]
    q = queue.Queue()
    q.put(start)
    distance[start[0]][start[1]]=0

    while not q.empty():
        hoge=q.get()
        x=hoge[0]
        y=hoge[1]
        dis=distance[x][y]

        for i in range(4):
            x1=x+li_x[i]
            y1=y+li_y[i]
            if (0 <=x1 < W and 0 <= y1 < H):
                if distance[x1][y1] == -1:
                    if S[y1][x1]=='.':
                        q.put([x1,y1])
                        distance[x1][y1]=dis+1

    return distance[goal[0]][goal[1]]

done=[]
for sx in range(W):
    for gx in range(W):
        for sy in range(H):
            for gy in range(H):
                if S[sy][sx]=='.' and S[gy][gx]=='.':
                    if [gx,gy,sx,sy] not in done:
                        re=dfs([sx,sy],[gx,gy])
                        done.append([sx,sy,gx,gy])
                        if re > ans:
                            ans=re

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
H, W = map(int, input().split())
S= [input() for i in range(H)]

ans=-1

def dfs(start,goal):
    distance=[[-1]*H for j in range(W)]
    li_x=[1,-1,0,0]
    li_y=[0,0,1,-1]
    q = queue.Queue()
    q.put(start)
    distance[start[0]][start[1]]=0

    while not q.empty():
        hoge=q.get()
        x=hoge[0]
        y=hoge[1]
        dis=distance[x][y]

        for i in range(4):
            x1=x+li_x[i]
            y1=y+li_y[i]
            if (0 <=x1 < W and 0 <= y1 < H):
                if distance[x1][y1] == -1:
                    if S[y1][x1]=='.':
                        q.put([x1,y1])
                        distance[x1][y1]=dis+1

    return distance[goal[0]][goal[1]]

for sx in range(W):
    for gx in range(W):
        for sy in range(H):
            for gy in range(H):
                if S[sy][sx]=='.' and S[gy][gx]=='.':
                    re=dfs([sx,sy],[gx,gy])
                    if re > ans:
                        ans=re

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
H, W = map(int, input().split())
S= [input() for i in range(H)]

ans=-1

def dfs(start,goal):
    distance=[[-1]*H for j in range(W)]
    li_x=[1,-1,0,0]
    li_y=[0,0,1,-1]
    q = queue.Queue()
    q.put(start)
    distance[start[0]][start[1]]=0

    while not q.empty():
        hoge=q.get()
        x=hoge[0]
        y=hoge[1]
        dis=distance[x][y]

        for i in range(4):
            x1=x+li_x[i]
            y1=y+li_y[i]
            if (0 <=x1 < W and 0 <= y1 < H):
                if distance[x1][y1] == -1:
                    if S[y1][x1]=='.':
                        q.put([x1,y1])
                        distance[x1][y1]=dis+1

    return distance[goal[0]][goal[1]]

for sx in range(W):
    for gx in range(W):
        for sy in range(H):
            for gy in range(H):
                if S[sy][sx]=='.' and S[gy][gx]=='.':
                    re=dfs([sx,sy],[gx,gy])
                    if re > ans:
                        ans=re

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import namedtuple
from queue import Queue
from copy import deepcopy

def bfs(start, stage):
    if stage[start.y][start.x] == "#":
        return -1
    ans = 0
    q = Queue()
    q.put(start)
    stage[start.y][start.x] = 0
    while not q.empty():
        current = q.get()
        for move in moves:
            nxt = point(current.y + move.y, current.x + move.x)
            can_move = 0 <= nxt.y < h and 0 <= nxt.x < w and stage[nxt.y][nxt.x] == "."
            if can_move:
                q.put(nxt)
                stage[nxt.y][nxt.x] = stage[current.y][current.x] + 1
                ans = stage[current.y][current.x] + 1
    return ans


point = namedtuple("point", "y, x")
moves = [point(-1, 0), point(0, 1), point(1, 0), point(0, -1)]
h, w = map(int, input().split())
S = [list(input()) for _ in range(h)]
ans = -1
for y in range(h):
    for x in range(w):
        steps = bfs(point(y, x), deepcopy(S))
        ans = max(ans, steps)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
h, w = map(int, input().split())
MAZE = ['#'*(w+2)]
for _ in range(h):
    MAZE.append("#"+input()+"#")
else:
    MAZE.append('#'*(w+2))

INF = 10**3
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def bfs(init_x, init_y):
    dp = [[INF]*(w+2) for _ in range(h+2)]
    q = Queue()
    q.put((init_x, init_y))
    dp[init_x][init_y] = 0
    MAX = 0
    while not q.empty():
        x, y = q.get()
        for i, j in directions:
            if MAZE[x+i][y+j] == '#':
                continue
            if dp[x+i][y+j] != INF:
                continue
            q.put((x+i, y+j))
        dp[x][y] = min(dp[x][y], min(dp[x+v][y+w]+1 for v, w in directions))
        MAX = max(MAX, dp[x][y])
    return MAX


ans = 0
for i in range(1, h+1):
    for j in range(1, w+1):
        if MAZE[i][j] == '#':
            continue
        ans = max(ans, bfs(i, j))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from queue import Queue
h, w = map(int, input().split())
MAZE = ['#'*(w+2)]
for _ in range(h):
    MAZE.append("#"+input()+"#")
else:
    MAZE.append('#'*(w+2))

INF = 10**3
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]


def bfs(init_x, init_y):
    dp = [[INF]*(w+2) for _ in range(h+2)]
    q = Queue()
    q.put((init_x, init_y))
    dp[init_x][init_y] = 0
    while not q.empty():
        x, y = q.get()
        for i, j in directions:
            if MAZE[x+i][y+j] == '#':
                continue
            if dp[x+i][y+j] != INF:
                continue
            q.put((x+i, y+j))
        dp[x][y] = min(dp[x][y], min(dp[x+v][y+w]+1 for v, w in directions))
    return dp


ans = 0
for i in range(1, h+1):
    for j in range(1, w+1):
        if MAZE[i][j] == '#':
            continue
        dp = bfs(i, j)
        ans = max(
            ans,  max(max([x for x in row if x < INF]+[0]) for row in dp))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

U, D, L, R = (-1, 0), (+1, 0), (0, -1), (0, +1)

is_good = lambda x, y, R, C: True if x < R and x >= 0 and y < C and y >= 0 else False


def traverse(grid, start, end):
  d = deque([(start, 0)])
  visited = set()
  while d:
    node, path = d.popleft()
    if node == end:
      break
    cx, cy = node
    for dx, dy in U, D, L, R:
      if is_good(cx + dx, cy + dy, len(grid), len(grid[0])) and grid[cx + dx][cy + dy] != '#' and (cx + dx, cy + dy) not in visited:
        nx, ny = cx + dx, cy + dy
        visited.add((nx, ny))
        d.append([(nx, ny), path+1])
  #print(start, end, path)
  return path


def bfs():
  R, C = tuple(map(int, input().split()))
  grid =[list(input()) for _ in range(R)]
  answer = 0
  for row in range(R):
    for col in range(C):
      if grid[row][col] != '#':
        start = (row, col)
      for rw in range(R):
        for cl in range(C):
          if grid[row][col] != '#':
            end = (rw, cl)
            answer = max(answer, traverse(grid, start, end))
  return answer


print(bfs())

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
H, W = map(int, input().split())
X = [input() for _ in range(H)]
maxloc = -10

def bfs(sx, sy, gx, gy):
  dist = [[-1]*W for _ in range(H)]
  dist[sx-1][sy-1] = 0
  q = deque([(sx-1, sy-1)])
  while q:
    u, v = q.popleft()
    for i, j in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
      if not(0 <= u+i < H and 0 <= v+j < W):
        continue
    
      if(dist[u+i][v+j] >= 0 or X[u+i][v+j] == "#"):
        continue

      dist[u+i][v+j] = dist[u][v]+1
      q.append((u+i, v+j))

  return dist[gx-1][gy-1]

for i in range(H):
  for j in range(W):
    sx = i
    sy = j
    for k in range(H):
      for l in range(W):
        gx = k
        gy = l
        if(bfs(i+1, j+1, k+1, l+1) > maxloc):
          maxloc = bfs(i+1, j+1, k+1, l+1)
          
print(maxloc)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
H, W = map(int, input().split())
M = []
for i in range(H):
    M.append(list(input()))


def getLength(Sx, Sy, Gx, Gy):
    def bigcost():
        return 10**16
    costs = defaultdict(bigcost)
    costs[(Sx, Sy)] = 0
    current = [(Sx, Sy)]
    visited = set()
    while len(current) > 0:
        next = []
        for v in current:
            c = costs[v]
            if v[0] > 0 and M[v[1]][v[0]-1] == ".":
                coord = (v[0]-1, v[1])
                if coord not in visited:
                    visited.add(coord)
                    next.append(coord)
                    costs[coord] = min(c+1, costs[coord])
            if v[0] < W-1 and M[v[1]][v[0]+1] == ".":
                coord = (v[0]+1, v[1])
                if coord not in visited:
                    visited.add(coord)
                    next.append(coord)
                    costs[coord] = min(c+1, costs[coord])
            if v[1] < H-1 and M[v[1]+1][v[0]] == ".":
                coord = (v[0], v[1]+1)
                if coord not in visited:
                    visited.add(coord)
                    next.append(coord)
                    costs[coord] = min(c+1, costs[coord])
            if v[1] > 0 and M[v[1]-1][v[0]] == ".":
                coord = (v[0], v[1]-1)
                if coord not in visited:
                    visited.add(coord)
                    next.append(coord)
                    costs[coord] = min(c+1, costs[coord])
        current = next
    return costs[(Gx, Gy)]


result = 0
for Sx in range(W):
    for Gx in range(W):
        for Sy in range(H):
            for Gy in range(H):
                if M[Sy][Sx] == '.' and M[Gy][Gx] == '.':
                    result = max(result, getLength(Sx, Sy, Gx, Gy))
print(result)

Submission status: Time Limit Exceeded

Solution code:
h,w=map(int,input().split())
s=[list(input()) for i in range(h)]
inf=1000000000
wf=[[inf]*(h*w) for i in range(h*w)]
for i in range(h*w):
    k,l=i//w,i%w
    #print(l)
    if s[k][l]=="#":
        continue
    if k!=0:
        if s[k-1][l]==".":
            wf[i][i-w]=1
    if k!=h-1:
        if s[k+1][l]==".":
            wf[i][i+w]=1
    if l!=0:
        if s[k][l-1]==".":
            wf[i][i-1]=1
    if l!=w-1:
        if s[k][l+1]==".":
            wf[i][i+1]=1
    wf[i][i]=0
for i in range(h*w):
    for j in range(h*w):
        for k in range(h*w):
            wf[j][k]=min(wf[j][k],wf[j][i]+wf[i][k])
ans=0
for i in range(h*w):
    for j in range(h*w):
        if wf[i][j]!=inf:
            ans=max(ans,wf[i][j])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
import sys
def input():
    return sys.stdin.readline()[:]
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
q = queue.Queue
d = []
for i in range(h):
  s = [j for j in input()]
  d.append(s)

def find_possible(i, j, ng):
  if i >= h-1:
    iaround = [i, i-1]
  elif i<=0:
    iaround = [i, i+1]
  else:
    iaround = [i, i-1, i+1]
  if j >= w-1:
    jaround = [j, j-1]
  elif j<=0:
    jaround = [j, j+1]
  else:
    jaround = [j, j-1, j+1]
  retv = []
  for a1 in iaround:
    for a2 in jaround:
      if [a1, a2] in ng or abs(a1-i) == abs(a2-j):
        continue
      elif d[a1][a2] == '.':
        retv.append([a1, a2])
  #print(i,j,retv)
  return retv

def bfs(qu):
  #includes points=[y][x], distance, parents=[[y][x]]
  used = [[-1 for _ in range(w)] for _ in range(h)]
  m = 0
  while not qu.empty():
    current = qu.get()
    row = current[0][0]
    column = current[0][1]
#    print(row, column, used[row][column])
    if used[row][column] > current[1] or used[row][column]<0:
      used[row][column] = current[1]
#      print(used)
#      print('update:', current[1])
      for a in find_possible(row, column, current[2]):
#          print('extend:',a,current[1]+1, tmp)          
        qu.put([a,current[1]+1, current[2] + [[row, column]]])
   #       if current[1]+1 > m:
   #         m = current[1]+1
#    print()
  m = 0
#  for i in used:
#    for j in i:
#      if m < j:
#        m = j
#  return m
  return used
m = 0
cans = []
for i in range(h):
  for j in range(w):
    if d[i][j] == '#':
      continue
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    cans.append(t)
import numpy as np
m = np.array(cans)

print(np.max(m))
#print(max(cans))

Submission status: Time Limit Exceeded

Solution code:
import queue
import sys
def input():
    return sys.stdin.readline()[:]
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
q = queue.Queue
d = []
for i in range(h):
  s = [j for j in input()]
  d.append(s)

def find_possible(i, j, ng):
  if i >= h-1:
    iaround = [i, i-1]
  elif i<=0:
    iaround = [i, i+1]
  else:
    iaround = [i, i-1, i+1]
  if j >= w-1:
    jaround = [j, j-1]
  elif j<=0:
    jaround = [j, j+1]
  else:
    jaround = [j, j-1, j+1]
  retv = []
  for a1 in iaround:
    for a2 in jaround:
      if [a1, a2] in ng or abs(a1-i) == abs(a2-j):
        continue
      elif d[a1][a2] == '.':
        retv.append([a1, a2])
  #print(i,j,retv)
  return retv

def bfs(qu):
  #includes points=[y][x], distance, parents=[[y][x]]
  used = [[-1 for _ in range(w)] for _ in range(h)]
  m = 0
  while not qu.empty():
    current = qu.get()
    row = current[0][0]
    column = current[0][1]
#    print(row, column, used[row][column])
    if used[row][column] > current[1] or used[row][column]<0:
      used[row][column] = current[1]
#      print(used)
#      print('update:', current[1])
      for a in find_possible(row, column, current[2]):
#          print('extend:',a,current[1]+1, tmp)          
        qu.put([a,current[1]+1, current[2] + [[row, column]]])
   #       if current[1]+1 > m:
   #         m = current[1]+1
#    print()
  m = 0
  for i in used:
    for j in i:
      if m < j:
        m = j
  return m
m = 0
cans = []
for i in range(h):
  for j in range(w):
    if d[i][j] == '#':
      continue
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    cans.append(t)
#import numpy as np
#m = np.array(cans)

#print(np.max(m))
print(max(cans))

Submission status: Time Limit Exceeded

Solution code:
import queue
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
q = queue.Queue
d = []
for i in range(h):
  s = [j for j in input()]
  d.append(s)
def find_possible(i, j, ng):
  if i >= h-1:
    iaround = [i, i-1]
  elif i<=0:
    iaround = [i, i+1]
  else:
    iaround = [i, i-1, i+1]
  if j >= w-1:
    jaround = [j, j-1]
  elif j<=0:
    jaround = [j, j+1]
  else:
    jaround = [j, j-1, j+1]
  retv = []
  for a1 in iaround:
    for a2 in jaround:
      if [a1, a2] in ng or abs(a1-i) == abs(a2-j):
        continue
      elif d[a1][a2] == '.':
        retv.append([a1, a2])
  #print(i,j,retv)
  return retv

def bfs(qu):
  #includes points=[y][x], distance, parents=[[y][x]]
  used = [[-1 for _ in range(w)] for _ in range(h)]
  m = 0
  while not qu.empty():
    current = qu.get()
    row = current[0][0]
    column = current[0][1]
#    print(row, column, used[row][column])
    if used[row][column] > current[1] or used[row][column]<0:
      used[row][column] = current[1]
#      print(used)
#      print('update:', current[1])
      for a in find_possible(row, column, current[2]):
#          print('extend:',a,current[1]+1, tmp)          
        qu.put([a,current[1]+1, current[2] + [[row, column]]])
   #       if current[1]+1 > m:
   #         m = current[1]+1
#    print()
  m = 0
  for i in used:
    for j in i:
      if m < j:
        m = j
  return m
m = 0
cans = []
for i in range(h):
  for j in range(w):
    if d[i][j] == '#':
      continue
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    cans.append(t)
#import numpy as np
#m = np.array(cans)

#print(np.max(m))
print(max(cans))

Submission status: Time Limit Exceeded

Solution code:
import queue
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
q = queue.Queue
d = []
for i in range(h):
  s = [j for j in input()]
  d.append(s)
from collections import defaultdict
def find_possible(i, j, ng):
  if i >= h-1:
    iaround = [i, i-1]
  elif i<=0:
    iaround = [i, i+1]
  else:
    iaround = [i, i-1, i+1]
  if j >= w-1:
    jaround = [j, j-1]
  elif j<=0:
    jaround = [j, j+1]
  else:
    jaround = [j, j-1, j+1]
  retv = []
  for a1 in iaround:
    for a2 in jaround:
      if [a1, a2] in ng or abs(a1-i) == abs(a2-j):
        continue
      elif d[a1][a2] == '.':
        retv.append([a1, a2])
  #print(i,j,retv)
  return retv

def bfs(s):
  qu = queue.Queue()
  qu.put([s, 0, []])
  #includes points=[y][x], distance, parents=[[y][x]]
  used = [[-1 for _ in range(w)] for _ in range(h)]
  m = 0
  while not qu.empty():
    current = qu.get()
    row = current[0][0]
    column = current[0][1]
#    print(row, column, used[row][column])
    if used[row][column] > current[1] or used[row][column]<0:
      used[row][column] = current[1]
#      print(used)
#      print('update:', current[1])
      for a in find_possible(row, column, current[2]):
#          print('extend:',a,current[1]+1, tmp)          
        qu.put([a,current[1]+1, current[2] + [[row, column]]])
   #       if current[1]+1 > m:
   #         m = current[1]+1
#    print()
  m = 0
  return used
m = 0
cans = []
for i in range(h):
  for j in range(w):
    if d[i][j] == '#':
      continue
    t = bfs([i,j])
    cans.append(t)
import numpy as np
m = np.array(cans)

print(np.max(m))

Submission status: Time Limit Exceeded

Solution code:
import queue
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
q = queue.Queue
d = []
for i in range(h):
  s = [j for j in input()]
  d.append(s)
from collections import defaultdict
def find_possible(i, j, ng):
  if i >= h-1:
    iaround = [i, i-1]
  elif i<=0:
    iaround = [i, i+1]
  else:
    iaround = [i, i-1, i+1]
  if j >= w-1:
    jaround = [j, j-1]
  elif j<=0:
    jaround = [j, j+1]
  else:
    jaround = [j, j-1, j+1]
  retv = []
  for a1 in iaround:
    for a2 in jaround:
      if [a1, a2] in ng or abs(a1-i) == abs(a2-j):
        continue
      elif d[a1][a2] == '.':
        retv.append([a1, a2])
  #print(i,j,retv)
  return retv

def bfs(qu):
  #includes points=[y][x], distance, parents=[[y][x]]
  used = [[-1 for _ in range(w)] for _ in range(h)]
  m = 0
  while not qu.empty():
    current = qu.get()
    row = current[0][0]
    column = current[0][1]
#    print(row, column, used[row][column])
    if used[row][column] > current[1] or used[row][column]<0:
      used[row][column] = current[1]
#      print(used)
#      print('update:', current[1])
      for a in find_possible(row, column, current[2]):
#          print('extend:',a,current[1]+1, tmp)          
        qu.put([a,current[1]+1, current[2] + [[row, column]]])
   #       if current[1]+1 > m:
   #         m = current[1]+1
#    print()
  m = 0
  return used
m = 0
cans = []
for i in range(h):
  for j in range(w):
    if d[i][j] == '#':
      continue
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    cans.append(t)
import numpy as np
m = np.array(cans)

print(np.max(m))

Submission status: Time Limit Exceeded

Solution code:
import queue
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
q = queue.Queue
d = []
for i in range(h):
  s = [j for j in input()]
  d.append(s)
from collections import defaultdict
def find_possible(i, j):
  if i >= h-1:
    iaround = [i, i-1]
  elif i<=0:
    iaround = [i, i+1]
  else:
    iaround = [i, i-1, i+1]
  if j >= w-1:
    jaround = [j, j-1]
  elif j<=0:
    jaround = [j, j+1]
  else:
    jaround = [j, j-1, j+1]
  retv = []
  for a1 in iaround:
    for a2 in jaround:
      if abs(a1-i) == abs(a2-j):
        continue
      elif d[a1][a2] == '.':
        retv.append([a1, a2])
  #print(i,j,retv)
  return retv

def bfs(qu):
  #includes points=[y][x], distance, parents=[[y][x]]
  used = [[-1 for _ in range(w)] for _ in range(h)]
  m = 0
  while not qu.empty():
    current = qu.get()
    row = current[0][0]
    column = current[0][1]
#    print(row, column, used[row][column])
    if used[row][column] > current[1] or used[row][column]<0:
      used[row][column] = current[1]
#      print(used)
#      print('update:', current[1])
      for a in find_possible(row, column):
        if (a not in current[2]) and (a != [row, column]):
          tmp = current[2] + [[row, column]]
#          print('extend:',a,current[1]+1, tmp)          
          qu.put([a,current[1]+1, tmp])
   #       if current[1]+1 > m:
   #         m = current[1]+1
#    print()
  m = 0
  return used
m = 0
cans = []
for i in range(h):
  for j in range(w):
    if d[i][j] == '#':
      continue
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    cans.append(t)
import numpy as np
m = np.array(cans)

print(np.max(m))