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  = [int(v) for v in input().split()]
S = ['#'+input()+'#' for _ in range(H)]
S.insert(0,"#"*(W+2))
S.append("#"*(W+2))

ans = 0

for y in range(1,H+1):
    for x in range(1,W+1):
        if S[y][x] == "#": continue
        queue = deque([[x,y,0]])
        visited = [[False for _ in range(W+2)] for _ in range(H+2)]
        visited[y][x] = True
        while queue:
            x,y,c = queue.pop()
            visited[y][x] = True
            for ny,nx in [[y+1,x],[y,x+1],[y-1,x],[y,x-1]]:
                if visited[ny][nx] or S[ny][nx] == '#': continue
                queue.appendleft([nx,ny,c+1])

            ans = max(ans,c)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

def print_l(l):
    print(' '.join(map(str, l)))

class Interval():
    def __init__(self, li):
        self.li = li
        self.n = len(li)
        self.sum_li = [li[0]]
        for i in range(1, self.n):
            self.sum_li.append(self.sum_li[i-1] + li[i])

    def sum(self, a, b=None):
        if b is None:
            return self.sum(0, a)

        res = self.sum_li[min(self.n-1, b-1)]
        if a > 0:
            res -= self.sum_li[a-1]
        return res

h,w = l_in()
S = []
for _ in range(h):
    s = s_in()
    S.append(s)
    
from collections import deque

res = 0
for i in range(h):
    for j in range(w):
        q = deque()
        s = set()
        check = lambda x,y: (not (x,y) in s) and x >= 0 and x < h and y >=0 and y < w and S[x][y] == '.'
        
        if S[i][j] == '.':
            q.append((i,j,0))

        while len(q) > 0:
            i,j,d = q.popleft()
            s.add((i,j))
            res = max(d,res)
            
            if check(i+1,j):
                q.append((i+1,j,d+1))
            if check(i-1,j):
                q.append((i-1,j,d+1))
            if check(i,j+1):
                q.append((i,j+1,d+1))
            if check(i,j-1):
                q.append((i,j-1,d+1))

print(res)

Submission status: Time Limit Exceeded

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


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

def bfs(sx,sy,gx,gy):
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    d = [[float('inf')]*w for i in range(h)]
    q = deque()
    q.append((sx,sy))
    d[sx][sy] = 0
    while q:
        x,y = q.popleft()
        if x == gx and y == gy:
            break
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if  0<= nx < h and 0 <= ny < w and d[nx][ny]==float('inf') and s[nx][ny]=='.':
                q.append((nx,ny))
                d[nx][ny] = d[x][y]+1
    return d[gx][gy]

count = 0
for i in range(h):
    for j in range(w):
        for k in range(h):
            for l in range(w):
                if s[i][j] != '#' and s[k][l] != '#':
                    count  = max(count, bfs(i,j,k,l))
print(count)

Submission status: Time Limit Exceeded

Solution code:
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

from copy import deepcopy
import itertools

h,w=n1()
s=s2(h)
s=["#"+x+"#" for x in s]
s=["#"*(w+2)]+s+["#"*(w+2)]
meiro_original=[[0]*(w+2) for _ in range(h+2)]
road=[]
for i in range(len(s)):
    for j in range(len(s[i])):
        if s[i][j]=="#":
            meiro_original[i][j]=2
        else:
            meiro_original[i][j]=0
            road.append([i,j])

def calc(start):
    ans=0
    meiro=deepcopy(meiro_original)
    pos=[[start[0],start[1],0]]
    while len(pos)>0:
        x,y,c=pos.pop(0)

        meiro[x][y]=2

        f=False
        if meiro[x-1][y]<2:
            pos.append([x-1,y,c+1])
            f=True
        if meiro[x+1][y]<2:
            pos.append([x+1,y,c+1])
            f=True
        if meiro[x][y-1]<2:
            pos.append([x,y-1,c+1]) 
            f=True
        if meiro[x][y+1]<2:
            pos.append([x,y+1,c+1])
            f=True
        if f==False:
            ans=max(ans,c)   
    return ans

l=0
for x in road:
    l=max(l,calc(x))
    
print(l)

Submission status: Time Limit Exceeded

Solution code:
def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

from copy import deepcopy
import itertools

h,w=n1()
s=s2(h)
s=["#"+x+"#" for x in s]
s=["#"*(w+2)]+s+["#"*(w+2)]
meiro_original=[[0]*(w+2) for _ in range(h+2)]
road=[]
for i in range(len(s)):
    for j in range(len(s[i])):
        if s[i][j]=="#":
            meiro_original[i][j]=2
        else:
            meiro_original[i][j]=0
            road.append([i,j])


