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

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

board = []
for row in range(h):
    board.append(list(input()))

def bfs(row, col):
    max_path = 0
    queue = deque([(row, col)])
    visited[row][col] = 0
    while queue:
        next = queue.popleft()
        if next[0] < h-1 and visited[next[0]+1][next[1]] == -1 and board[next[0]+1][next[1]] == ".":
            visited[next[0]+1][next[1]] = visited[next[0]][next[1]] + 1
            if visited[next[0]][next[1]] + 1 > max_path:
                max_path = visited[next[0]][next[1]] + 1
            queue.append((next[0]+1, next[1]))
        if next[0] > 0 and visited[next[0]-1][next[1]] == -1 and board[next[0]-1][next[1]] == ".":
            visited[next[0]-1][next[1]] = visited[next[0]][next[1]] + 1
            if visited[next[0]][next[1]] + 1 > max_path:
                max_path = visited[next[0]][next[1]] + 1
            queue.append((next[0]-1, next[1]))
        if next[1] < w-1 and visited[next[0]][next[1]+1] == -1 and board[next[0]][next[1]+1] == ".":
            visited[next[0]][next[1]+1] = visited[next[0]][next[1]] + 1
            if visited[next[0]][next[1]] + 1 > max_path:
                max_path = visited[next[0]][next[1]] + 1
            queue.append((next[0], next[1]+1))
        if next[1] > 0 and visited[next[0]][next[1]-1] == -1 and board[next[0]][next[1]-1] == ".":
            visited[next[0]][next[1]-1] = visited[next[0]][next[1]] + 1
            if visited[next[0]][next[1]] + 1 > max_path:
                max_path = visited[next[0]][next[1]] + 1
            queue.append((next[0], next[1]-1))
    return max_path

result = 0
for i in range(h):
    for j in range(w):
        visited = [[-1]*w for _ in range(h)]
        max_path = bfs(i, j)
        if result < max_path:
            result = max_path

print(result)

Submission status: Wrong Answer

Solution code:
from collections import deque
def farthest(yi,xi):
    q = deque([])
    q.append((yi,xi))
    dis = [[-1]*(w+2) for i in range(h+2)]
    dis[yi][xi] = 0
    while q:
        y,x = q.popleft()
        for i in range(4):
            nexty = y + dy[i]
            nextx = x + dx[i]
            if maze[nexty][nextx] == '.' and dis[nexty][nextx] == -1:
                q.append((nexty,nextx))
                dis[nexty][nextx] = dis[y][x] + 1
    return dis[y][x]
h,w = map(int,input().split())
maze = [['#'] * (w+2)]
maze += [['#']+[x for x in input()]+['#'] for _ in range(h)]
maze += [['#'] * (w+2)]
dx = [-1,0,0,1]
dy = [0,1,-1,0]
maxdis = 1
for i in range(1,h+1):
    for j in range(1,w+1):
        maxdis = max(maxdis,farthest(i,j))
print(maxdis)

Submission status: Wrong Answer

Solution code:
def max_array(Array):
  _max = 0
  for i in range(len(Array)):
    if max(Array[i]) > _max:
      _max = max(Array[i])
  return _max
  
def check(i, j):
  exp = length[i][j] + 1
  if i > 0:
    if length[i-1][j] == -1 and S[i-1][j]:
      length[i-1][j] = exp
      check(i-1, j)
  if i < H-1:
    if length[i+1][j] == -1 and S[i+1][j]:
      length[i+1][j] = exp
      check(i+1, j)
  if j > 0:
    if length[i][j-1] == -1 and S[i][j-1]:
      length[i][j-1] = exp
      check(i, j-1)
  if j < W-1:
    if length[i][j+1] == -1 and S[i][j+1]:
      length[i][j+1] = exp
      check(i, j+1)

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

for i in range(H):
  A = input()
  for j in range(W):
    S[i].append(True if A[j] == '.' else False)
  
