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:
from collections import deque
import sys
sys.setrecursionlimit(10**8)
INF = float('inf')



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

def bfs(sy, sx):
  dist = [[0 for x in range(w)] for y in range(h)]
  dy = [0, 1, 0, -1]
  dx = [1, 0, -1, 0]
  Q = deque()
  Q.append((sy, sx))
  while Q:
    q = Q.popleft()
    y = q[0]
    x = q[1]
    d = dist[y][x]
    for i in range(4):
      ny = y + dy[i]
      nx = x + dx[i]
      if ny < 0 or h <= ny or nx < 0 or w <= nx:
        continue
      #迷路における道が'.'、壁が'#'で表されている場合
      if maze[ny][nx] == '#':
        continue
      nd = d + 1
      if dist[ny][nx] != 0 and nd >= dist[ny][nx]:
        continue
      dist[ny][nx] = nd
      Q.append((ny, nx))
  return max(max(x) for x in dist)

ans = 0
for y in range(h):
  for x in range(w):
    if maze[y][x] == '.':
      ans = max(ans, bfs(y,x))
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy
from collections import deque
from itertools import product
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val
        
h, w = map(int, inputs[0].split())
grid_origin = Grid(inputs[1:], function=lambda x: int(x == '.'))

def bfs(root):
    d = 0
    x, y = root
    grid[y, x] = 0
    queue = deque([root])
    while queue:
        x, y = queue.popleft()
        d += 1
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                queue.append((x+dx, y+dy))
                grid[y+dy, x+dx] = 0
    return d-1
    
ans = 0
for i, j in product(range(h), range(w)):
    if grid_origin[i, j]:
        grid = deepcopy(grid_origin)
        ans = max(ans, bfs((j, i)))
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy
from collections import deque
from itertools import product
import numpy as np
inputs = open(0).readlines()
class Grid():
    def __init__(self, grid, w=0, h=0, function=lambda x: x):
        self.w = w = w if w else len(grid[0])
        self.h = h = h if h else len(grid)
        dtype = type(function(grid[0][0]))
        self.grid = np.empty((h, w), dtype=dtype)
        for i, row in zip(range(h), grid):
            for j, val in zip(range(w), row):
                self.grid[i][j] = function(val)
    
    def is_valid_x(self, x):
        return 0 <= x < self.w
    def is_valid_y(self, y):
        return 0 <= y < self.h
    def is_valid_xy(self, x, y):
        return self.is_valid_x(x) and self.is_valid_y(y) 
    
    def __iter__(self):
        return iter(self.grid)
    def __repr__(self):
        return '\n'.join([' '.join(map(str, row)) for row in self.grid])
    def __getitem__(self, x):
        return self.grid[x]
    def __setitem__(self, x, val):
        self.grid[x] = val
        
h, w = map(int, inputs[0].split())
grid_origin = Grid(inputs[1:], function=lambda x: int(x == '.'))

def bfs(root):
    d = 0
    queue = deque([root])
    while queue:
        x, y = queue.popleft()
        d += 1
        grid[y, x] = 0
        for dx, dy in zip([1, 0, -1, 0], [0, 1, 0, -1]):
            if grid.is_valid_xy(x+dx, y+dy) and grid[y+dy, x+dx]:
                queue.append((x+dx, y+dy))
                grid[y+dy, x+dx] = 0
    return d-1
    
ans = 0
for i, j in product(range(h), range(w)):
    if grid_origin[i, j]:
        grid = deepcopy(grid_origin)
        ans = max(ans, bfs((j, i)))
print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
h,w = list(map(int,input().split()))
inf=float("inf")
s = [[-1]*(w+2)] + [[-1] + [inf if i=="." else -1 for i in input()] + [-1] for _ in range(h)] + [[-1]*(w+2)]

from copy import deepcopy
from collections import deque