def calc(start,goal):
    min_count=9999999999
    meiro=deepcopy(meiro_original)
    meiro[goal[0]][goal[1]]=1
    pos=[[start[0],start[1],0]]
    while len(pos)>0:
        x,y,count=pos.pop(0)

        if meiro[x][y]==1:
            min_count=min(count,min_count)
            break

        meiro[x][y]=2

        if meiro[x-1][y]<2:
            pos.append([x-1,y,count+1])    
        if meiro[x+1][y]<2:
            pos.append([x+1,y,count+1])    
        if meiro[x][y-1]<2:
            pos.append([x,y-1,count+1]) 
        if meiro[x][y+1]<2:
            pos.append([x,y+1,count+1])

    return min_count
ans=0
for x in itertools.combinations(road,2):
    ans=max(ans,calc(x[0],x[1]))
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

def bfs(start, maze, H, W):
    max_step = 0
    used = [[False for _ in range(W)] for _ in range(H)]
    stack = deque([[start, 0]])
    while stack:
        (i, j), step = stack.popleft()
        used[i][j] = True
        if maze[i][j] == '#':
            continue
        max_step = max(max_step, step)
        for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
            if 0 <= x < H and 0 <= y < W and not used[x][y]:
                stack.append([(x, y), step + 1])
    return max_step

if __name__ == '__main__':
    H, W = map(int, input().split())
    S = []
    for _ in range(H):
        S.append(list(input()))
    ret = 0
    for i in range(H):
        for j in range(W):
            ret = max(ret, bfs((i, j), S, H, W))
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
INF = 20 * 20 + 1

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

    ans = 0
    goal_base = [[-1 for _ in range(W+2)] for _ in range(H)]
    goal_base = [[-1 for _ in range(W+2)]] + goal_base + [[-1 for _ in range(W+2)]]
    for h in range(H):
        for w in range(W):
            if maze[h][w] == '#':
                goal_base[h+1][w+1] = -1
            else:
                goal_base[h+1][w+1] = INF

    for hs in range(H):
        for ws in range(W):
            if maze[hs][ws] == '#':
                continue

            goal_dists = copy.deepcopy(goal_base)
            goal_dists[hs+1][ws+1] = 0
            d = deque([[hs+1, ws+1]])
            while len(d) > 0:
                ht, wt = d.popleft()
                dist = goal_dists[ht][wt]
                for dh, dw in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                    if goal_dists[ht+dh][wt+dw] > dist:
                        goal_dists[ht+dh][wt+dw] = dist + 1
                        d.append([ht+dh, wt+dw])
            
            max_dist = [goal_dists[h][w] for w in range(1, W+2) for h in range(1, H+2) if goal_dists[h][w] != INF]
            ans = max(ans, max(max_dist))

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
INF = 20 * 20 + 1

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

    ans = 0
    goal_dists_base = [[-1 for _ in range(W+2)] for _ in range(H)]
    goal_dists_base = [[-1 for _ in range(W+2)]] + goal_dists_base + [[-1 for _ in range(W+2)]]
    for h in range(H):
        for w in range(W):
            if maze[h][w] == '#':
                goal_dists_base[h+1][w+1] = -1
            else:
                goal_dists_base[h+1][w+1] = INF

    for hs in range(H):
        for ws in range(W):
            if maze[hs][ws] == '#':
                continue
            
            goal_dists = copy.deepcopy(goal_dists_base)
            goal_dists[hs+1][ws+1] = 0
            d = deque([[hs+1, ws+1]])
            while len(d) > 0:
                ht, wt = d.popleft()
                dist = goal_dists[ht][wt]
                for dh, dw in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                    if goal_dists[ht+dh][wt+dw] > dist:
                        goal_dists[ht+dh][wt+dw] = dist + 1
                        d.append([ht+dh, wt+dw])
            
            max_dist = 0
            for h in range(1, H+2):
                for w in range(1, W+2):
                    if goal_dists[h][w] == INF:
                        continue
                    max_dist = max(max_dist, goal_dists[h][w])
            ans = max(ans, max_dist)

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
INF = 20 * 20 + 1

