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:
import queue
h, w = map(int, input().split())
bigger = h if h > w else w
dfs = [[0]*bigger]*bigger
used_dfs = [[[]]*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
  for row in used:
    for column in row:
      if column == -1:
        continue
      elif m < column:
        m = column
  return m
m = 0
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)
    if m < t:
      m = t
print(m)

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    H, W = map(int, input().split())
    s = [input() for _ in range(H)]

    def bfs(row, col, R, C, s):
        from collections import deque
        q = deque()
        q.append([(row, col), 0])
        seen = set()
        ans = 0
        while q:
            (r, c), dist = q.popleft()
            ans = max(dist, ans)
            seen.add((r, c))
            for (next_r, next_c) in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
                if (next_r, next_c) not in seen and \
                    0 <= next_r < R and 0 <= next_c < C and \
                   s[next_r][next_c] == '.':
                    q.append([(next_r, next_c), dist + 1])
        return ans

    max_v = 0
    for h in range(H):
        for w in range(W):
            if s[h][w] == '.':
                max_v = max(max_v, bfs(h, w, H, W, s))
    print(max_v)
resolve()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    H, W = map(int, input().split())
    s = [input() for _ in range(H)]

    def bfs(row, col, R, C, s):
        from collections import deque
        q = deque()
        q.append([(row, col), 0])
        seen = set()
        ans = 0
        while q:
            (r, c), dist = q.popleft()
            ans = max(dist, ans)
            seen.add((r, c))
            for (next_r, next_c) in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
                if 0 <= next_r < R and 0 <= next_c < C and \
                   (next_r, next_c) not in seen and \
                   s[next_r][next_c] == '.':
                    q.append([(next_r, next_c), dist + 1])
        return ans

    max_v = 0
    for h in range(H):
        for w in range(W):
            if s[h][w] == '.':
                max_v = max(max_v, bfs(h, w, H, W, s))
    print(max_v)
resolve()

Submission status: Time Limit Exceeded

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

S = [["#"]*W for i in range(H)]
      
for i in range(H):
    S[i] = list(input())

Sp = [["#"]*(W+2) for i in range(H+2)]
       
for i in range(1,H+1):
    for j in range(1,W+1):
        Sp[i][j] = S[i-1][j-1]

mx = 0

for i in range(1,H+1):
    for j in range(1,W+1):
        if Sp[i][j] == "." and not(Sp[i-1][j]==Sp[i+1][j]==Sp[i][j-1]==Sp[i][j+1]=="."):
            Wo = [[-1]*(W+2) for i in range(H+2)]
            Wo[i][j] = 0
            cnt = 1
            while cnt>0:
                cnt = 0
                for k in range(1,H+1):
                    for l in range(1,W+1):
                        if Wo[k][l] != -1:
                            if Sp[k-1][l] == ".":
                                if Wo[k-1][l] == -1:
                                    Wo[k-1][l] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k+1][l] == ".":
                                if Wo[k+1][l] == -1:
                                    Wo[k+1][l] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k][l-1] == ".":
                                if Wo[k][l-1] == -1:
                                    Wo[k][l-1] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k][l+1] == ".":
                                if Wo[k][l+1] == -1:
                                    Wo[k][l+1] = Wo[k][l]+1
                                    cnt+=1
            for k in range(1,H+1):
                mx=max(mx,max(Wo[k]))

print(mx)

Submission status: Time Limit Exceeded

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

S = [["#"]*W for i in range(H)]
      
for i in range(H):
    S[i] = list(input())

Sp = [["#"]*(W+2) for i in range(H+2)]
       
for i in range(1,H+1):
    for j in range(1,W+1):
        Sp[i][j] = S[i-1][j-1]

mx = 0

