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())
maze = []
for _ in range(H):
    maze.append(list(input()))


def bfs(initial):
    # goal判定はなく、一番遠いところで返す
    frontier = deque()
    frontier.append((initial, None))
    # tuple
    explored = {initial}
    while len(frontier):
        locations = []
        current_node = frontier.popleft()
        current_state = current_node[0]
        x, y = current_state
        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))
        for child in locations:
            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))
            counter = node_to_path_count(solution)
            if ans < counter:
                ans = counter

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter,defaultdict,deque
import sys
import bisect
import math
import itertools
import string
import queue
import copy
# import numpy as np
# import scipy
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
 
def inp(): # n=1
    return int(input())
def inpm(): # x=1,y=2
    return map(int,input().split())
def inpl(): # a=[1,2,3,4,5,...,n]
    return list(map(int, input().split()))
def inpls(): # a=['1','2','3',...,'n']
    return list(input().split())
def inplm(n): # x=[] 複数行
    return list(int(input()) for _ in range(n))
def inpll(n): # [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
    return [list(map(int, input().split())) for _ in range(n)]
 
 
def main():
    h, w = map(int, input().split())
    s = [list(input()) for _ in range(h)]
    
    ans = 0
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    for i in range(h):
        for j in range(w):
            if s[i][j] == '#': continue
    
            q = []
            q.append([i, j])
            visited = [[False for _ in range(w+5)] for _ in range(h + 5)]
            dist = [[0 for _ in range(w+5)] for _ in range(h + 5)]
            M = 0
            while q:
                x, y = q[0]
                q.pop(0)
                visited[x][y] = True
                for p in range(4):
                    nx, ny = x + dx[p], y + dy[p]
                    if 0 <= nx < h and 0 <= ny < w:
                        if not visited[nx][ny] and s[nx][ny] == '.':
                            q.append([nx, ny])
                            dist[nx][ny] = dist[x][y] + 1
                            if M<dist[nx][ny]:
                                M = dist[nx][ny]
            ans = max(ans,M)
    print(ans)
 
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
h,w = list(map(int,input().split()))
s = []
for i in range(h):
    sh = list(input())
    s.append(sh)   
ki = [[] for i in range(h*w)]
def ichi(a,b):
    return a + b*h
for a in range(h):
    for b in range(w):
        if s[a][b] == ".":
            if  a+1 < h and s[a+1][b] == "." :
                ki[ichi(a+1,b)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a+1,b))
            if  a-1 >= 0 and s[a-1][b] == ".":
                ki[ichi(a-1,b)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a-1,b))
            if b-1 >= 0 and s[a][b-1] == ".":
                ki[ichi(a,b-1)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a,b-1))
            if b+1 < w and s[a][b+1] == "." :
                ki[ichi(a,b+1)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a,b+1))
        else:
            pass
for i in range(w*h):
    ki[i] = list(set(ki[i]))
ans = [0]
for i in range(w*h):
    ikeru = deque([i])
    sumi = []
    kaisuu = [-1]*(w*h)
    kaisuu[i] = 0
    while ikeru:
        j = ikeru.popleft()
        sumi.append(j)
        for k in range(len(ki[j])):
            if not ki[j][k] in sumi:
                ikeru.append(ki[j][k])
                if kaisuu[ki[j][k]] > kaisuu[j] + 1:
                    kaisuu[ki[j][k]] = kaisuu[j] + 1
                elif kaisuu[ki[j][k]] == -1:
                    kaisuu[ki[j][k]] = kaisuu[j] + 1 
#        print(i,kaisuu,ikeru)
    ans.append(max(kaisuu))
#print(ans)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import numpy as np
def main():
    hw = list(map(int, input().split()))
    s = np.zeros((hw[0],hw[1]), dtype=int)
    validpoints = []
    for i in range(hw[0]):
        tmp = input()
        tm = [None]*hw[1]
        for j in range(hw[1]):
            if tmp[j] == '.':
                tm[j] = 0
                validpoints.append((i,j))
            elif tmp[j] == '#':
                tm[j] = 1
        s[i] = np.array(tm)

    ma = 0
    for i in validpoints:
        for j in validpoints:
            vis = np.array(s)
            cost = breadth(s,i,j,vis)
            if cost > ma:
                ma = cost
    print(ma)

    # print(breadth(s,(2,0),(0,4)))
    # print(breadth(s,(0,0),(1,0)))
    
def breadth(ss, start, goal, visited):
    newvis = np.array(visited)
    newvis[start] = 1
    if start == goal:
        return 0
    down = (start[0]+1,start[1])
    up = (start[0]-1,start[1])
    right = (start[0],start[1]+1)
    left = (start[0],start[1]-1)
    child = [down,up,right,left]
    child = list(filter(lambda i: 0 <= i[0] < len(ss) and 0 <= i[1] < len(ss[0]) and visited[i[0],i[1]] == 0, child))
    if len(child) > 0:
        mi = 99999
        for i in child:
            co = breadth(ss,i,goal,newvis)
            if mi > co:
                mi = co
        return 1+mi
    else:
        return 1
    