_max = 0
for i in range(H):
  for j in range(W):
    if S[i][j]:
      length = [[-1] * W for i in range(H)]
      length[i][j] = 0
      check(i, j)
      num = max_array(length)
      #print(num, length)
      
      if num > _max:
        _max = num

print(_max)

Submission status: Wrong Answer

Solution code:
from collections import deque
#import numpy as np

h, w = map(int, input().split())
S = [input() for _ in range(h)] # #.のグリッドの場合

starts = []
for i in range(h):
    for j in range(w):
        if S[i][j] == '.':
            starts.append((i,j))

step = [(1, 0), (-1, 0), (0, 1), (0, -1)]
ans = 0
for si in starts:
    maxlen = 0
    seen = [[0] * w for _ in range(h)]
    que = deque()
    que.append(si)
    while len(que) > 0:
        x, y = que.popleft()
        for xs, ys in step:
            xi, yi = x + xs, y + ys
            if xi < 0 or yi < 0 or xi >= h or yi >= w:
                continue
            if S[xi][yi] == '#':
                continue
            if seen[xi][yi] != 0:
                continue
            else:
                seen[xi][yi] = seen[x][y] + 1
                que.append((xi, yi))
                maxlen = max(maxlen, seen[xi][yi])
    #print(np.array(seen))
    ans = max(ans, maxlen)
print(ans)

Submission status: Wrong Answer

Solution code:
from copy import deepcopy


def solve(maze, i, j, h, w, count):
    if maze[i][j] == "#":
        return 0
    else:
        next_search = [(i, j)]
        while not next_search == []:
            now = next_search.pop(0)
            if maze[now[0]][now[1]] == ".":
                maze[now[0]][now[1]] = "#"
                for direction in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
                    search = [direction[0] + now[0], direction[1] + now[1]]
                    if 0 <= search[0] < h and 0 <= search[1] < w and maze[search[0]][search[1]] == ".":
                        count[now[0] + direction[0]][now[1] + direction[1]] = count[now[0]][now[1]] + 1
                        next_search.append((now[0] + direction[0], now[1] + direction[1]))
        return max(max(count))


def main():
    height, width = map(int, input().split(" "))
    maze = []
    answer = 0
    for _ in range(height):
        maze.append(list(input()))
    count = [[0 for _ in range(width)] for _ in range(height)]
    for i in range(height):
        for j in range(width):
            answer = max(answer, solve(deepcopy(maze), i, j, height, width, deepcopy(count)))
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import queue

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

q = queue.Queue()
def bfs(x, y, cnt):
    if 0 <= x and x < w and 0 <= y and y < h and s[y][x] == "." and t[y][x] == ".":
        t[y][x] = cnt
        cnt += 1
        q.put((x, y))
        x, y = q.get()
        bfs(x+1, y, cnt)
        bfs(x-1, y, cnt)
        bfs(x, y+1, cnt)
        bfs(x, y-1, cnt)
        ans.append(cnt-1)
        
ans = []
for i in range(h):
    for j in range(w):
        t = [["."]*w for _ in range(h)]
        bfs(j, i, 0)

print(max(ans))

Submission status: Wrong Answer

Solution code:
h,w=map(int,input().split())
data=[]
data.append(list("#"*(w+2)))
for i in range(h):
    s=input()
    s="#"+s+"#"
    lists=list(s)
    data.append(lists)
data.append("#"*(w+2))
s=0
graph={i:[] for i in range(1,h*w+1)}
for i in range(1,h+1):
    for j in range(1,w+1):
        if data[i][j]==".":
            a=w*(i-1)+j
            s=a
            if data[i+1][j]==".":
                b=w*(i)+j
                graph[b].append(a)
                graph[a].append(b)

            if data[i][j+1]==".":
                b=w*(i-1)+j+1
                graph[b].append(a)
                graph[a].append(b)

from collections import deque

def how_far_from(s,n):
    d=deque()
