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: Wrong Answer

Solution code:
import queue

dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]

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

ans = 0

for i in range(h) :
    for j in range(w) :
        if s[i][j] == '#' :
            continue
        dist = [[-1 for i in range(w)] for j in range(h)]
        q = queue.Queue()
        q.put([j,i])
        dist[i][j] = 0
        cnt = 0
        while not q.empty() :
            xy = q.get()
            for k in range(4) :
                x = xy[0] + dx[k]
                y = xy[1] + dy[k]
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if dist[y][x] != -1 :
                    continue
                q.put([x, y])
                dist[y][x] = dist[xy[1]][xy[0]] + 1
        for i in range(h) :
            for j in range(w) :
                ans = max(ans, dist[i][j])


print(ans)

Submission status: Wrong Answer

Solution code:
import queue

dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]

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

ans = 0

for i in range(h) :
    for j in range(w) :
        if s[i][j] == '#' :
            continue
        dist = [[-1 for i in range(h)] for j in range(w)]
        q = queue.Queue()
        q.put([j,i])
        dist[j][i] = 0
        cnt = 0
        while not q.empty() :
            xy = q.get()
            for k in range(4) :
                x = xy[0] + dx[k]
                y = xy[1] + dy[k]
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if dist[x][y] != -1 :
                    continue
                q.put([x, y])
                dist[x][y] = dist[xy[0]][xy[1]] + 1
        for i in range(h) :
            for j in range(w) :
                ans = max(ans, dist[j][i])


print(ans)

Submission status: Wrong Answer

Solution code:
import queue

dx = [0, 0, -1, -1]
dy = [1, -1, 0, 0]

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

ans = 0

for i in range(h) :
    for j in range(w) :
        if s[i][j] == '#' :
            continue
        dist = [[-1 for i in range(h)] for j in range(w)]
        q = queue.Queue()
        q.put([j,i])
        dist[j][i] = 0
        cnt = 0
        while not q.empty() :
            xy = q.get()
            for k in range(4) :
                x = xy[0] + dx[k]
                y = xy[1] + dy[k]
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if dist[x][y] != -1 :
                    continue
                q.put([x, y])
                dist[x][y] = dist[xy[0]][xy[1]] + 1
        for i in range(h) :
            for j in range(w) :
                ans = max(ans, dist[j][i])


print(ans)

Submission status: Wrong Answer

Solution code:
import queue

dx = [0, 0, -1, -1]
dy = [1, -1, 0, 0]

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

ans = 0

for i in range(h) :
    for j in range(w) :
        if s[i][j] == '#' :
            continue
        dist = [[-1 for i in range(h)] for j in range(w)]
        q = queue.Queue()
        q.put([j,i])
        dist[j][i] = 0
        cnt = 0
        while not q.empty() :
            xy = q.get()
            for k in range(4) :
                x = xy[0] + dx[k]
                y = xy[1] + dy[k]
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if dist[x][y] != -1 :
                    continue
                q.put([x, y])
                dist[x][y] = dist[xy[0]][xy[1]] + 1

for i in range(h) :
    for j in range(w) :
        ans = max(ans, dist[j][i])


print(ans)

Submission status: Wrong Answer

Solution code:
import queue

dx = [0, 0, -1, -1]
dy = [1, -1, 0, 0]

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

ans = -1

for i in range(h) :
    for j in range(w) :
        if s[i][j] == '#' :
            continue
        mapple = [[100 for i in range(h)] for j in range(w)]
        q = queue.Queue()
        q.put([j,i,0])
        mapple[j][i] = 0
        cnt = 0
        while not q.empty() :
            xyc = q.get()
            cnt = max(cnt, xyc[2])
            for k in range(4) :
                x = xyc[0] + dx[k]
                y = xyc[1] + dy[k]
                #print(x, y, xyc[2])
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if mapple[x][y] != 100 :
                    continue
                q.put([x, y, xyc[2]+1])
                mapple[x][y] = 0
                #print(x, y, xyc[2])
        ans = max(ans, cnt)


print(ans)