for i in range(1,H+1):
    for j in range(1,W+1):
        if Sp[i][j] == ".":
            Wo = [[-1]*(W+2) for i in range(H+2)]
            Wo[i][j] = 0
            cnt = 1
            while cnt>0:
                cnt = 0
                for k in range(1,H+1):
                    for l in range(1,W+1):
                        if Wo[k][l] != -1:
                            if Sp[k-1][l] == ".":
                                if Wo[k-1][l] == -1:
                                    Wo[k-1][l] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k+1][l] == ".":
                                if Wo[k+1][l] == -1:
                                    Wo[k+1][l] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k][l-1] == ".":
                                if Wo[k][l-1] == -1:
                                    Wo[k][l-1] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k][l+1] == ".":
                                if Wo[k][l+1] == -1:
                                    Wo[k][l+1] = Wo[k][l]+1
                                    cnt+=1
            for k in range(1,H+1):
                mx=max(mx,max(Wo[k]))

print(mx)

Submission status: Time Limit Exceeded

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

S = [["#"]*W for i in range(H)]
      
for i in range(H):
    S[i] = list(input())

Sp = [["#"]*(W+2) for i in range(H+2)]
       
for i in range(1,H+1):
    for j in range(1,W+1):
        Sp[i][j] = S[i-1][j-1]

mx = 0

for i in range(1,H+1):
    for j in range(1,W+1):
        if Sp[i][j] == ".":
            Wo = [[-1]*(W+2) for i in range(H+2)]
            Wo[i][j] = 0
            cnt = 1
            while cnt>0:
                cnt = 0
                for k in range(1,H+1):
                    for l in range(1,W+1):
                        if Wo[k][l] != -1:
                            if Sp[k-1][l] == ".":
                                if Wo[k-1][l] == -1:
                                    Wo[k-1][l] = Wo[k][l]+1
                                    cnt+=1
                                elif Wo[k-1][l]>Wo[k][l]+1:
                                    Wo[k-1][l] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k+1][l] == ".":
                                if Wo[k+1][l] == -1:
                                    Wo[k+1][l] = Wo[k][l]+1
                                    cnt+=1
                                elif Wo[k+1][l]>Wo[k][l]+1:
                                    Wo[k+1][l] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k][l-1] == ".":
                                if Wo[k][l-1] == -1:
                                    Wo[k][l-1] = Wo[k][l]+1
                                    cnt+=1
                                elif Wo[k][l-1]>Wo[k][l]+1:
                                    Wo[k][l-1] = Wo[k][l]+1
                                    cnt+=1
                            if Sp[k][l+1] == ".":
                                if Wo[k][l+1] == -1:
                                    Wo[k][l+1] = Wo[k][l]+1
                                    cnt+=1
                                elif Wo[k][l+1]>Wo[k][l]+1:
                                    Wo[k][l+1] = Wo[k][l]+1
                                    cnt+=1
            for k in range(1,H+1):
                mx=max(mx,max(Wo[k]))

print(mx)

Submission status: Time Limit Exceeded

Solution code:
def bfs(sx, sy, gx, gy, maze):
  INF = 10000
  distance = [[INF for i in range(W)] for j in range(H)]
  queue = []
  queue.insert(0, (sx, sy))
  distance[sy][sx] = 0
  while len(queue):
    x, y = queue.pop()
    if x == gx and y == gy:
      break
    for i in range(0, 4):
      nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
      if (0 <= nx and nx < W and 0 <= ny and ny < H and maze[ny][nx] != '#' and distance[ny][nx] == INF):
        queue.insert(0, (nx, ny))
        distance[ny][nx] = distance[y][x] + 1
  return distance[gy][gx]

H,W = (int(x) for x in input().split())
maze = ['']*H
max_distance = 0
maze = [list(input()) for _ in range(H)]