#頂点sからどのくらいの距離にあるのかを返す関数
    parent=[0 for i in range(n+1)]
    visited=[False for i in range(n+1)]
    visited[s]=True
    d.append((s,0))

    how_far={i:[] for i in range(n+1)}
    while d:
        node=d.popleft()
        for point in graph[node[0]]:
            if visited[point]==False:
      
                visited[point]=True

                d.append((point,node[1]+1))
                how_far[node[1]+1].append(point)

    return how_far

P=how_far_from(s,h*w)


for i in range(h*w,-1,-1):
    if P[i]:
        start=P[i][0]
        break
Q=how_far_from(start,h*w)
for i in range(h*w,-1,-1):
    if Q[i]:
        print(i)
        break

Submission status: Wrong Answer

Solution code:
from collections import deque

h, w = map(int, input().split())
s = [list(input()) for _ in range(h)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]


def bfs(x, y):
    d = [[-1] * w for _ in range(h)]
    q = deque()
    q.append([x, y])
    d[x][y] = 0
    while q:
        p = q.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != '#' and d[nx][
                    ny] == -1:
                q.append([nx, ny])
                d[nx][ny] = d[p[0]][p[1]] + 1
    cnt = 0
    for i in range(h):
        for j in range(w):
            cnt = max(cnt, d[i][j])
    return cnt


ans = 0
for i in range(h):
    for j in range(w):
        ans = max(ans, bfs(i, j))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w = map(int,input().rstrip().split())

def bsf(x,y,sy,sx):
  dx = [1,0,-1,0]
  dy = [0,1,0,-1]
  val = 0
  x[sx][sy] = 0
  cx = sx
  cy = sy
  d = deque()
  d.append((cx,cy))
  while d:
    cx,cy = d.popleft()
      
    for l in range(4):
      nx = cx + dx[l]
      ny = cy + dy[l]
      
      if 0 <= nx < h and 0 <= ny < w :
        if x[nx][ny] <= -1 and y[nx][ny] != '#':
          d.append((nx,ny))
          x[nx][ny] = x[cx][cy] + 1 

  return max(max(x))

#いけるとこといけないとこ
y = []
for i in range(h):
  y.append(list(input().rstrip()))

#初期迷路
x = [[-1] * w for _ in range(h)]


res = 0
for i in range(w):
  for j in range(h):
    sx = i 
    sy = j
    tmp = bsf(x,y,i,j)
    res = max(res,tmp)

print(res)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w=map(int,input().split())
G=[["#"]*(w+2) for i in range(h+2)]
for i in range(1,h+1):
  G[i]=["#"]+list(input())+["#"]
ans=0
for sx in range(1,h+1):
  for sy in range(1,w+1):
    if G[sx][sy]==".":
      B=[[0]*(w+2) for i in range(h+2)]
      for i in range(h+2):
        for j in range(w+2):
          if G[i][j]=="#":
            B[i][j]=1
      INF=10**4
      A=[[INF]*(w+2) for i in range(h+2)]
      C=[-1,1,0,0]
      D=[0,0,-1,1]
      A[sx][sy]=0
      E=deque([sx,sy])
      while len(E)>0:
        x=E[0]
        E.popleft()
        y=E[0]
        E.popleft()
        B[x][y]=1
        for i in range(4):
          if B[x+C[i]][y+D[i]]==0:
            A[x+C[i]][y+D[i]]=A[x][y]+1
            a=A[x+C[i]][y+D[i]]
            print(a)
            B[x+C[i]][y+D[i]]=1
            E.append(x+C[i])
            E.append(y+D[i])
      if ans<a:
        ans=a
    else:
      continue
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w=map(int,input().split())
G=[["#"]*(w+2) for i in range(h+2)]
for i in range(1,h+1):
  G[i]=["#"]+list(input())+["#"]