# def breadth(ss, start, goal):
#     q = deque()
#     visited = np.array(ss)
#     visited[start] = 1
#     q.append(start)
#     c = 0
#     while not len(q) == 0:
#         v = q.pop()
#         if v == goal:
#             break
#         down = (v[0]+1,v[1])
#         up = (v[0]-1,v[1])
#         right = (v[0],v[1]+1)
#         left = (v[0],v[1]-1)
#         child = [down,up,right,left]
#         child = list(filter(lambda i: 0 <= i[0] < len(ss) and 0 <= i[1] < len(ss[0]) and visited[i[0],i[1]] == 0, child))

#         if len(child) > 0:
#             for i in child:
#                 visited[i] = 1
#                 q.append(i)
#             c += 1
        
#     return c

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# BFS queue
import queue
import copy

import time
sss = time.time()
H, W = map(int,input().split())
b = [list(input()) for _ in range(H)]
dist = [[10**9 for _ in range(W)] for _ in range(H)]
start = (-1,-1)
qq = queue.Queue()
for i in range(H):
    for j in range(W):
        if b[i][j] == '.':
            qq.put((i,j))
far = 0
move = [(-1,0), (0,-1), (1,0), (0,1)]
def BFS(start, bb):
    dist = [[10**9 for _ in range(W)] for _ in range(H)]
    far = 0
    q = queue.Queue()
    q.put(start)
    dist[start[0]][start[1]] = 0
    # BFS
    while 1:
        now = q.get()
        x = now[0]
        y = now[1]
        bb[x][y] = '#'
        for elem in move:
            dx = elem[0]
            dy = elem[1]
            if x+dx>=0 and x+dx<= H-1 and y+dy>=0 and y+dy<=W-1:
                if bb[x+dx][y+dy] != '#':
                    if dist[x+dx][y+dy] > dist[x][y]:
                        dist[x+dx][y+dy] = dist[x][y] + 1
                        if dist[x+dx][y+dy] > far:
                            far = dist[x+dx][y+dy]
                        q.put((x+dx,y+dy))
        if q.empty():
            break
    return far
res = 0
while 1:
    ttt = time.time()
    if sss-ttt >= 1.8:
        break
    now = qq.get()
    res = max([res, BFS(now, copy.deepcopy(b))])
    if qq.empty():
        break
print(res)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy as dcopy
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
def mostfar(sx,sy,s):
  if s[sy][sx]=='#':
    return -1
  mx=len(s)*len(s[0])-1
  l=[[mx if s[j][i]=='.' else -1 for i in range(w)] for j in range(h)]
  step=0
  l[sy][sx]=0
  tmp=dcopy(l)
  while 1:
    step+=1
    for x in range(w):
      for y in range(h):
        if l[y][x]==step-1:
          if x!=0:
            l[y][x-1]=min(l[y][x-1],step)
          if x!=w-1:
            l[y][x+1]=min(l[y][x+1],step)
          if y!=0:
            l[y-1][x]=min(l[y-1][x],step)
          if y!=h-1:
            l[y+1][x]=min(l[y+1][x],step)
    if tmp==l:
      break
    tmp=dcopy(l)
  return max([max(r) for r in l])

ans=max(max(mostfar(x,y,s) for x in range(w)) for y in range(h))
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):
        idx=0
        if s[i][j] == '#': continue

        q = deque()
        q.append([i, j])
        visited = [[False] * (w + 5) for _ in range(h + 5)]
        dist = [[0] * (w + 5) for _ in range(h + 5)]
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        while len(q) > idx:
            x, y = q[idx]
            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])
                        dist[nx][ny] = dist[x][y] + 1
            idx += 1
        for x in dist:
            ans = max(ans, max(x))
print(ans)

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 bfs(initial):
    # goal判定はなく、一番遠いところで返す
    frontier = deque()
    frontier.append((initial, None))
    # tuple
    explored = {initial}
    while len(frontier):
        locations = []
        current_node = frontier.popleft()
        current_state = current_node[0]
        x, y = current_state
        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))
        for child in locations:
            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))
            counter = node_to_path_count(solution)
            if ans < counter:
                ans = counter

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):
        idx=0
        if s[i][j] == '#': continue

        q = deque()
        q.append([i, j])
        visited = [[False] * (w + 5) for _ in range(h + 5)]
        dist = [[0] * (w + 5) for _ in range(h + 5)]
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        while len(q) >= idx:
            x, y = q[idx]
            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])
                        dist[nx][ny] = dist[x][y] + 1
        for x in dist:
            ans = max(ans, max(x))
        idx+=1