dic = {}
for i in range(H*W):
  dic[i] = [i % W,i//W,0]
  
for i in range(H*W):
  sx,sy = dic[i][0],dic[i][1]
  s = maze[sy][sx]
  if s == '#':
    continue
  for j in range(H*W):
    gx,gy = dic[j][0],dic[j][1]
    g = maze[gy][gx]
    if i == j or g == '#' or dic[j][2] == 1:
        continue
    tmp_s = s
    tmp_g = g
    maze[sy][sx] = 'S'
    maze[gy][gx] = 'G'
    max_distance = max(max_distance,bfs(sx, sy, gx, gy, maze))
    maze[sy][sx] = tmp_s
    maze[gy][gx] = tmp_g
  dic[i][2] = 1
        
print(max_distance)

Submission status: Time Limit Exceeded

Solution code:
def clear_maze(sx, sy, gx, gy, maze):
    INF = 10000
    distance = [[INF for i in range(W)] for j in range(H)]
    def bfs():
        queue = []
        queue.insert(0, (sx, sy))
        distance[sy][sx] = 0
        while len(queue):
            x, y = queue.pop()
            if x == gx and y == gy:
                break
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                if (0 <= nx and nx < W and 0 <= ny and ny < H and maze[ny][nx] != '#' and distance[ny][nx] == INF):
                    queue.insert(0, (nx, ny))
                    distance[ny][nx] = distance[y][x] + 1
        return distance[gy][gx]
    return bfs()

H,W = (int(x) for x in input().split())
maze = ['']*H
max_distance = 0
for i in range(H):
  maze[i] = list(input())
  
dic = {}
for i in range(H*W):
  dic[i] = [i % W,i//W,0]
  
for i in range(H*W):
  sx,sy = dic[i][0],dic[i][1]
  s = maze[sy][sx]
  if s == '#':
    continue
  for j in range(H*W):
    gx,gy = dic[j][0],dic[j][1]
    g = maze[gy][gx]
    if i == j or g == '#' or dic[j][2] == 1:
        continue
    tmp_s = s
    tmp_g = g
    maze[sy][sx] = 'S'
    maze[gy][gx] = 'G'
    max_distance = max(max_distance,clear_maze(sx, sy, gx, gy, maze))
    maze[sy][sx] = tmp_s
    maze[gy][gx] = tmp_g
  dic[i][2] = 1
        
print(max_distance)

Submission status: Time Limit Exceeded

Solution code:
def clear_maze(sx, sy, gx, gy, maze):
    INF = 100000000
    distance = [[INF for i in range(W)] for j in range(H)]
    def bfs():
        queue = []
        queue.insert(0, (sx, sy))
        distance[sy][sx] = 0
        while len(queue):
            x, y = queue.pop()
            if x == gx and y == gy:
                break
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                if (0 <= nx and nx < W and 0 <= ny and ny < H and maze[ny][nx] != '#' and distance[ny][nx] == INF):
                    queue.insert(0, (nx, ny))
                    distance[ny][nx] = distance[y][x] + 1
        return distance[gy][gx]
    return bfs()

H,W = (int(x) for x in input().split())
maze = ['']*H
max_distance = 0
for i in range(H):
  maze[i] = list(input())
  
dic = {}
for i in range(H*W):
  dic[i] = [i % W,i//W,0]
  
for i in range(H*W):
  sx,sy = dic[i][0],dic[i][1]
  s = maze[sy][sx]
  if s == '#':
    continue
  for j in range(H*W):
    gx,gy = dic[j][0],dic[j][1]
    g = maze[gy][gx]
    if i == j or g == '#' or dic[j][2] == 1:
        continue
    tmp_s = s
    tmp_g = g
    maze[sy][sx] = 'S'
    maze[gy][gx] = 'G'
    max_distance = max(max_distance,clear_maze(sx, sy, gx, gy, maze))
    maze[sy][sx] = tmp_s
    maze[gy][gx] = tmp_g
  dic[i][2] = 1
        
print(max_distance)

Submission status: Time Limit Exceeded

Solution code:
def clear_maze(sx, sy, gx, gy, maze):
    INF = 100000000
    distance = [[INF for i in range(W)] for j in range(H)]
    def bfs():
        queue = []
        queue.insert(0, (sx, sy))
        distance[sy][sx] = 0
        while len(queue):
            x, y = queue.pop()
            if x == gx and y == gy:
                break
            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]
                if (0 <= nx and nx < W and 0 <= ny and ny < H and maze[ny][nx] != '#' and distance[ny][nx] == INF):
                    queue.insert(0, (nx, ny))
                    distance[ny][nx] = distance[y][x] + 1
        return distance[gy][gx]
    return bfs()

H,W = (int(x) for x in input().split())
maze = ['']*H
max_distance = 0
for i in range(H):
  maze[i] = list(input())
  
dic = {}
for i in range(H*W):
  dic[i] = [i % W,i//W,0]
  
for i in range(H*W):
  sx,sy = dic[i][0],dic[i][1]
  s = maze[sy][sx]
  if s == '#':
    continue
  for j in range(H*W):
    gx,gy = dic[j][0],dic[j][1]
    g = maze[gy][gx]
    if (sx == gx and sy == gy) or g == '#' or dic[j][2] == 1:
        continue
    tmp_s = s
    tmp_g = g
    maze[sy][sx] = 'S'
    maze[gy][gx] = 'G'
    max_distance = max(max_distance,clear_maze(sx, sy, gx, gy, maze))
    maze[sy][sx] = tmp_s
    maze[gy][gx] = tmp_g
    dic[i][2] = 1
        
print(max_distance)

Submission status: Time Limit Exceeded

Solution code:
def clear_maze(sx, sy, gx, gy, maze):

    INF = 100000000

    distance = [[INF for i in range(W)] for j in range(H)]
    #    distance = [[None]*field_x_length]*field_y_length

    def bfs():
        queue = []

        queue.insert(0, (sx, sy))

        distance[sy][sx] = 0

        while len(queue):
            x, y = queue.pop()

            if x == gx and y == gy:
                break

            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

                if (0 <= nx and nx < W and 0 <= ny and ny < H and maze[ny][nx] != '#' and distance[ny][nx] == INF):
                    queue.insert(0, (nx, ny))
                    distance[ny][nx] = distance[y][x] + 1


        return distance[gy][gx]

    return bfs()

H,W = (int(x) for x in input().split())
maze = ['']*H
max_distance = 0
for i in range(H):
  maze[i] = list(input())
  
dic = {}
for i in range(H*W):
  dic[i] = [i % W,i//W,0]
  
for i in range(H*W):
  sx,sy = dic[i][0],dic[i][1]
  if maze[sy][sx] == '#':
    continue
  for j in range(H*W):
    gx,gy = dic[j][0],dic[j][1]
    if (sx == gx and sy == gy) or maze[gy][gx] == '#' or dic[j][2] == 1:
        continue
    tmp_s = maze[sy][sx]
    tmp_g = maze[gy][gx]
    maze[sy][sx] = 'S'
    maze[gy][gx] = 'G'
    max_distance = max(max_distance,clear_maze(sx, sy, gx, gy, maze))
    maze[sy][sx] = tmp_s
    maze[gy][gx] = tmp_g
    dic[i][2] = 1
        
print(max_distance)

Submission status: Time Limit Exceeded

Solution code:
def clear_maze(sx, sy, gx, gy, maze):

    INF = 100000000

    distance = [[INF for i in range(W)] for j in range(H)]
    #    distance = [[None]*field_x_length]*field_y_length

    def bfs():
        queue = []

        queue.insert(0, (sx, sy))

        distance[sy][sx] = 0

        while len(queue):
            x, y = queue.pop()

            if x == gx and y == gy:
                break

            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

                if (0 <= nx and nx < W and 0 <= ny and ny < H and maze[ny][nx] != '#' and distance[ny][nx] == INF):
                    queue.insert(0, (nx, ny))
                    distance[ny][nx] = distance[y][x] + 1


        return distance[gy][gx]

    return bfs()

H,W = (int(x) for x in input().split())
maze = ['']*H
max_distance = 0
for i in range(H):
  maze[i] = list(input())
for sy in range(H):
  for sx in range(W):
    if maze[sy][sx] == '#':
      continue
    for gy in range(H):
      for gx in range(W):
        if (sx == gx and sy == gy) or maze[gy][gx] == '#':
          continue
        tmp_s = maze[sy][sx]
        tmp_g = maze[gy][gx]
        maze[sy][sx] = 'S'
        maze[gy][gx] = 'G'
        
        max_distance = max(max_distance,clear_maze(sx, sy, gx, gy, maze))
        maze[sy][sx] = tmp_s
        maze[gy][gx] = tmp_g
        
print(max_distance)

Submission status: Time Limit Exceeded

Solution code:
def grid2graph(grid):
    # .が道で#が壁のグリッドをグラフに変換する
    H, W = len(grid), len(grid[0])
    f = {}
    cnt = 0
    for h in range(H):
        for w in range(W):
            if grid[h][w] == '.':
                f[(h, w)] = cnt
                cnt += 1
    G = [[] for i in range(cnt)]
    for h in range(H):
        for w in range(W):
            if grid[h][w] == '#':
                continue
            i = f[(h, w)]
            if 0 <= h-1 and grid[h-1][w] == '.':
                j = f[(h-1, w)]
                G[i].append(j)
            if 0 <= w-1 and grid[h][w-1] == '.':
                j = f[(h, w-1)]
                G[i].append(j)
            if h+1 < H and grid[h+1][w] == '.':
                j = f[(h+1, w)]
                G[i].append(j)
            if w+1 < W and grid[h][w+1] == '.':
                j = f[(h, w+1)]
                G[i].append(j)
    return G


def warshall_floyd(G):
    inf = 10**18
    n = len(G)
    d = [[inf for i in range(n)] for j in range(n)]
    for i in range(n):
        d[i][i] = 0
        for j in G[i]:
            d[i][j] = 1
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])
    return d


H, W = map(int, input().split())
S = []
for h in range(H):
    S.append(list(input()))
G = grid2graph(S)
d = warshall_floyd(G)
n = len(d)
ans = 0
for i in range(n-1):
    for j in range(n):
        ans = max(ans, d[i][j])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H,W=map(int, input().split())
maze=[]
maze.append(list("#"*(W+2)))
for h in range(H):
    maze.append(list("#"+input()+"#"))
maze.append(list("#"*(W+2)))

from collections import deque
import itertools
import copy

def chk_bfd(sy,sx,gy,gx):
    ma=copy.deepcopy(maze)
    ma[sy][sx]=0
    d=[(1,0),(-1,0),(0,1),(0,-1)]
    q=deque([[sy,sx]])
    while q:
        y,x=q.popleft()
        for dy,dx in d:
            if ma[y+dy][x+dx]=='.':
                q.append([y+dy,x+dx])
                ma[y+dy][x+dx]=ma[y][x]+1
    return ma[gy][gx]

s=[]
for h in range(H+2):
    for w in range(W+2):
        if maze[h][w]=='.':
            s.append([h,w])

res=0
for spoint,gpoint in list(itertools.combinations(s,2)):
    sy,sx=spoint[0],spoint[1]
    gy,gx=gpoint[0],gpoint[1]
    tmp=chk_bfd(sy,sx,gy,gx)
    res=max(res,tmp)

print(res)

Submission status: Time Limit Exceeded

Solution code:
import Queue
import copy

def main():
    H, W = map(int, raw_input().split())
    S = []

    for i in range(H):
        S.append(list(raw_input()))


    def bfs(start, S2):
        q = Queue.Queue()
        q.put(start)
        candidates = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        dist = [[0]*W for _ in range(H)]
        while not q.empty():
            i = q.get()
            x = i[0]
            y = i[1]
            S2[x][y] = "#"

            for candi in candidates:
                x_new = x + candi[0]
                y_new = y + candi[1]

                if x_new < H and x_new >= 0:
                    if y_new < W and y_new >=0:
                        if S2[x_new][y_new] == ".":
                            dist[x_new][y_new] = dist[x][y] + 1
                            q.put([x_new, y_new])

        ans = 0
        for i in range(H):
            ans = max(ans, max(dist[i]))

        return ans

    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == ".":
                S2 = copy.deepcopy(S)
                ans = max(ans, bfs([i, j], S2))

    print ans


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import Queue
import copy

def main():
    H, W = map(int, raw_input().split())
    S = []

    for i in range(H):
        S.append(list(raw_input()))


    def bfs(start, S2):
        q = Queue.Queue()
        q.put(start)
        candidates = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        dist = [[0]*W for _ in range(H)]
        while not q.empty():
            i = q.get()
            x = i[0]
            y = i[1]
            S2[x][y] = "#"

            for candi in candidates:
                x_new = x + candi[0]
                y_new = y + candi[1]

                if x_new < H and x_new >= 0:
                    if y_new < W and y_new >=0:
                        if S2[x_new][y_new] == ".":
                            dist[x_new][y_new] = dist[x][y] + 1
                            q.put([x_new, y_new])

        ans = 0
        for i in range(H):
            ans = max(ans, max(dist[i]))

        return ans

    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == ".":
                S2 = copy.deepcopy(S)
                ans = max(ans, bfs([i, j], S2))

    print ans


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import Queue
import copy

def main():
    H, W = map(int, raw_input().split())
    S = []

    for i in range(H):
        S.append(list(raw_input()))


    def bfs(start, goal, S2):
        q = Queue.Queue()
        q.put(start)
        candidates = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        dist = [[0]*W for _ in range(H)]
        while not q.empty():
            i = q.get()
            x = i[0]
            y = i[1]
            S2[x][y] = "#"

            for candi in candidates:
                x_new = x + candi[0]
                y_new = y + candi[1]

                if x_new < H and x_new >= 0:
                    if y_new < W and y_new >=0:
                        if S2[x_new][y_new] == ".":
                            dist[x_new][y_new] = dist[x][y] + 1
                            q.put([x_new, y_new])

        return dist[goal[0]][goal[1]]


    ans = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == ".":
                for k in range(H):
                    for l in range(W):
                        if S[k][l] == ".":
                            S2 = copy.deepcopy(S)
                            ans = max(ans, bfs([i, j], [k, l], S2))

    print ans


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import Queue
import copy

H, W = map(int, raw_input().split())
S = []

for i in range(H):
    S.append(list(raw_input()))


def bfs(start, goal, S2):
    q = Queue.Queue()
    q.put(start)
    candidates = [[0, 1], [1, 0], [0, -1], [-1, 0]]
    dist = [[0]*W for _ in range(H)]
    while not q.empty():
        i = q.get()
        x = i[0]
        y = i[1]
        S2[x][y] = "#"

        for candi in candidates:
            x_new = x + candi[0]
            y_new = y + candi[1]

            if x_new < H and x_new >= 0:
                if y_new < W and y_new >=0:
                    if S2[x_new][y_new] == ".":
                        dist[x_new][y_new] = dist[x][y] + 1
                        q.put([x_new, y_new])

    return dist[goal[0]][goal[1]]


ans = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            for k in range(H):
                for l in range(W):
                    S2 = copy.deepcopy(S)
                    ans = max(ans, bfs([i, j], [k, l], S2))

print ans

Submission status: Time Limit Exceeded

Solution code:
import copy
import sys
from collections import deque

input = sys.stdin.readline
H,W= map(int,input().split())
input_maze = [list(input()) for _ in range(H)]
ans = 0
for i in range(H):
    for j in range(W):
        if input_maze[i][j] ==".":
            queue = deque()
            queue.append([i,j,0])#最初の△
            maze = copy.deepcopy(input_maze)
            while True:
                if len(queue) ==0:
                    tem_ans = point[2]
                    break
                point=queue.popleft()#queueの先頭座標+何回移動したかの取得
                maze[point[0]][point[1]] = point[2] 
                
                #print(numpy.array(maze))    
                if point[0] > 0 and maze[point[0]-1][point[1]]==".":#上
                    queue.append([point[0]-1,point[1],point[2]+1])
                if point[0] < len(maze)-1 and maze[point[0]+1][point[1]]==".":#下
                    queue.append([point[0]+1,point[1],point[2]+1])
                if point[1] > 0 and maze[point[0]][point[1]-1]==".":#左
                    queue.append([point[0],point[1]-1,point[2]+1])
                if point[1] < len(maze[point[0]])-1 and maze[point[0]][point[1]+1]=="." :#右
                    queue.append([point[0],point[1]+1,point[2]+1])
            ans = max(ans,tem_ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue

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

def movable(S,px,py):
    if  0 <= px and px < H and 0 <= py and py < W:
        if S[px][py] == ".":
            return True
        else:
            return False
    else:
        return False

def bfs(S,sx,sy):
    S_dist = [[0 for _ in range(W)] for _ in range(H)]
    q = queue.Queue()
    q.put((sx,sy))
    vec = [(0,1),(0,-1),(1,0),(-1,0)]
    write = set([])
    #deepcopyしたやつを使うと遅いので上書きしたやつを戻して再利用
    while not q.empty():
        p = q.get()
        S[p[0]][p[1]] = "#"
        write.add((p[0],p[1]))
        ret = S_dist[p[0]][p[1]]
        for vx,vy in vec:
            if movable(S,p[0]+vx,p[1]+vy):
                S_dist[p[0]+vx][p[1]+vy] = S_dist[p[0]][p[1]]+1
                q.put((p[0]+vx,p[1]+vy))
    for wx,wy in write:
        S[wx][wy] = "."
    return ret

ans = 0
for i in range(H*W):
    if S[i//W][i%W] == ".":
        ans = max(ans,bfs(S,i//W,i%W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy

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

def movable(S,px,py):
    if  0 <= px and px < H and 0 <= py and py < W:
        if S[px][py] == ".":
            return True
        else:
            return False
    else:
        return False

def bfs(S,sx,sy):
    S_dist = [[0 for _ in range(W)] for _ in range(H)]
    q = queue.Queue()
    q.put((sx,sy))
    vec = [(0,1),(0,-1),(1,0),(-1,0)]
    write = set([])
    #deepcopyしたやつを使うと遅いので上書きしたやつを戻して再利用
    while not q.empty():
        p = q.get()
        S[p[0]][p[1]] = "#"
        write.add((p[0],p[1]))
        ret = S_dist[p[0]][p[1]]
        for vx,vy in vec:
            if movable(S,p[0]+vx,p[1]+vy):
                S_dist[p[0]+vx][p[1]+vy] = S_dist[p[0]][p[1]]+1
                q.put((p[0]+vx,p[1]+vy))
    for wx,wy in write:
        S[wx][wy] = "."
    return ret

ans = 0
for i in range(H*W):
    if S[i//W][i%W] == ".":
        ans = max(ans,bfs(S,i//W,i%W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy

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

def movable(S,px,py):
    if  0 <= px and px < H and 0 <= py and py < W:
        if S[px][py] == ".":
            return True
        else:
            return False
    else:
        return False

def bfs(S,sx,sy):
    S_dist = [[0 for _ in range(W)] for _ in range(H)]
    q = queue.Queue()
    q.put((sx,sy))
    vec = [(0,1),(0,-1),(1,0),(-1,0)]
    while not q.empty():
        p = q.get()
        S[p[0]][p[1]] = "#"
        ret = S_dist[p[0]][p[1]]
        for vx,vy in vec:
            if movable(S,p[0]+vx,p[1]+vy):
                S_dist[p[0]+vx][p[1]+vy] = S_dist[p[0]][p[1]]+1
                q.put((p[0]+vx,p[1]+vy))
    return ret

ans = 0
for i in range(H*W):
    if S[i//W][i%W] == ".":
        S_ = copy.deepcopy(S)
        ans = max(ans,bfs(S_,i//W,i%W))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue
import copy

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

def movable(S,px,py):
    if  0 <= px and px < H and 0 <= py and py < W:
        if S[px][py] == ".":
            return True
        else:
            return False
    else:
        return False

def bfs(S,sx,sy):
    S_dist = [[0 for _ in range(W)] for _ in range(H)]
    q = queue.Queue()
    q.put((sx,sy))
    vec = [(0,1),(0,-1),(1,0),(-1,0)]
    while not q.empty():
        p = q.get()
        S[p[0]][p[1]] = "#"
        for vx,vy in vec:
            if movable(S,p[0]+vx,p[1]+vy):
                S_dist[p[0]+vx][p[1]+vy] = S_dist[p[0]][p[1]]+1
                ret = S_dist[p[0]+vx][p[1]+vy]
                q.put((p[0]+vx,p[1]+vy))
    return ret

ans = 0
for i in range(H*W):
    if S[i//W][i%W] == ".":
        S_ = copy.deepcopy(S)
        ans = max(ans,bfs(S_,i//W,i%W))
print(ans)