ans=0
for sx in range(1,h+1):
  for sy in range(1,w+1):
    if G[sx][sy]==".":
      B=[[0]*(w+2) for i in range(h+2)]
      for i in range(h+2):
        for j in range(w+2):
          if G[i][j]=="#":
            B[i][j]=1
      INF=10**4
      A=[[INF]*(w+2) for i in range(h+2)]
      C=[-1,1,0,0]
      D=[0,0,-1,1]
      A[sx][sy]=0
      E=deque([sx,sy])
      while len(E)>0:
        x=E[0]
        E.popleft()
        y=E[0]
        E.popleft()
        for i in range(4):
          if B[x+C[i]][y+D[i]]==0:
            A[x+C[i]][y+D[i]]=A[x][y]+1
            a=A[x+C[i]][y+D[i]]
            B[x+C[i]][y+D[i]]=1
            E.append(x+C[i])
            E.append(y+D[i])
      if ans<a:
        ans=a
    else:
      continue
print(ans)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]
INF = 10<<1000

V = H*W
maze = [[INF]*V for _ in range(V)]

#隣接行列（対角成分）
for i in range(V):
    maze[i][i] = 0

#隣接行列（経路があれば1）
for py in range(H):
    for px in range(W):
        if s[py][px] == '#': continue
        target = [(px+1, py), (px-1, py), (px, py+1), (px, py-1)]
        for x, y in target:
            if not (0<=x<W and 0<=y<H): continue
            if s[y][x] == '#': continue
            maze[W*py+px][W*y+x] = 1

#ワーシャル・フロイド
for k in range(V):
    for i in range(V):
        for j in range(V):
            maze[i][j] = min(maze[i][j], maze[i][k]+maze[k][j])

res = 0
for i in range(V):
    for j in range(V):
        if j!=INF: res = max(res, maze[i][j])
          
print(res)

Submission status: Wrong Answer

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

#迷路と始点を引数に、最も遠い点までの距離を返す
def bfs(maze, sx, sy):
    d = [[-float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sy, sx))
    d[sy][sx] = 0

    while que:
        p = que.popleft()
        # if p[0] == gy and p[1] == gx:
        #     break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == -float("inf"):
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1

    for i in d:
        an = max(i)
    return an

# 取りうる全ての始点と終点の最短経路の最大値を求める
ans = 0
for i in range(h):
    for j in range(w):
        if maze[i][j]!="#":
            ans = max(ans, bfs(maze, j, i))

print(ans)

Submission status: Wrong Answer