Submission status: Wrong Answer

Solution code:
import queue

dx = [0, 0, -1, -1]
dy = [1, -1, 0, 0]

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

ans = -1

for i in range(h) :
    for j in range(w) :
        mapple = [[100 for i in range(h)] for j in range(w)]
        q = queue.Queue()
        q.put([j,i,0])
        mapple[j][i] = 0
        cnt = 0
        while not q.empty() :
            xyc = q.get()
            cnt = max(cnt, xyc[2])
            for k in range(4) :
                x = xyc[0] + dx[k]
                y = xyc[1] + dy[k]
                #print(x, y, xyc[2])
                if y < 0 or y >= h or x < 0 or x >= w :
                    continue
                if s[y][x] == '#' :
                    continue
                if mapple[x][y] != 100 :
                    continue
                q.put([x, y, xyc[2]+1])
                mapple[x][y] = 0
                #print(x, y, xyc[2])
        ans = max(ans, cnt)


print(ans)

Submission status: Wrong Answer

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

d=((-1,0),(0,-1),(1,0),(0,1))
ans_l=set()

def search(pos):
    D=[[0]*W for _ in range(H)]
    while len(pos)>0:
        x,y,depth=pos.popleft()
        for i in range(4):
            nx=x+d[i][0]
            ny=y+d[i][1]
            if 0<=nx<H and 0<=ny<W and MAZE[nx][ny]=='.' and D[nx][ny]!=-1:
                pos.append((nx,ny,depth+1))
                D[nx][ny]=-1
    return depth

for i in range(H):
    for j in range(W):
        if MAZE[i][j]=='.':
            p=deque([[i,j,0]])
            ans_l.add(search(p))

print(max(ans_l))

Submission status: Wrong Answer

Solution code:
import sys, math, copy
def input():
    return sys.stdin.readline()[:-1]
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial

sys.setrecursionlimit(10**7)
H, W = map(int, input().split())
maze = [[c for c in input()] for _ in range(H)]

moves = [[-1, 0], [1, 0], [0, -1], [0, 1]]

def chkcell(maze_copy, h, w):
    if 0<=h and h<H and 0<=w and w<W and maze_copy[h][w]=='.':
        return True

def count_steps(q, maze_copy):
    steps = -1
    while len(q):
#        print('q:', q)
#        print('maze:', maze)
        steps += 1
        next_cells = []
        cells = q.pop()
        for cell in cells:
            maze_copy[cell[0]][cell[1]] = '#'
            for move in moves:
                newcell = [i+j for i, j in zip(cell, move)]
                if chkcell(maze_copy=maze_copy, h=newcell[0], w=newcell[1]):
                    next_cells.append(newcell)
        if next_cells:
            q.append(next_cells)

#    print('max_step:', steps)
    return steps

res = 0
for i in range(H):
    for j in range(W):
#        print('i, j', i, j)
        q = deque()
        q.append([[i, j]])
        maze_copy = copy.deepcopy(maze)
        val = count_steps(q, maze_copy)
        if res < val: res = val

print(res)

Submission status: Wrong Answer

Solution code:
import sys, math, copy
def input():
    return sys.stdin.readline()[:-1]
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial

sys.setrecursionlimit(10**7)
H, W = map(int, input().split())
maze = [[c for c in input()] for _ in range(H)]

moves = [[-1, 0], [1, 0], [0, -1], [0, 1]]

def chkcell(maze_copy, h, w):
    if 0<=h and h<H and 0<=w and w<W and maze_copy[h][w]=='.':
        return True

def count_steps(q, maze_copy):
    steps = -1
    while len(q):
#        print('q:', q)
#        print('maze:', maze)
        steps += 1
        next_cells = []
        cells = q.pop()
        for cell in cells:
            maze_copy[cell[0]][cell[1]] = '#'
            for move in moves:
                newcell = [i+j for i, j in zip(cell, move)]
                if chkcell(maze_copy=maze_copy, h=newcell[0], w=newcell[1]):
                    next_cells.append(newcell)
        if next_cells:
            q.append(next_cells)