print(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 = ["#" * (W+2)] + ["#" + input() + "#" for _ in range(H)] + ["#" * (W+2)]

ans = 0

for j in range(1, H+1):
    for i in range(1, W+1):
        if S[j][i] != ".":
            continue
        m = [[-1] * (W+2) for _ in range(H+2)]

        q = deque()
        q.append((j, i, 0))

        while q:
            y, x, v = q.popleft()
            m[y][x] = v
            for d in ((y, x + 1), (y, x-1), (y+1, x), (y-1, x)):
                dj, di = d
                if S[dj][di] == "." and m[dj][di] == -1:
                    q.append((dj, di, v+1))
                    if ans < v+1:
                        ans = v+1
print(ans)

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):
    # 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))
            counter = node_to_path_count(solution)
            if ans < counter:
                ans = counter

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def bfs():
  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
  ans = 0
  for k in range(len(S)):
    maze1 = copy.deepcopy(maze)
    maze1[S[k][0]][S[k][1]] = 0
    q = deque([[S[k][0],S[k][1]]])
    while q:
      y, x = q.popleft()
      for i, j in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
        nexty, nextx = y+i, x+j
        if nexty < 0 or nexty>=H or nextx < 0 or nextx>=W:
          continue
        dist1 = maze1[nexty][nextx]
        if dist1 != -1:
          if dist1 > maze1[y][x]:
            maze1[nexty][nextx] = maze1[y][x] + 1
            q.append([nexty, nextx])
            ans = max(ans, maze1[nexty][nextx])
  print(ans)
bfs()

Submission status: Time Limit Exceeded

Solution code:
def sol():
    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):
        ih,iw=i//w,i%w
        if d[ih][iw]!=".": continue
        for j in range(x):
            jh,jw=j//w,j%w
            if d[jh][jw]!=".": continue
            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)

if __name__=="__main__":
    sol()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

INF = float('inf')

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

point_list = []
for i in range(w*h):
    point_list.append([w*h]*w*h)
maze = []

Q = deque([])


for i in range(h):
    tmp = list(input())
    maze.append(tmp)

for s_y in range(h):
    for s_x in range(w):
        if maze[s_y][s_x] == "#":
            continue
        check = []
        Q.append((s_y,s_x))
        check.append((s_y,s_x))
        point_list[s_x+s_y*w][s_x+s_y*w] = 0
        while Q:
            y, x = Q.popleft()
            if y == 0:
                pass
            elif maze[y-1][x]=="#":
                pass
            else:
                point_list[s_x+s_y*w][x+(y-1)*w] = min(point_list[s_x+s_y*w][x+(y-1)*w],point_list[s_x+s_y*w][x+y*w]+1)
                if (y-1,x) in check:
                    pass
                else:
                    check.append((y-1,x))
                    Q.append((y-1,x))
                    

            if y == h-1 :
                pass
            elif maze[y+1][x]=="#":
                pass
            else:
                point_list[s_x+s_y*w][x+(y+1)*w] = min(point_list[s_x+s_y*w][x+(y+1)*w],point_list[s_x+s_y*w][x+y*w]+1)
                if (y+1,x) in check:
                    pass
                else:
                    check.append((y+1,x))
                    Q.append((y+1,x))
                    

            if x==0:
                pass
            elif maze[y][x-1]=="#":
                pass
            else:
                point_list[s_x+s_y*w][(x-1)+y*w] = min(point_list[s_x+s_y*w][(x-1)+y*w],point_list[s_x+s_y*w][x+y*w]+1)
                if (y,x-1) in check:
                    pass
                else:
                    check.append((y,x-1))
                    Q.append((y,x-1))
                    

            if x==w-1:
                pass
            elif maze[y][x+1]=="#":
                pass
            else:
                point_list[s_x+s_y*w][(x+1)+y*w] = min(point_list[s_x+s_y*w][(x+1)+y*w],point_list[s_x+s_y*w][x+y*w]+1)
                if (y,x+1) in check:
                    pass
                else:
                    check.append((y,x+1))
                    Q.append((y,x+1))
                    
max_list = []
for i in range(w*h):
    tmp = set(point_list[i])
    if min(tmp)==w*h:
        continue
    if w*h in tmp:
        tmp.remove(w*h)
    max_list.append(max(tmp))

ans = max(max_list)
print(ans)

Submission status: Time Limit Exceeded

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

dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]
mx = 0 
for i in range(H):
        for j in range(W):
                if S[i][j] == ".":
                        q = queue.Queue()
                        q.put([i, j, 0]) 
                        checked = [[0 for l in range(W)] for k in range(H)]
                        while not q.empty():
                                di = q.get()    
                                if mx < di[2]:
                                        mx = di[2]
                                checked[di[0]][di[1]] = -1
                                for k in range(4):
                                        nh = di[0] + dy[k]
                                        nx = di[1] + dx[k]
                                        if 0 <= nx < W and 0 <= nh < H and checked[nh][nx] == 0:
                                                if S[nh][nx] == ".":
                                                        q.put([nh, nx, di[2] + 1]) 