Solution code:
#python3
from collections import deque         
INF = int(1e9)
dd = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def main():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = -1 
    
    for i in range(h):
        for j in range(w):
            if maze[i][j] == '#':
                continue
            g = [[INF for _ in range(w)] for _ in range(h)] 
            q = deque()
            q.append((i, j))
            g[i][j] = 0
            while len(q) > 0:
                pi, pj = q.popleft()
                for dx, dy in dd:
                    x = pi + dx
                    y = pj + dy
                    if (x < 0) | (y < 0) | (x >= h) | (y >= w): 
                        continue
                    if maze[x][y] == '#':
                        continue
                    if g[x][y] != INF:
                        continue
                    q.append((x, y))
                    g[x][y] = g[pi][pj]+1 
            

            for k in range(h):
                for l in range(w):
                    if g[k][l] == INF:
                        continue
                    ans = max(ans, g[i][j])
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
#python3
from collections import deque         
INF = int(1e9)
dd = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def main():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = -1 
    
    for i in range(h):
        for j in range(w):
            if maze[i][j] == '#':
                continue
            g = [[INF for _ in range(w)] for _ in range(h)] 
            q = deque()
            q.append((i, j))
            g[i][j] = 0
            while len(q) > 0:
                pi, pj = q.popleft()
                for dx, dy in dd:
                    x = pi + dx
                    y = pj + dy
                    if (x < 0) | (y < 0) | (x >= h) | (y >= w): 
                        continue
                    if maze[x][y] == '#':
                        continue
                    if g[x][y] != INF:
                        continue
                    q.append((x, y))
                    g[x][y] = g[pi][pj]+1 
            

            for i in range(h):
                for j in range(w):
                    if g[i][j] == INF:
                        continue
                    ans = max(ans, g[i][j])
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
#python3
from collections import deque         
INF = int(1e9)
dd = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def main():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = -1 
    
    for i in range(h):
        for j in range(w):
            if maze[i][j] == "#":
                continue
            g = [[INF for _ in range(w)] for _ in range(h)] 
            q = deque()
            q.append((i, j))
            g[i][j] = 0
            while len(q) > 0:
                pi, pj = q.popleft()
                for dx, dy in dd:
                    x = pi + dx
                    y = pj + dy
                    if (x < 0) | (y < 0) | (x >= h) | (y >= w): 
                        continue
                    if maze[x][y] == "#":
                        continue
                    if g[x][y] != INF:
                        continue
                    q.append((x, y))
                    g[x][y] = g[pi][pj]+1 
            

            for i in range(h):
                for j in range(w):
                    if g[i][j] == INF:
                        continue
                    ans = max(ans, g[i][j])
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
#python3
INF = int(1e9)
dd = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def main():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = -1 
    
    for i in range(h):
        for j in range(w):
            if maze[i][j] == "#":
                continue
            g = [[INF for _ in range(w)] for _ in range(h)] 
            from collections import deque         
            q = deque()
            q.append((i, j))
            g[i][j] = 0
            while len(q) > 0:
                pi, pj = q.popleft()
                for dx, dy in dd:
                    x = pi + dx
                    y = pj + dy
                    if (x < 0) | (y < 0) | (x >= h) | (y >= w): 
                        continue
                    if maze[x][y] == "#":
                        continue
                    if g[x][y] != INF:
                        continue
                    q.append((x, y))
                    g[x][y] = g[pi][pj]+1 
            

            for i in range(h):
                for j in range(w):
                    if g[i][j] == INF:
                        continue
                    ans = max(ans, g[i][j])
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
#python3
INF = int(1e9)
dd = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def main():
    h, w = map(int, input().split())
    maze = []
    ans = 0
    for _ in range(h):
        data = input()
        maze.append(data)    
    
    for i in range(h):
        for j in range(w):
            if maze[i][j] == "#":
                continue
            start = (i, j)
            from collections import deque         
            g = [[INF for _ in range(w)] for _ in range(h)] 
            q = deque()
            q.append(start)
            g[i][j] = 0
            while len(q) > 0:
                x, y = q.popleft()
                for d in dd:
                    di = x + d[0]
                    dj = y + d[1]
                    if (di < 0) | (dj < 0) | (di >= h) | (dj >= w): 
                        continue
                    if maze[di][dj] == "#":
                        continue
                    if g[di][dj] != INF:
                        continue
                    q.append((di, dj))
                    g[di][dj] = g[x][y]+1 
            

            for i in range(h):
                for j in range(w):
                    if g[i][j] == INF:
                        continue
                    ans = max(ans, g[i][j])
    print(ans)
main()

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = map(int, input().split())
#print("H={}, W={}".format(H, W))
S = [list(input()) for _ in range(H)] # input().split()だと分割されない！！！
#print(S)

def maxCost(s0, s1):
    """
    (s0, s1)から任意の道に最短経路で移動するとして、その中での最大コストを算出する
    """
    maxCost = 0
    visited = [[10**9 for _ in range(W)] for _ in range(H)] # そのマスへの移動の最小コスト
    q = deque([(s0, s1, 0)])
    visited[s0][s1] = 0

    while q:
        u0, u1, cost = q.popleft()
        #print("({}, {}), cost={}".format(u0, u1, cost))
        if u0 < H - 1 and S[u0+1][u1] == "." and visited[u0+1][u1] > cost+1:
            #print("first")
            visited[u0+1][u1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0+1, u1, cost+1))
        if u0 > 0 and S[u0-1][u1] == "." and visited[u0-1][u1] > cost+1:
            #print("second")
            visited[u0-1][u1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0-1, u1, cost+1))
        if u1 < W - 1 and S[u0][u1+1] == "." and visited[u0][u1+1] > cost+1:
            #print("third")
            visited[u0][u1+1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0, u1+1, cost+1))
        if u1 > 0 and S[u0][u1-1] == "." and visited[u0][u1-1] > cost+1:
            #print("fourth")
            visited[u0][u1-1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0, u1-1, cost+1))

    return maxCost