def main():
    H, W = map(int, input().split())
    maze = [list(input()) for _ in range(H)]
    
    ans = 0
    for hs in range(H):
        for ws in range(W):
            if maze[hs][ws] == '#':
                continue
            goal_dists = [[-1 for _ in range(W+2)] for _ in range(H)]
            goal_dists = [[-1 for _ in range(W+2)]] + goal_dists + [[-1 for _ in range(W+2)]]
            for h in range(H):
                for w in range(W):
                    if maze[h][w] == '#':
                        goal_dists[h+1][w+1] = -1
                    else:
                        goal_dists[h+1][w+1] = INF
            goal_dists[hs+1][ws+1] = 0
            d = deque([[hs+1, ws+1]])
            while len(d) > 0:
                ht, wt = d.popleft()
                dist = goal_dists[ht][wt]
                for dh, dw in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
                    if goal_dists[ht+dh][wt+dw] == -1:
                        continue
                    if goal_dists[ht+dh][wt+dw] > dist:
                        goal_dists[ht+dh][wt+dw] = dist + 1
                        d.append([ht+dh, wt+dw])
            
            max_dist = 0
            for h in range(1, H+2):
                for w in range(1, W+2):
                    if goal_dists[h][w] == INF:
                        continue
                    max_dist = max(max_dist, goal_dists[h][w])
            ans = max(ans, max_dist)
    
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from itertools import product

h, w = map(int, input().split())
s = np.full((h, w), 'x', dtype='U1')
for i in range(h):
    s[i] = list(input())

d = np.full((h*w, w*h), float('inf'))
for i in range(h * w):
    d[i, i] = 0

for i, k in product(range(h), range(w)):
    if s[i, k] == '#':
        continue
    for dy, dx in ((-1, 0), (0, -1), (0, 1), (1, 0)):
        y, x = i + dy, k + dx
        if y < 0 or h <= y or x < 0 or w <= x or s[y, x] == '#':
            continue
        d[i*w+k, y*w+x] = 1
        d[y*w+x, i*w+k] = 1

# warshall-floyd
for k, i, j in product(range(h * w), repeat=3):
    d[i, j] = min(d[i, j], d[i, k] + d[k, j])

print(d.astype('i8').max())

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w=map(int,input().split())
S=[]
pos=[]
for i in range(h):
  l=input()
  L=[]
  for j in range(w):
    if l[j]=='.':
      L.append('.')
      pos.append((i,j))
    else:
      L.append('#')
  S.append(L)
Maze=[[float('inf')]*w for i in range(h)]
def bfs(h,w,S,Maze,sy,sx,gy,gx):
    maze=Maze
    maze=[[float('inf')]*w for i in range(h)]
    maze[sy][sx]=0
    que=deque([[sy,sx]])
    while que: #キューの中に入っているということはまだ調べる余地有り
        y,x=que.popleft()
        for (i,j) in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if 0<=nexty<=h-1 and 0<=nextx<=w-1:
              dist=maze[nexty][nextx]
              if S[nexty][nextx]!='#':
                if dist>maze[y][x]+1: #今の経路から(nexty,nextx)に進む方が距離が短くなるなら
                    maze[nexty][nextx]=maze[y][x]+1
                    que.append([nexty,nextx])

    return maze[gy][gx]
M=0
for (sy,sx) in pos:
  for (gy,gx) in pos:
    if bfs(h,w,S,Maze,sy,sx,gy,gx)>M:
      M=bfs(h,w,S,Maze,sy,sx,gy,gx)

print(M)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

h,w=map(int,input().split())
S=[]
pos=[]
for i in range(h):
  l=input()
  L=[]
  for j in range(w):
    if l[j]=='.':
      L.append('.')
      pos.append((i,j))
    else:
      L.append('#')
  S.append(L)
      
def bfs(h,w,S,sy,sx,gy,gx):
    maze=[[float('inf')]*w for i in range(h)]
    maze[sy][sx]=0
    que=deque([[sy,sx]])
    while que: #キューの中に入っているということはまだ調べる余地有り
        y,x=que.popleft()
        for (i,j) in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if 0<=nexty<=h-1 and 0<=nextx<=w-1:
              dist=maze[nexty][nextx]
              if S[nexty][nextx]!='#':
                if dist>maze[y][x]+1: #今の経路から(nexty,nextx)に進む方が距離が短くなるなら
                    maze[nexty][nextx]=maze[y][x]+1
                    que.append([nexty,nextx])

    return maze[gy][gx]
M=0
for (sy,sx) in pos:
  for (gy,gx) in pos:
    if bfs(h,w,S,sy,sx,gy,gx)>M:
      M=bfs(h,w,S,sy,sx,gy,gx)
      (Sx,Sy)=(sx,sy)
      (Gx,Gy)=(gx,gy)
      
print(M)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