print(mx)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def bfs():
  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
  ans = 0
  for k in range(len(S)):
    maze1 = copy.deepcopy(maze)
    maze1[S[k][0]][S[k][1]] = 0
    q = deque([[S[k][0],S[k][1]]])
    while q:
      y, x = q.popleft()
      for i, j in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
        nexty, nextx = y+i, 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()

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

for j in range(H):
    for i in range(W):
        if S[j][i] != ".":
            continue
        m = [[-1] * W for _ in range(H)]

        q = deque()
        q.append((j, i, 0))

        while q:
            y, x, v = q.popleft()
            m[y][x] = v
            for d in ((y, x + 1), (y, x-1), (y+1, x), (y-1, x)):
                dj, di = d
                if 0 <= dj < H and 0 <= di < W and S[dj][di] == "." and m[dj][di] == -1:
                    q.append((dj, di, v+1))
                    if ans < v+1:
                        ans = v+1
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])
        visited = [[False] * (w + 5) for _ in range(h + 5)]
        dist = [[0] * (w + 5) for _ in range(h + 5)]
        dirr = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        while len(q) != 0:
            x, y = q.popleft()
            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])
                        dist[nx][ny] = dist[x][y] + 1
        for x in dist:
            ans = max(ans, max(x))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def bfs():
  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
  ans = 0
  q = deque()
  for k in range(len(S)):
    maze1 = copy.deepcopy(maze)
    maze1[S[k][0]][S[k][1]] = 0
    q.append([S[k][0],S[k][1]])
    while len(q)>0:
      y, x = q.popleft()
      for i, j in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
        nexty, nextx = y+i, 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()

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

for j in range(H):
    for i in range(W):
        if S[j][i] != ".":
            continue
        m = [[-1] * W for _ in range(H)]

        q = deque()
        q.append((j, i, 0))

        while q:
            y, x, v = q.popleft()
            m[y][x] = v
            for d in ((y, x + 1), (y, x-1), (y+1, x), (y-1, x)):
                dj = d[0]
                di = d[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
print(ans)

Submission status: Time Limit Exceeded

Solution code:
#n = int(input())
h,w = list(map(int,input().split()))
s = []
for i in range(h):
    sh = list(input())
    s.append(sh)
#ki = ["n"]*(h*w)    
ki = [[] for i in range(h*w)]
def ichi(a,b):
    return a + b*h
for a in range(h):
    for b in range(w):
        if s[a][b] == ".":
            if  a+1 < h and s[a+1][b] == "." :
                ki[ichi(a+1,b)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a+1,b))
            if  a-1 >= 0 and s[a-1][b] == ".":
                ki[ichi(a-1,b)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a-1,b))
            if b-1 >= 0 and s[a][b-1] == ".":
                ki[ichi(a,b-1)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a,b-1))
            if b+1 < w and s[a][b+1] == "." :
                ki[ichi(a,b+1)].append(ichi(a,b))
                ki[ichi(a,b)].append(ichi(a,b+1))
        else:
            pass
for i in range(w*h):
    ki[i] = list(set(ki[i]))
ans = [0]
for i in range(w*h):
    ikeru = [i]
    sumi = []
    kaisuu = [-1]*(w*h)
    kaisuu[i] = 0
    while len(ikeru) > 0:
        j = ikeru.pop(0)
        sumi.append(j)
        for k in range(len(ki[j])):
            if not ki[j][k] in sumi:
                ikeru.append(ki[j][k])
                if kaisuu[ki[j][k]] > kaisuu[j] + 1:
                    kaisuu[ki[j][k]] = kaisuu[j] + 1
                elif kaisuu[ki[j][k]] == -1:
                    kaisuu[ki[j][k]] = kaisuu[j] + 1 
#        print(i,kaisuu,ikeru)
    ans.append(max(kaisuu))
#print(ans)
print(max(ans))

Submission status: Time Limit Exceeded

Solution code:
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):
    ih,iw=i//w,i%w
    if d[ih][iw]!=".": continue
    for j in range(x):
        jh,jw=j//w,j%w
        if d[jh][jw]!=".": continue
        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:
from collections import deque
import copy
def bfs():
  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
  ans = 0
  for k in range(len(S)):
    maze1 = copy.deepcopy(maze)
    maze1[S[k][0]][S[k][1]] = 0
    q = deque()
    q.append([S[k][0],S[k][1]])
    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()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import copy
def bfs():
  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
  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()

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 d in ((j, i + 1), (j, i-1), (j+1, i), (j-1, i)):
            dj = d[0]
            di = d[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)