ans = 0
for i in range(H):
    for j in range(W):
        ans = max(ans, maxCost(i, j))
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from math import sqrt
from collections import deque
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)

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

def bfs(x,y):
    for i,j in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]]:
        if i<0 or h<=i or j<0 or w<=j :continue
        if dist[i][j] != -1:continue
        if miti[i][j]=="#":continue
        dist[i][j]=dist[x][y]+1
        queue.append([i,j])
    while queue:
        t,r=queue.popleft()
        bfs(t,r)
ans=0
for i in range(h):
    for j in range(w):
        if miti[i][j]=="#":continue
        dist=[[-1 for i in range(w)] for j in range(h)]
        dist[i][j]=0
        queue=deque([])
        bfs(i,j)
        print(dist)
        
        for s in range(h):
            for t in range(w):
                ans=max(ans,dist[s][t])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from math import sqrt
from collections import deque
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)

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

def bfs(x,y):
    for i,j in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]]:
        if i<0 or h<=i or j<0 or w<=j :continue
        if dist[i][j] != -1:continue
        if miti[i][j]=="#":continue
        dist[i][j]=dist[x][y]+1
        queue.append([i,j])
    while queue:
        t,r=queue.popleft()
        bfs(t,r)
ans=0
for i in range(h):
    for j in range(w):
        dist=[[-1 for i in range(w)] for j in range(h)]
        dist[i][j]=0
        queue=deque([])
        bfs(i,j)
        
        for s in range(h):
            for t in range(w):
                ans=max(ans,dist[s][t])
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from math import sqrt
from collections import deque
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)

h,w=map(int,input().split())
miti=[]
for i in range(h):
    miti.append(input())
    
dist=[[-1 for i in range(w)] for j in range(h)]
dist[0][0]=0
queue=deque([])
def bfs(x,y):
    for i,j in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]]:
        if i<0 or h<=i or j<0 or w<=j :continue
        if dist[i][j] != -1:continue
        if miti[i][j]=="#":continue
        dist[i][j]=dist[x][y]+1
        queue.append([i,j])
    while queue:
        t,r=queue.popleft()
        bfs(t,r)
bfs(0,0)
dis0=0
ty=[0,0]
for i in range(h):
    for j in range(w):
        if dis0<dist[i][j]:
            dis0=dist[i][j]
            ty=[i,j]
i,j=ty
dist=[[-1 for i in range(w)] for j in range(h)]
dist[i][j]=0
queue=deque([])
bfs(i,j)

ans=0


for i in range(h):
    for j in range(w):
        if ans<dist[i][j]:
            ans=dist[i][j]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from math import sqrt
from collections import deque
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)

h,w=map(int,input().split())
miti=[]
for i in range(h):
    miti.append(input())
    
dist=[[-1 for i in range(w)] for j in range(h)]
dist[0][0]=0
queue=deque([])
def bfs(x,y):
    for i,j in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]]:
        if i<0 or h<=i or j<0 or w<=j :continue
        if dist[i][j] != -1:continue
        if miti[i][j]=="#":continue
        dist[i][j]=dist[x][y]+1
        queue.append([i,j])
    while queue:
        t,r=queue.popleft()
        bfs(t,r)
bfs(0,0)
dis0=0
ty=[0,0]
for i in range(h):
    for j in range(w):
        if dis0<dist[i][j]:
            dis0=dist[i][j]
            ty=[i,j]
i,j=ty
dist=[[-1 for i in range(w)] for j in range(h)]
dist[i][j]=0
bfs(i,j)

ans=0


for i in range(h):
    for j in range(w):
        if ans<dist[i][j]:
            ans=dist[i][j]

print(ans)

Submission status: Wrong Answer

Solution code:
#縦がx，横がy

from collections import deque

H, W = map(int, input().split())
S = []
maxlen = 0

for _ in range(H):
    S.append(input())