H, W = map(int, input().split())
Maze = [list(input()) for _ in range(H)]
ans = 0
sy = 0
while sy < H:
  sx = 0
  while sx < W:
    if Maze[sy][sx] == ".":
      M_cnt = 0
      q = deque()
      memo = [[False]*(W) for _ in range((H))]
      q.append([[sy, sx],0])
      while q:
        cur, cnt = q.popleft()
        cy, cx = cur
        memo[cy][cx] = True
        M_cnt = max(M_cnt, cnt)
        for ny, nx in zip((cy, cy, cy+1, cy-1) , (cx+1, cx-1, cx, cx)):
          if ny >= 0 and ny < H and nx >= 0 and nx < W and Maze[ny][nx] == "." and not memo[ny][nx]:
            q.append([[ny, nx],cnt+1])
      ans = max(ans, M_cnt)
    sx += 1
  sy += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def solve(maze, start):
  memo = [[False]*len(maze[0]) for _ in range(len(maze))]
  q = deque()
  q.append([start,0])
  ans = 0
  while q:
    cur, cnt = q.popleft()
    ans = max(ans, cnt)
    memo[cur[0]][cur[1]] = True
    for y, x in zip((0,0,1,-1),(1,-1,0,0)):
      if maze[cur[0]+y][cur[1]+x] == "." and not memo[cur[0]+y][cur[1]+x]:
        q.append([[cur[0]+y,cur[1]+x],cnt+1])
  return ans


H, W = map(int, input().split())
Maze = [["#"]*(W+2)]+[["#"]+list(input())+["#"] for _ in range(H)] + [["#"]*(W+2)]
Ans = 0
sy = 1
while sy <= H:
  sx = 1
  while sx <= W:
    if Maze[sy][sx] == ".":
      Ans = max(Ans, solve(Maze, [sy, sx]))
    sx += 1
  sy += 1