ret = 0
for i in range(1,h+1):
    for j in range(1,w+1):
        temp_s = deepcopy(s)
        temp_s[i][j]=-1
        stack_deque = deque([(i,j,0)])
        max_v=0
        while len(stack_deque)>0:
            hi,wj,v = stack_deque.popleft()
            v+=1
            if temp_s[hi][wj-1]!=-1:
                temp_s[hi][wj-1]=-1
                stack_deque.append([hi,wj-1,v])
                max_v=max(max_v,v)
            if temp_s[hi][wj+1]!=-1:
                temp_s[hi][wj+1]=-1
                stack_deque.append([hi,wj+1,v])
                max_v=max(max_v,v)
            if temp_s[hi-1][wj]!=-1:
                temp_s[hi-1][wj]=-1
                stack_deque.append([hi-1,wj,v])
                max_v=max(max_v,v)
            if temp_s[hi+1][wj]!=-1:
                temp_s[hi+1][wj]=-1
                stack_deque.append([hi+1,wj,v])
                max_v=max(max_v,v)
        ret=max(ret,max_v)
print(ret)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

def bfs(sy, sx):
    dist = [[-INF] * W for _ in range(H)]
    dist[sy][sx] = 0
    que = deque([(sy, sx)])
    popleft = que.popleft; append = que.append
    while que:
        y, x = popleft()
        cur = dist[y][x]
        for dy, dx in zip([0, 1, 0, -1], [1, 0, -1, 0]):            
            ny = y + dy
            nx = x + dx
            if 0 <= ny < H and 0 <= nx < W and \
                    grid[ny][nx] != '#' and dist[ny][nx] == -INF:
                dist[ny][nx] = cur + 1
                append((ny, nx))
    ret = max(max(x for x in di)for di in dist)
    return ret

INF = 10 ** 3
H, W = lr()
grid = [sr() for _ in range(H)]
answer = max(max(bfs(i, j) for j in range(W)) for i in range(H))
print(answer)
# 22

Submission status: Wrong Answer

Solution code:
h, w = map(int, input().split())
MAZE = ['#'*(w+2)]
for _ in range(h):
    MAZE.append("#"+input()+"#")
else:
    MAZE.append('#'*(w+2))
INF = 10**3
dp = [[INF]*(w+2) for _ in range(h+2)]
directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]

def bfs(pos):
    x, y = pos
    can_go = []
    for i, j in directions:
        if MAZE[x+i][y+j] == '.':
            if dp[x+i][y+j] != INF:
                continue
            dp[x+i][y+j] = min(dp[x+i+v][y+j+w]+1 for v, w in directions)
            can_go.append((x+i, y+j))
    for x, y in can_go:
        bfs((x, y))

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

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

H, W = lr()
grid = [sr() for _ in range(H)]

def bfs(sy, sx):
    d = [[float('inf')] * W for _ in range(H)]
    dy = [0, 1, 0, -1]
    dx = [1, 0, -1, 0]
    que = deque()
    que.append((sy, sx))
    d[sy][sx] = 0
    while que:
        p = que.popleft()
        for i in range(4):
            ny = p[0] + dy[i]
            nx = p[1] + dx[i]                
            if 0 <= ny < H and 0 <= nx < W and \
                    grid[ny][nx] != '#' and d[ny][nx] == float('inf'):
                d[ny][nx] = d[p[0]][p[1]] + 1
                que.append((ny, nx))
    max = 0
    for row in d:
        for r in row:
            if r != float('inf') and r > max:
                max = r
    return max

answer = 0    
for i in range(H):
    for j in range(W):
        result = bfs(i, j)
        if result > answer:
            answer = result

print(answer)
# 49

Submission status: Wrong Answer

Solution code:
def gridbfs(grid,sy,sx):
    INF = 10**18

    gridy = len(grid)
    gridx = len(grid[0])

    dist = [[INF]*gridx for _ in range(gridy)]
    dist[sy][sx] = 0
    q = [(sy,sx)]
    d = 1

    while q:
        qq = []
        for y,x in q:
            for dy,dx in [(-1,0),(1,0),(0,-1),(0,1)]:
                yy,xx = y+dy, x+dx
                if not (0 <= yy < gridy and 0 <= xx < gridx):
                    continue
                if grid[yy][xx] == '#':
                    continue
                if dist[yy][xx] != INF:
                    continue
                dist[yy][xx] = d
                qq.append((yy,xx))
        q = qq
        d += 1

    return dist