#スタート地点
for i in range(H):
    for j in range(W):
        queue = deque([[i,j]])
        distance = [[-1]*W for _ in range(H)]
        distance[i][j] = 0
        mazemax = 0
        while len(queue): #queueが無くなるまで
            #print(*distance,sep="\n",end="\n\n")
            x, y = queue.popleft()
            for i2, j2 in ([1, 0], [-1, 0], [0, 1], [0, -1]): #四方向を見る
                new_x, new_y = x+i2, y+j2
                if new_x < 0 or new_x >= H or new_y < 0 or new_y >= W:
                    continue
                elif S[new_x][new_y] == "." and distance[new_x][new_y] == -1:
                    distance[new_x][new_y] = distance[x][y] + 1
                    mazemax = max(mazemax, distance[new_x][new_y])
                    queue.append([new_x, new_y])
            if len(queue) == 0:
                maxlen = max(maxlen,mazemax)

print(maxlen)

Submission status: Wrong Answer

Solution code:
from collections import deque
h,w=map(int,input().split())
S=[input() for _ in range(h)]
inf=float("inf")
ans=0
for i in range(h):
   for j in range(w):
      if S[i][j]!="#":
         dp=[[inf for _ in range(w)]for _ in range(h)]
         dp[i][j]=0
         que=deque([(i,j)])
         while que:
            si,sj=que.pop()
            for ni,nj in [(si+1,sj),(si-1,sj),(si,sj+1),(si,sj-1)]:
               if 0<=ni<h and 0<=nj<w and S[ni][nj]!="#":
                  if dp[ni][nj]>dp[si][sj]+1:
                     dp[ni][nj]=dp[si][sj]+1
                     que.append((ni,nj))
                     ans=max(ans,dp[si][sj]+1)
print(ans)

Submission status: Wrong Answer

Solution code:
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

# 改行またはスペース区切りの入力をすべて読み込んでイテレータを返します。
def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

def neighbors4(x, y):
  dxy = (0, 1, 0, -1, 0 )
  for i in range(4):
    yield(x + dxy[i], y + dxy[i+1])

h,w = get_nums_l()

grid_s = [ input() for _ in range(h) ]
grid = [ [-1] * (w+2) for _ in range(h+2) ]

log(grid_s)

for y in range(1,h+1):
    for x in range(1, w+1):
        if grid_s[y-1][x-1] == ".":
            grid[y][x] = 999999999999999999

# ダイクストラ一回目 適当な開始位置を決める

start_x = 1
start_y = 1
while grid[start_y][start_x] == -1:
    start_x += 1
    if start_x > w:
        start_x = 1
        start_y += 1

log(start_x, start_y)

grid[start_y][start_x] = 0

que = deque()
que.append((start_x, start_y, 1))

while que:
    x,y,score = que.popleft()

    for nx,ny in neighbors4(x,y):
        if grid[ny][nx] != -1 and grid[ny][nx] > score:
            grid[ny][nx] = score
            que.append((nx, ny, score+1))

log("ダイクストラ一回目 end")
log(grid)

max_ = -1
max_x = -1
max_y = -1

for y in range(1,h+1):
    for x in range(1, w+1):
        if grid[y][x] > max_:
            max_ = grid[y][x]
            max_x = x
            max_y = y

for y in range(1,h+1):
    for x in range(1, w+1):
        if grid_s[y-1][x-1] == ".":
            grid[y][x] = 999999999999999999

que = deque()
que.append((max_x, max_y, 1))


grid[max_y][max_x] = 0

while que:
    x,y,score = que.popleft()

    for nx,ny in neighbors4(x,y):
        if grid[ny][nx] != -1 and grid[ny][nx] > score:
            grid[ny][nx] = score
            que.append((nx, ny, score+1))

max_ = 0
max_x = -1
max_y = -1

for y in range(1,h+1):
    for x in range(1, w+1):
        if grid[y][x] > max_:
            max_ = grid[y][x]
            max_x = x
            max_y = y

for g in grid:
    log(g)

print(max_)