print(Ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def solve(maze, start):
  memo = [[False]*len(maze[0]) for _ in range(len(maze))]
  q = deque()
  q.append([start,0])
  ans = 0
  while q:
    cur, cnt = q.popleft()
    ans = max(ans, cnt)
    memo[cur[0]][cur[1]] = True
    for y, x in zip((0,0,1,-1),(1,-1,0,0)):
      if maze[cur[0]+y][cur[1]+x] == "." and not memo[cur[0]+y][cur[1]+x]:
        q.append([[cur[0]+y,cur[1]+x],cnt+1])
  return ans

H, W = map(int, input().split())
Maze = [["#"]*(W+2)]+[["#"]+list(input())+["#"] for _ in range(H)] + [["#"]*(W+2)]
Ans = 0
sy = 1
while sy <= H:
  sx = 1
  while sx <= W:
    if Maze[sy][sx] == "#":
      continue
    else:
      Ans = solve(Maze, [sy, sx])
    sx += 1
  sy+= 1
print(Ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def solve(maze, start):
  memo = [[False]*len(maze[0]) for _ in range(len(maze))]
  q = deque()
  q.append([start,0])
  ans = 0
  while q:
    cur, cnt = q.popleft()
    ans = max(ans, cnt)
    memo[cur[0]][cur[1]] = True
    for y, x in zip((0,0,1,-1),(1,-1,0,0)):
      if maze[cur[0]+y][cur[1]+x] == "." and not memo[cur[0]+y][cur[1]+x]:
        q.append([[cur[0]+y,cur[1]+x],cnt+1])
  return ans


H, W = map(int, input().split())
Maze = [["#"]*(W+2)]+[["#"]+list(input())+["#"] for _ in range(H)] + [["#"]*(W+2)]
Ans = 0
for sy in range(1, H+1):
  for sx in range(1, W+1):
    if Maze[sy][sx] == "#":
      continue
    else:
      Ans = max(Ans, solve(Maze, [sy, sx]))
print(Ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def solve(maze, start):
  memo = deque()
  q = deque()
  q.append([start,0])
  ans = 0
  while q:
    cur, cnt = q.popleft()
    ans = max(ans, cnt)
    memo.append(cur)
    for y, x in zip((0,0,1,-1),(1,-1,0,0)):
      if maze[cur[0]+y][cur[1]+x] == "." and not [cur[0]+y,cur[1]+x] in memo:
        q.append([[cur[0]+y,cur[1]+x],cnt+1])
  return ans


H, W = map(int, input().split())
Maze = [["#"]*(W+2)]+[["#"]+list(input())+["#"] for _ in range(H)] + [["#"]*(W+2)]
Ans = 0
for sy in range(1, H+1):
  for sx in range(1, W+1):
    if Maze[sy][sx] == "#":
      continue
    else:
      Ans = max(Ans, solve(Maze, [sy, sx]))
print(Ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import numpy as np


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    depth = np.full((H+2, W+2), -1, dtype=np.int32)
    q = deque()
    q.append((y, x))
    depth[y][x] = 0
    max_depth = 0
    while q:
        y, x = q.popleft()
        max_depth = max(max_depth, depth[y][x])
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if depth[ny][nx] == -1 and S[ny][nx] == '.':
                depth[ny][nx] = depth[y][x] + 1
                q.append((ny, nx))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                d = bfs(y+1, x+1, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import numpy as np


def bfs(y, x, H, W, S):
    dirs = [(-1, 0), (0, -1), (1, 0), (0, 1)]
    depth = np.ones((H+2, W+2), dtype=np.int32) * -1
    q = deque()
    q.append((y, x))
    depth[y][x] = 0
    max_depth = 0
    while q:
        y, x = q.popleft()
        max_depth = max(max_depth, depth[y][x])
        for dy, dx in dirs:
            ny, nx = y + dy, x + dx
            if depth[ny][nx] == -1 and S[ny][nx] == '.':
                depth[ny][nx] = depth[y][x] + 1
                q.append((ny, nx))
    return max_depth


def solve():
    H, W = map(int, input().split())
    S = list()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H):
        for x in range(W):
            if S[y+1][x+1] == '.':
                d = bfs(y+1, x+1, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


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


def solve():
    H, W = map(int, input().split())
    S = deque()
    S.append(['#'] * (W+2))
    for _ in range(H):
        buf = input()
        S.append(list('#' + buf + '#'))
    S.append(['#'] * (W+2))

    dist_max = 0
    for y in range(H+2):
        for x in range(W+2):
            if S[y][x] == '.':
                d = bfs(y, x, H, W, S)
                dist_max = max(d, dist_max)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

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

max_move = 0
for start_i in range(h):
  for start_j in range(w):
    if maze[start_i][start_j] == '.':
      queue = deque([(0, start_i, start_j)])
      yet = [[True] * w for _ in range(h)]
      while queue:
        move, i, j = queue.popleft()
        yet[i][j] = False
        if i != 0 and maze[i-1][j] == '.' and yet[i-1][j]:
          queue.append((move + 1, i - 1, j))
        if i != h - 1 and maze[i+1][j] == '.' and yet[i+1][j]:
          queue.append((move + 1, i + 1, j))
        if j != 0 and maze[i][j-1] == '.' and yet[i][j-1]:
          queue.append((move + 1, i, j - 1))
        if j != w - 1 and maze[i][j+1] == '.' and yet[i][j+1]:
          queue.append((move + 1, i, j + 1))
      if move > max_move:
        max_move = move

print(max_move)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


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


def solve():
    H, W = map(int, input().split())
    S = deque()
    S.append('#' * (W+2))
    for h in range(H):
        buf = input()
        S.append('#' + buf + '#')
    S.append('#' * (W+2))
    S = ''.join(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)
    print(dist_max)


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque


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


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

    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)
    print(dist_max)


if __name__ == '__main__':
    solve()

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 = [0] * ((H+2) * (W+2))
    q = deque()
    q.append((yx, 0))
    max_depth = 0
    while len(q) > 0:
        yx, depth = q.popleft()
        visited[yx] = 1
        max_depth = max(max_depth, depth)
        if max_depth == H * W:
            break
        for dyx in dirs:
            nyx = yx + dyx
            if S[nyx] == '.' and visited[nyx] == 0:
                q.append((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 = [0] * ((H+2) * (W+2))
    q = deque()
    q.append((yx, 0))
    max_depth = 0
    while len(q) > 0:
        yx, depth = q.popleft()
        visited[yx] = 1
        max_depth = max(max_depth, depth)
        for dyx in dirs:
            nyx = yx + dyx
            if S[nyx] == '.' and visited[nyx] == 0:
                q.append((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
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])
q = deque()
popleft = q.popleft
append = q.append
for i in range(h):
    for j in range(w):
        if s[i][j] != ".":
            continue
        q.clear()
        q.append([i, j])
        temp = [[i, j]]
        tempappend = temp.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)
                    tempappend(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.append((yx, 0))
    max_depth = 0
    while len(q) > 0:
        yx, depth = q.popleft()
        visited[yx] = True
        max_depth = max(max_depth, depth)
        for dyx in dirs:
            nyx = yx + dyx
            if S[nyx] == '.' and not visited[nyx]:
                q.append((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
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
        tempappend = temp.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)
                    tempappend(el)
            if count == 0:
                d += 1
                count = counter
                counter = 0
            if len(q) == 0:
                break
        result = result if result>d else d
print(result)