#    print('max_step:', steps)
    return steps

res = 0
for i in range(H):
    for j in range(W):
#        print('i, j', i, j)
        q = deque()
        q.append([[i, j]])
        maze_copy = copy.deepcopy(maze)
        val = count_steps(q, maze_copy)
        if res < val: res = val

print(res)

Submission status: Wrong Answer

Solution code:
import sys
from functools import reduce
import copy
import math
from pprint import pprint
import collections
import bisect
import itertools
import heapq


sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def int_inputs(num_of_input):
    ins = [int(input()) for i in range(num_of_input)]
    return ins


def solve(H, W, inputs):
    INF = -1 * (10 ** 9)
    d_map = inputs
    matrix = {}
    V = []

    for sh in range(H):
        for sw in range(W):
            m = {}
            V.append((sh, sw))
            for eh in range(H):
                for ew in range(W):
                    m[(eh, ew)] = INF
            matrix[(sh, sw)] = m

    def can_pass(y, x):
        if y < 0 or x < 0 or y >= H or x >= W:
            return False
        if d_map[y][x] == '#':
            return False
        return True

    for h in range(H):
        for w in range(W):
            if not can_pass(h, w):
                continue
            if can_pass(h-1, w):
                matrix[(h-1, w)][(h, w)] = 1
                matrix[(h, w)][(h-1, w)] = 1
            if can_pass(h+1, w):
                matrix[(h+1, w)][(h, w)] = 1
                matrix[(h, w)][(h+1, w)] = 1
            if can_pass(h, w-1):
                matrix[(h, w-1)][(h, w)] = 1
                matrix[(h, w)][(h, w-1)] = 1
            if can_pass(h, w+1):
                matrix[(h, w+1)][(h, w)] = 1
                matrix[(h, w)][(h, w+1)] = 1
    # pprint(matrix)

    for mid in V:
        for start in V:
            for end in V:
                candidate = []
                if matrix[start][end] != INF:
                    candidate.append(matrix[start][end])
                if matrix[start][mid] != INF and matrix[mid][end] != INF:
                    candidate.append(matrix[start][mid] + matrix[mid][end])
                if len(candidate) > 0:
                    matrix[start][end] = min(candidate)

    max_dis = -1
    for v in V:
        max_dis = max(max_dis, max(matrix[v].values()))
    return max_dis


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    [H, W] = string_to_int(input())
    ret = solve(H, W, inputs(H))
    print(ret)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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

maze = []
for _ in range(H):
  maze.append([i for i in input()])
  
# 無向グラフを作ってワーシャルフロイド法で解く

inf = float("inf")
d = defaultdict(lambda: inf)

directions = [(1, 0), (0, 1)]
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      d[((i, j), (i, j))] = 0
      for di, dj in directions:
        if i + di < H and j + dj < W\
        and maze[i + di][j + dj] == '.':
          d[((i, j), (i + di, j + dj))] = 1
          d[((i + di, j + dj), (i, j))] = 1

for i1 in range(H):
  for j1 in range(W):
    if maze[i1][j1] == '.':
      for i2 in range(H):
        for j2 in range(W):
          if maze[i2][j2] == '.':
            for i3 in range(H):
              for j3 in range(W):
                if maze[i3][j3] == '.':
                  d[((i1, j1), (i3, j3))]\
                  = min(
                    d[((i1, j1), (i3, j3))],
                    d[((i1, j1), (i2, j2))] + d[((i2, j2), (i3, j3))]
                  )

# 全ての連結成分の最大距離を求めて出力

ret = 0
for value in d.values():
  if value != inf:
    ret = max(ret, value)
    
print(ret)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

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

maze = []
for _ in range(H):
  maze.append([i for i in input()])
  
# 無向グラフを作ってワーシャルフロイド法で解く

inf = float("inf")
d = defaultdict(lambda: inf)
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      d[((i, j), (i, j))] = 0

directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      for di, dj in directions:
        if i + di >= 0 and i + di < H\
        and j + dj >= 0 and j + dj < W\
        and maze[i + di][j + dj] == '.':
          d[((i, j), (i + di, j + dj))] = 1
          d[((i + di, j + dj), (i, j))] = 1

            
# 連結成分ごとにワーシャルフロイド法を実行し、最大距離を計算する
for i1 in range(H):
  for j1 in range(W):
    for i2 in range(H):
      for j2 in range(W):
        for i3 in range(H):
          for j3 in range(W):
            if maze[i1][j1] == '.'\
            and maze[i2][j2] == '.'\
            and maze[i3][j3] == '.':
              d[((i1, j1), (i3, j3))]\
              = min(
                d[((i1, j1), (i3, j3))],
                d[((i1, j1), (i2, j2))] + d[((i2, j2), (i3, j3))]
              )

# 全ての連結成分の最大距離を求めて出力

ret = 0
for value in d.values():
  if value != inf:
    ret = max(ret, value)
    
print(ret)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from copy import copy
from queue import Queue

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

maze = []
for _ in range(H):
  maze.append([i for i in input()])
  
# 無向グラフを作ってワーシャルフロイド法で解く

inf = float("inf")
d = defaultdict(lambda: inf)
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      d[((i, j), (i, j))] = 0

directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(H):
  for j in range(W):
    if maze[i][j] == '.':
      for di, dj in directions:
        if i + di >= 0 and i + di < H\
        and j + dj >= 0 and j + dj < W\
        and maze[i + di][j + dj] == '.':
          d[((i, j), (i + di, j + dj))] = 1
          d[((i + di, j + dj), (i, j))] = 1

            
# 連結成分ごとにワーシャルフロイド法を実行し、最大距離を計算する
for i1 in range(H):
  for j1 in range(W):
    for i2 in range(H):
      for j2 in range(W):
        for i3 in range(H):
          for j3 in range(W):
            if maze[i1][j1] == '.'\
            and maze[i2][j2] == '.'\
            and maze[i3][j3] == '.':
              d[((i1, j1), (i3, j3))]\
              = min(
                d[((i1, j1), (i3, j3))],
                d[((i1, j1), (i2, j2))] + d[((i2, j2), (i3, j3))]
              )

# 全ての連結成分の最大距離を求めて出力

ret = 0
for i1 in range(H):
  for j1 in range(W):
    for i2 in range(H):
      for j2 in range(W):
        if d[((i1, j1), (i2, j2))] != inf\
        and d[((i1, j1), (i2, j2))] > ret:
          ret = d[((i1, j1), (i2, j2))]
          
print(ret)

Submission status: Wrong Answer

Solution code:

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

array = []
for _ in range(H):
  array.append(input())
  
max_path = 0
import queue
from collections import deque

for h in range(H):
  for w in range(W):    
    if array[h][w] == ".":
#      que = queue.Queue()
      que = deque()
      checked = [[-1 if array[h][w] =="." else -2 for w in range(W)] for h in range(H)]
#      que.put((w, h, 0))
      que.append((w, h, 0))
#      while not que.empty():
#        x, y, l = que.get()
      while len(que) > 0:
        x, y, l = que.pop()
        checked[y][x] = l
        max_path = max(max_path, l)
        if (x > 0) and (checked[y][x-1] == -1):
#          que.put((x-1, y, l+1))
           que.append((x-1, y, l+1))
        if (y > 0) and (checked[y-1][x] == -1):
          que.append((x, y - 1, l+1))
        if (x < W - 1) and (checked[y][x+1] == -1):
          que.append((x + 1, y, l+1))
        if (y < H - 1) and (checked[y+1][x] == -1):
          que.append((x, y + 1, l+1))
        
          
        
  
print(max_path)

Submission status: Wrong Answer

Solution code:
HW = [int(i) for i in input().split()]

""" input section """
S = []
for i in range(0, HW[0]):
  S.append(list(input()))

""" test section """
root_max = 0