h,w = map(int,input().split())
s = [input() for i in range(h)]
c = 0
for i in range(h):
    for j in range(w):
        d_list = gridbfs(s,i,j)
        for k in range(h):
            for l in range(w):
                if d_list[k][l] != 10**18:
                    c = max(c,d_list[k][l])
print(c)

Submission status: Wrong Answer

Solution code:
import copy
import sys
sys.setrecursionlimit(10**6)

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

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

walker=[]
for row in range(H):
    walker.append([None]*W)
waiting=[]
def func(xy, walker):
    x, y = xy
    for i in range(4):
        if 0 <= x+dx[i] < W and 0 <= y+dy[i] <H:
            if walker[y+dy[i]][x+dx[i]] == None and S[y+dy[i]][x+dx[i]] == '.':
                walker[y+dy[i]][x+dx[i]] = walker[y][x]+1
                waiting.append((x+dx[i], y+dy[i]))
    if waiting:
        func(waiting.pop(0) ,walker)
    else:
        return None


candicate = []
for sx in range(W):
    for sy in range(H):
        if S[sy][sx] == '.':
            temp_walker=copy.deepcopy(walker)
            temp_walker[sy][sx]=0
            func((sx,sy), temp_walker)
            far=0

            for gx in range(W):
                for gy in range(H):
                    if S[gy][gx]=='.':
                        if far < temp_walker[gy][gx]:
                            far = temp_walker[gy][gx]

            print(sx, sy, temp_walker, far)
            candicate.append(far)
print(max(candicate))

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
meiro = []
for i in range(h):
    meiro.append(list(input()))
#進む方向のリスト
d = [(1,0) , (-1,0) , (0,1),(0,-1)]
ans = 0

def search(n,m):
    ans = -1  #最後に次の層に行けなくても+1するから-1から
    
    X = [[0 for i in range(w)] for j in range(h)]  #探索判定用配列
    X[n][m] = 1#初期位置を到達済みにする
    que = [(n,m)]#初期位置をキューに追加
    while que:#キューがからでないなら
        new_que = []#深さ+1で到達済みの点を次のqueにする
        for x,y in que:
            for dx,dy in d:
                if 0<= x+dx < h and 0<= y+dy < w and meiro[x+dx][y+dy] == '.' and X[x+dx][y+dy] == 0:
                    X[x+dx][y+dy] = 1
                    new_que.append((x+dx , y+dy))
        ans += 1
        que = new_que
    return ans

Submission status: Wrong Answer

Solution code:
from collections import deque
h, w = map(int, input().split())
s = []
for _ in range(h):
    s.append(list(input()))

def cal_dist(sx, sy):
    # スタートからの距離を格納
    x_max, y_max = h, w
    dist = [[float('inf')] * w for _ in range(h)]

    # キューを作成
    que = deque([])
    que.append((sx, sy))
    dist[sx][sy] = 0

    # ゴールにたどり着くまで探索
    dist_max = 0
    while len(que) > 0:
        x, y = que.popleft()
        # if x == gx and y == gy:
        #     break

        dx, dy = [1, 0, -1, 0], [0, 1, 0, -1]
        for i in range(0, 4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < x_max and 0 <= ny < y_max and \
               s[nx][ny] != '#' and dist[nx][ny] == float('inf'):
                que.append((nx, ny))
                dist[nx][ny] = dist[x][y] + 1
                dist_max = max(dist[nx][ny], dist_max)

    return dist_max

dist_max = 0
for i in range(h):
    for j in range(w):
        dist = cal_dist(i, j)
        if dist == float('inf'):
            continue
        dist_max = max(dist, dist_max)
print(dist_max)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
s=[]
for _ in range(H):
    s.append(list(input()))
count=[[0]*W for _  in range(H)]
def dfs(y,x):
    q=[(y,x)]
    visited=[[-1]*W for _ in range(H)]
    visited[y][x]=0
    while q:
        cy,cx=q.pop()
        for dy,dx in ((1,0),(-1,0),(0,-1),(0,1)):
            nx=cx+dx
            ny=cy+dy
            if 0<=ny<H and 0<=nx<W and s[ny][nx]=='.' and visited[ny][nx]==-1:
                visited[ny][nx]=visited[cy][cx]+1
                q.append((ny,nx))
    return max(max(i) for i in visited)
ans=0
for h in range(H):
    for w in range(W):
        if s[h][w]=='.':
            ans=max(dfs(h,w),ans)
print(ans)

Submission status: Wrong Answer

Solution code:
H,W=map(int,input().split())
s=[]
for _ in range(H):
    s.append(list(input()))
count=[[0]*W for _  in range(H)]
def dfs(y,x):
    q=[(y,x)]
    visited=[[-1]*W]*H
    visited[y][x]=0
    while q:
        cy,cx=q.pop()
        for dy,dx in ((1,0),(-1,0),(0,-1),(0,1)):
            nx=cx+dx
            ny=cy+dy
            if 0<=ny<H and 0<=nx<W and s[ny][nx]=='.' and visited[ny][nx]==-1:
                visited[ny][nx]=visited[cy][cx]+1
                q.append((ny,nx))
    return max(max(i) for i in visited)
ans=0
for h in range(H):
    for w in range(W):
        if s[h][w]=='.':
            ans=max(dfs(h,w),ans)
print(ans)

Submission status: Wrong Answer

Solution code:
H,W = map(int, input().split())
S = [list('#'+input()+"#") for i in range(H)]
S.insert(0, list('#'*(W+2)))
S.append(list('#'*(W+2)))
vector = [(1,0), (-1,0), (0,1), (0,-1)]
ans = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if S[i][j]=='.':
            Q = [(i,j)]
            distance = [[0]*(W+2) for i in range(H+2)]
            distance[i][j] = 1
            while Q!=[]:
                x,y = Q.pop(0)
                for k in vector:
                    x1,y1 = x+k[0],y+k[1]
                    if S[x1][y1]=='.' and distance[x1][y1]==0:
                        Q.append((x1,y1))
                        distance[x1][y1] = distance[x][y] + 1
            for i in range(H+2):
                for j in range(W+2):
                    ans = max(ans, distance[i][j])
print(ans-1)

Submission status: Wrong Answer

Solution code:
H,W = map(int, input().split())
S = [list('#'+input()+"#") for i in range(H)]
S.insert(0, list('#'*(W+2)))
S.append(list('#'*(W+2)))
vector = [(1,0), (-1,0), (0,1), (0,-1)]
ans = 0
for i in range(1,H+1):
    for j in range(1,W+1):
        if S[i][j]=='.':
            Q = [(i,j)]
            distance = [[0]*(W+2) for i in range(H+2)]
            distance[i][j] = 1
            while Q!=[]:
                x,y = Q.pop(0)
                for k in vector:
                    x1,y1 = x+k[0],y+k[1]
                    if S[x1][y1]=='.' and distance[x1][y1]==0:
                        Q.append((x1,y1))
                        distance[x1][y1] = distance[x][y] + 1
            for i in range(H+2):
                ans = max(ans, max(distance[i]))
print(ans-1)

Submission status: Wrong Answer

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

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

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

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

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

Submission status: Wrong Answer

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


def dfs(h, w, gh, gw, visited, count):
    min_move = float("inf")
    reach_goal = False
    # up
    if (h >= 1) and (S[h - 1][w] != "#") and (not visited[h - 1][w]):
        if (h - 1, w) == (gh, gw):
            return count + 1
        visited[h - 1][w] = True
        ret = dfs(h - 1, w, gh, gw, visited, count + 1)
        visited[h - 1][w] = False
        if (ret != -1) and ret < min_move:
            min_move = ret
            reach_goal = True
    # down
    if (h < H - 1) and (S[h + 1][w] != "#") and (not visited[h + 1][w]):
        if (h + 1, w) == (gh, gw):
            return count + 1
        visited[h + 1][w] = True
        ret = dfs(h + 1, w, gh, gw, visited, count + 1)
        visited[h + 1][w] = False
        if (ret != 0) and ret < min_move:
            min_move = ret
            reach_goal = True
    # left
    if (w >= 1) and (S[h][w - 1] != "#") and (not visited[h][w - 1]):
        if (h, w - 1) == (gh, gw):
            return count + 1
        visited[h][w - 1] = True
        ret = dfs(h, w - 1, gh, gw, visited, count + 1)
        visited[h][w - 1] = False
        if (ret != 0) and (ret < min_move):
            min_move = ret
            reach_goal = True
    # right
    if (w < W - 1) and (S[h][w + 1] != "#") and (not visited[h][w + 1]):
        if (h, w + 1) == (gh, gw):
            return count + 1
        visited[h][w + 1] = True
        ret = dfs(h, w + 1, gh, gw, visited, count + 1)
        visited[h][w + 1] = False
        if (ret != 0) and (ret < min_move):
            min_move = ret
            reach_goal = True
    if reach_goal:
        return min_move
    else:
        return -1


visited = [[False for _ in range(W)] for _ in range(H)]
ans = 0
for gh in range(H):
    for gw in range(W):
        if S[gh][gw] == "#":
            continue
        for h in range(H):
            for w in range(W):
                if S[h][w] == "#":
                    continue
                if (h, w) == (gh, gw):
                    continue
                visited[h][w] = True
                min_move = dfs(h, w, gh, gw, visited, 0)
                visited[h][w] = False
                if min_move > ans:
                    ans = min_move

print(ans)

Submission status: Wrong Answer

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):
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    if m < t:
      m = t