for i in range(0, HW[0]):
  for j in range(0, HW[1]):
    if S[i][j] == '#':
      continue
    
    """ 隣接4マスのチェック """
    """ 4マスの内 1つだけ道 の場合のみ """
    """ 最大移動回数迷路の始点になりうる """
    cnt = 0
    if i-1 >= 0 :
      if S[i-1][j] == '.' :
        cnt += 1
    if i+1 < HW[0] :
      if S[i+1][j] == '.' :
        cnt += 1
    if j-1 >= 0 :
      if S[i][j-1] == '.' :
        cnt += 1
    if j+1 < HW[1] :
      if S[i][j+1] == '.' :
        cnt += 1
    if cnt != 1 :
      continue
      
    """ 経路を調べていく """

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split()) #高さ、幅取得
maze=[]
for i in range(H):
  S=list(str(input()))
  maze.append(S)
# sx,sy=スタートの座標 gx,gy=ゴールの座標
def clear_maze(sx, sy, gx, gy, maze):

    INF = 500

    field_x_length = len(maze[0]) #幅
    field_y_length = len(maze) #高さ
    distance = [[INF for i in range(field_x_length)] for j in range(field_y_length)]
    #    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 < field_x_length and 0 <= ny and ny < field_y_length 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()
dist=0
INF = 500
H= len(maze)
W= len(maze[0])
for i in range(W):
  for j in range(H):
    for k in range(W):
      for l in range(H):
        dist0=clear_maze(i, j, k, l, maze)
        if dist0>dist and dist0 != INF:
          dist=dist0
print(dist)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split()) #高さ、幅取得
maze=[]
for i in range(H):
  S=list(str(input()))
  maze.append(S)
# sx,sy=スタートの座標 gx,gy=ゴールの座標
def clear_maze(sx, sy, gx, gy, maze):

    INF = 401

    field_x_length = len(maze[0]) #幅
    field_y_length = len(maze) #高さ
    distance = [[INF for i in range(field_x_length)] for j in range(field_y_length)]
    #    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 < field_x_length and 0 <= ny and ny < field_y_length 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()
dist=0
INF = 401
H= len(maze)
W= len(maze[0])
for i in range(W-1):
  for j in range(H):
    for k in range(1,W):
      for l in range(H):
        dist0=clear_maze(i, j, k, l, maze)
        if dist0>dist and dist0 != INF:
          dist=dist0
print(dist)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split()) #高さ、幅取得
maze=[]
for i in range(H):
  S=list(str(input()))
  maze.append(S)
# sx,sy=スタートの座標 gx,gy=ゴールの座標
def clear_maze(sx, sy, gx, gy, maze):

    INF = 100000000

    field_x_length = len(maze[0]) #幅
    field_y_length = len(maze) #高さ
    distance = [[INF for i in range(field_x_length)] for j in range(field_y_length)]
    #    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 < field_x_length and 0 <= ny and ny < field_y_length 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()
dist=0
INF = 100000000
H= len(maze)
W= len(maze[0])
for i in range(W):
  for j in range(H):
    for k in range(W):
      for l in range(H):
        dist0=clear_maze(i, j, k, l, maze)
        if dist0>dist and dist0 != INF:
          dist=dist0
print(dist)

Submission status: Wrong Answer

Solution code:
from queue import Queue
INF = 999999


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

m = 0
for si in range(H):
    for sj in range(W):
        if S[si][sj] == '#':
            continue
        
        q = Queue()
        q.put((si, sj, 0))
        done = [None] * H
        for i in range(H):
            done[i] = [False] * W

        unit = ((1, 0), (-1, 0), (0, 1), (0, -1))
        while not q.empty():
            i, j, w = q.get()

            for u in unit:
                nexti = i + u[0]
                nextj = j + u[1]
                if nexti >= 0 and nexti < H and nextj >= 0 and nextj < W and S[nexti][nextj] == '.' and (not done[nexti][nextj]):
                    q.put((nexti, nextj, w+1))
                    m = max(m, w + 1)
                    done[nexti][nextj] = True
print(m)

Submission status: Wrong Answer

Solution code:
from itertools import count, combinations, product

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

H += 2
W += 2

visited = [2**31]*(W*H)