print(m)

Submission status: Wrong Answer

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 == float('inf'):
        continue
      elif m < column:
        m = column
  return m
m = 0
for i in range(h):
  for j in range(w):
    q = queue.Queue()
    q.put([[i,j], 0, []])
    t = bfs(q)
    if m < t:
      m = t
print(m)

Submission status: Wrong Answer

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):
            max_v = max(max_v, bfs(h, w, H, W, s))
    print(max_v)
resolve()

Submission status: Wrong Answer

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

    def bfs(row, col, R, C, goal_r, goal_c, s):
        if s[goal_r][goal_c] == '#':
            return -1

        from collections import deque
        q = deque()
        q.append([(row, col), 0])
        seen = set()
        ans = -1
        while q:
            (r, c), dist = q.popleft()
            seen.add((r, c))
            if r == goal_r and c == goal_c:
                ans = dist
                break
            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

    def helper(i, j, row, column, s):
        max_v = -1
        for r in range(row):
            for c in range(column):
                max_v = max(max_v, bfs(i, j, H, W, r, c, s))
        return max_v

    max_v = -1
    for h in range(H):
        for w in range(W):
            max_v = max(max_v, helper(h, w, H, W, s))
    print(max_v)
resolve()

Submission status: Wrong Answer

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 dic[j][2] == 1:
      break
    if i == j or g == '#':
        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: Wrong Answer

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):
    for gy in range(H):
      for gx in range(W):
        if sx == gx and sy == gy and maze[sy][sx] == '#' and 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: Wrong Answer

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):
    for gy in range(H):
      for gx in range(W):
        if sx == gx and sy == gy:
          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: Wrong Answer

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

def bfs(x, y):
  D = [[10 ** 9 for i in range(W)] for j in range(H)]
  q = queue.Queue()
  q.put([x, y])
  D[y][x] = 0
  direct = [[-1, 0], [1, 0], [0, -1], [0, 1]]
  max_distance = 0
  while q.qsize() != 0:
    x, y = q.get()
    for dx, dy in direct:
      nx, ny = x + dx, y + dy
      if nx < 0 or nx >= W or ny < 0 or ny >= H:
        continue
      if M[ny][nx] == "#":
        continue
      if D[ny][nx] > D[y][x] + 1:
        D[ny][nx] = D[y][x] + 1
        max_distance = max([max_distance, D[ny][nx]])
        q.put([nx, ny])
  return max_distance

result = 0
for y in range(H):
  for x in range(W):
    result = max([result, bfs(x, y)])
print(result)