for i in range(1,H-1):
    S = input()
    for j,v in zip(range(1,W-1),S):
        if v == '.':
            visited[i*W + j] = 0

D = (W,-W,1,-1)
cnt = 0

def furthest(i):
    global cnt
    cnt += 1
    q = [i]
    visited[i] = cnt

    u = None
    for dist in count():
        if not q:
            break
        u = q[0]
        nq = []
        for j in q:
            for d in D:
                if visited[j+d] < cnt:
                    visited[j+d] = cnt
                    nq.append(j+d)
        q = nq
    return dist, u

res = 1
for i in range(W*H):
    if visited[i] != 0:
        continue
    _,u = furthest(i)
    d,_ = furthest(u)
    res = max(res, d)

print(res-1)

Submission status: Wrong Answer

Solution code:
from itertools import count, combinations, product

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

H += 2
W += 2

visited = [2**31]*(W*H)

for i in range(1,H-1):
    S = input()
    for j,v in zip(range(1,W-1),S):
        if v == '.':
            visited[i*W + j] = 0

D = (W,-W,1,-1)

def furthest(visited, i):
    q = [i]
    visited[i] = i

    u = None
    for dist in count():
        if not q:
            break
        u = q[0]
        nq = []
        for j in q:
            for d in D:
                if visited[j+d] < i:
                    visited[j+d] = i
                    nq.append(j+d)
        q = nq
    return dist, u

res = 1
for i in range(W*H):
    if visited[i] != 0:
        continue
    _,u = furthest(visited, i)
    d,_ = furthest(visited, u)
    res = max(res, d)

print(res-1)

Submission status: Wrong Answer

Solution code:
from itertools import count, combinations, product

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

H += 2
W += 2

visited = [2**31]*(W*H)

for i in range(1,H-1):
    S = input()
    for j,v in zip(range(1,W-1),S):
        if v == '.':
            visited[i*W + j] = 0

D = (W,-W,1,-1)

def furthest(visited, i):
    q = [i]
    visited[i] = i

    u = None
    for dist in count():
        if not q:
            break
        u = q[0]
        nq = []
        for j in q:
            for d in D:
                if visited[j+d] < i:
                    visited[j+d] = i
                    nq.append(j+d)
        q = nq
    return dist, u

res = 0
for i in range(W*H):
    if visited[i] != 0:
        continue
    _,u = furthest(visited, i)
    d,_ = furthest(visited, u)
    res = max(res, d)

print(res-1)

Submission status: Wrong Answer

Solution code:
from collections import deque
import numpy as np

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


def make_wall(W, Map):
    for map_row in Map:
        map_row.append("#")
        map_row.insert(0, "#")

    wall = ["#"]*(W+2)
    Map.append(wall)
    Map.insert(0, wall)
    return Map


start_list = deque()
search_list = deque()
Map = make_wall(W, Map)
H += 2
W += 2

start_h = 0
for h in range(H):
    start_w = 0
    for w in range(W):
        if Map[h][w] == ".":
            start_list.append([start_h, start_w])
        start_w += 1
    start_h += 1



max_cost = 0
while start_list != deque():
    search_list.append(start_list.popleft())
    cost_map = [[0] * W for i in range(H)]
    search_map = [[0] * W for i in range(H)]
    while search_list != deque():
        tmp = search_list.pop()
        x = tmp[0]
        y = tmp[1]
        search_map[x][y] = 1
        if Map[x][y+1] == "." and search_map[x][y+1] == 0:
            search_list.append([x, y+1])
            cost_map[x][y+1] = cost_map[x][y]+1
        if Map[x][y-1] == "." and search_map[x][y-1] == 0:
            search_list.append([x, y-1])
            cost_map[x][y-1] = cost_map[x][y]+1
        if Map[x+1][y] == "." and search_map[x+1][y] == 0:
            search_list.append([x+1, y])
            cost_map[x+1][y] = cost_map[x][y]+1
        if Map[x-1][y] == "." and search_map[x-1][y] == 0:
            search_list.append([x-1, y])
            cost_map[x-1][y] = cost_map[x][y]+1
    cost_map = np.array(cost_map)
    if max_cost < np.amax(cost_map):
        max_cost = np.amax(cost_map)


print(max_cost)

Submission status: Wrong Answer

Solution code:
from queue import Queue

def solve(h, w, SS):
    m = {
        (x, y): S[x] == '.'
        for y, S in enumerate(SS)
        for x in range(len(S))
    }
    conditions = {
        (-1, 0): lambda x, y: x > 0,
        (1, 0): lambda x, y: x < w - 1,
        (0, -1): lambda x, y: y > 0,
        (0, 1): lambda x, y: y < h - 1
    }

    def calc_max_len(x0, y0):
        q = Queue(maxsize = h * w)
        q.put((x0, y0))
        d = {(x0, y0): 0}
        max_len = 0
        while not q.empty():
            x, y = q.get(block=False)
            for dx, dy in conditions.keys():
                key = (x + dx, y + dy)
                if conditions[(dx, dy)](x, y) and m[key] and key not in d:
                    q.put(key)
                    d[key] = d[(x, y)] + 1
            if max_len < d[(x, y)]:
                max_len = d[(x, y)]
        return max_len
    return max(calc_max_len(x, y) for x, y in m)

_h, _w = map(int, input().split())
_SS = [input() for _ in range(_h)]
print(solve(_h, _w, _SS))

Submission status: Wrong Answer

Solution code:
import numpy as np
def min_rounte(s, sta, path):
    move = [[0,1],[0,-1],[1,0],[-1,0]]
    for i in move:
        ax = [sta[0]+i[0], sta[1]+i[1]]
        if s[ax[0]][ax[1]] == -1:
            continue
        if s[ax[0]][ax[1]] > path:
            s[ax[0]][ax[1]] = path
    return s
 
def bfs(s, sta):
    s_ = np.array(s)
    s_[sta[0]][sta[1]] = 0
    tmp = sta
    for i in range(400):
        ind = np.where(s_==i)
        for j in range(len(ind[0])):
            s_ = min_rounte(s_, [ind[0][j], ind[1][j]], i+1)
        if len(ind[0]) == 0:
            break
        tmp = [ind[0][0], ind[1][0]]
    return i-1, tmp
        

h, w = map(int, input().split())
#s_ = [[0 if i=="." else -1 for i in input()] for j in range(h)]
s = [[-1 for i in range(w+2)] for j in range(h+2)]
for i in range(h):
    a = input()
    for j in range(w):
        if a[j] == ".":
            s[i+1][j+1] = 512
        else:
            s[i+1][j+1] = -1

for i in range(1, h+1):
    for j in range(1, w+1):
        if s[i][j] == -1:
            continue
        temp, ax = bfs(s, [i,j])
        break
ans, t = bfs(s, ax)

print(ans)

Submission status: Wrong Answer

Solution code:

def get_next_str():
    return input().rstrip("\n")
def get_next_ints(delim=" "):
    return tuple([int(float(x)) for x in input().split(delim)])
def solve(maze, start_r, start_c):
    
    distances = {}
    offsets = [(-1,0),(1,0),(0,-1),(0,1)]
    
    distances[start_r, start_c] = 0
    candidates = [(start_r, start_c)]
    
    while candidates:
        r, c= candidates.pop(0)
        
        for offset_r, offset_c in offsets:
            move_r, move_c = r + offset_r, c + offset_c
            if not (move_r, move_c) in distances and maze[move_r, move_c] == ".":
                distances[move_r, move_c] = distances[r, c] + 1
                candidates.append((move_r, move_c))
    
    return max(distances.values())
    

def main():
    h, w = get_next_ints()
    from collections import defaultdict
    maze = defaultdict(str)
    for r in range(h):
        line = get_next_str()
        for c in range(w):
            maze[r,c] = line[c]
    
    results = []
    for r in range(h):
        for c in range(w):
            result = solve(maze, r, c)
            results.append(result)
    
    print(max(results))
    
if __name__ == '__main__':
    main()