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:
h, w = map(int, input().split())
s = [input() for _ in range(h)]

def bfs(x, y):
    q = []
    dp = {}
    def qpush(x, y, t):
        if 0 <= x < w and 0 <= y < h and s[y][x] != '#' and (x, y) not in dp:
            q.append((x, y))
            dp[(x, y)] = t

    qpush(x, y, 0)
    while len(q) > 0:
        (x, y) = q.pop(0)
        qpush(x + 1, y, dp[(x, y)] + 1)
        qpush(x, y - 1, dp[(x, y)] + 1)
        qpush(x - 1, y, dp[(x, y)] + 1)
        qpush(x, y + 1, dp[(x, y)] + 1)
    return (dp[(x, y)], x, y)

y = 0
while s[y] == '#' * w:
    y += 1
x = s[y].index('.')

ret = 0
count = 0
while True:
    (t, x, y) = bfs(x, y)
    if t <= ret:
        count += 1
    else:
        ret = t
    if count > 5:
        break
print(t)

Submission status: Wrong Answer

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

def bfs(x, y):
    q = []
    dp = {}
    def qpush(x, y, t):
        if 0 <= x < w and 0 <= y < h and s[y][x] != '#' and (x, y) not in dp:
            q.append((x, y))
            dp[(x, y)] = t

    qpush(x, y, 0)
    while len(q) > 0:
        (x, y) = q.pop(0)
        qpush(x + 1, y, dp[(x, y)] + 1)
        qpush(x, y - 1, dp[(x, y)] + 1)
        qpush(x - 1, y, dp[(x, y)] + 1)
        qpush(x, y + 1, dp[(x, y)] + 1)
    return (dp[(x, y)], x, y)

y = 0
while s[y] == '#' * w:
    y += 1
x = s[y].index('.')

ret = 0
while True:
    (t, x, y) = bfs(x, y)
    if t <= ret:
        break
    ret = t
print(t)

Submission status: Wrong Answer

Solution code:
import collections

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

def bfs(x0, y0):
    visited = [[0 for _ in range(w)] for _ in range(h)]
    deq = collections.deque()
    deq.append((x0, y0, -1))

    mx = 0
    while len(deq) > 0:
        x, y, d = deq.popleft()
        nd = d + 1
        visited[x][y] = 1
        mx = max(mx, nd)

        for dx, dy in [(-1, 0), (0, -1), (+1, 0), (0, +1)]:
            nx = x + dx
            ny = y + dy
            if not (0 <= nx < h) or not (0 <= ny < w):
                # bound check
                continue
            if smat[nx][ny] == '#':
                # cell attr check
                continue
            if visited[nx][ny] == 1:
                # already visited
                continue
            v = (nx, ny, nd)
            deq.append(v)
    
    return mx

if all(all(col == '.' for col in row) for row in smat):
    print(w * h)
else:
    mxall = 0
    for x0 in range(h):
        for y0 in range(w):
            if smat[x0][y0] == '.':
                mx = bfs(x0, y0)
                mxall = max(mxall, mx)
    print(mxall)

Submission status: Wrong Answer

Solution code:
from collections import deque
from copy import deepcopy


def bfs(table, i, j, h, w):
    dq = deque()
    ans = 0
    dq.append((i, j, 0))  # x,y,distance
    while dq:
        x, y, dis = dq.popleft()
        ans = max(ans, dis)
        if x > 0 and (x - 1, y) and table[x - 1][y] != "#":
            dq.append((x - 1, y, dis + 1))
            table[x - 1][y] = "#"
        if x < h - 1 and (x + 1, y) and table[x + 1][y] != "#":
            dq.append((x + 1, y, dis + 1))
            table[x + 1][y] = "#"
        if y > 0 and (x, y - 1) and table[x][y - 1] != "#":
            dq.append((x, y - 1, dis + 1))
            table[x][y - 1] = "#"
        if y < w - 1 and (x, y + 1) and table[x][y + 1] != "#":
            dq.append((x, y + 1, dis + 1))
            table[x][y + 1] = "#"
    return ans


def main():
    h, w = [int(i) for i in input().strip().split()]
    grid = [list(input()) for _ in range(h)]
    ans = 0
    for i in range(h):
        for j in range(w):
            if grid[i][j] == ".":
                _grid = deepcopy(grid)
                max_path = bfs(_grid, i, j, h, w)
                ans = max(ans, max_path)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
from copy import deepcopy
input = sys.stdin.readline


def bfs(table, i, j, h, w):
    dq = deque()
    if table[i][j] == "#":
        return -1
    ans = 0
    dq.append((i, j, 0))  # x,y,distance
    while dq:
        x, y, dis = dq.popleft()
        ans = max(ans, dis)
        if x > 0 and (x - 1, y) and table[x - 1][y] != "#":
            dq.append((x - 1, y, dis + 1))
            table[x - 1][y] = "#"
        if x < h - 1 and (x + 1, y) and table[x + 1][y] != "#":
            dq.append((x + 1, y, dis + 1))
            table[x + 1][y] = "#"
        if y > 0 and (x, y - 1) and table[x][y - 1] != "#":
            dq.append((x, y - 1, dis + 1))
            table[x][y - 1] = "#"
        if y < w - 1 and (x, y + 1) and table[x][y + 1] != "#":
            dq.append((x, y + 1, dis + 1))
            table[x][y + 1] = "#"
    return ans


def main():
    h, w = [int(i) for i in input().strip().split()]
    grid = [list(input().strip()) for _ in range(h)]
    ans = 0
    for i in range(h):
        for j in range(w):
            if grid[i][j] == ".":
                _grid = deepcopy(grid)
                max_path = bfs(_grid, i, j, h, w)
                ans = max(ans, max_path)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
from copy import deepcopy
input = sys.stdin.readline


def bfs(table, i, j):
    dq = deque()
    if table[i][j] == "#":
        return -1
    h = len(table)
    w = len(table[0])
    ans = 0
    dq.append((i, j, 0))  # x,y,distance
    while dq:
        x, y, dis = dq.popleft()
        ans = max(ans, dis)
        if x > 0 and (x - 1, y) and table[x - 1][y] != "#":
            dq.append((x - 1, y, dis + 1))
            table[x - 1][y] = "#"
        if x < h - 1 and (x + 1, y) and table[x + 1][y] != "#":
            dq.append((x + 1, y, dis + 1))
            table[x + 1][y] = "#"
        if y > 0 and (x, y - 1) and table[x][y - 1] != "#":
            dq.append((x, y - 1, dis + 1))
            table[x][y - 1] = "#"
        if y < w - 1 and (x, y + 1) and table[x][y + 1] != "#":
            dq.append((x, y + 1, dis + 1))
            table[x][y + 1] = "#"
    return ans


def main():
    h, w = [int(i) for i in input().strip().split()]
    grid = [list(input().strip()) for _ in range(h)]
    ans = 0
    for i in range(h):
        for j in range(w):
            if grid[i][j] == ".":
                _grid = deepcopy(grid)
                max_path = bfs(_grid, i, j)
                ans = max(ans, max_path)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque
import sys
from copy import deepcopy
input = sys.stdin.readline


def bfs(table, i, j):
    dq = deque()
    if table[i][j] == "#":
        return -1
    h = len(table)
    w = len(table[0])
    ans = 0
    dq.append((i, j, 0))  # x,y,distance
    while dq:
        x, y, dis = dq.popleft()
        ans = max(ans, dis)
        if x > 0 and (x - 1, y) and table[x - 1][y] != "#":
            dq.append((x - 1, y, dis + 1))
            table[x - 1][y] = "#"
        if x < h - 1 and (x + 1, y) and table[x + 1][y] != "#":
            dq.append((x + 1, y, dis + 1))
            table[x + 1][y] = "#"
        if y > 0 and (x, y - 1) and table[x][y - 1] != "#":
            dq.append((x, y - 1, dis + 1))
            table[x][y - 1] = "#"
        if y < w - 1 and (x, y + 1) and table[x][y + 1] != "#":
            dq.append((x, y + 1, dis + 1))
            table[x][y + 1] = "#"
    return ans


def main():
    h, w = [int(i) for i in input().strip().split()]
    grid = [list(input().strip()) for _ in range(h)]
    ans = -1
    for i in range(h):
        for j in range(w):
            if grid[i][j] == ".":
                _grid = deepcopy(grid)
                max_path = bfs(_grid, i, j)
                ans = max(ans, max_path)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import deque

H, W = [int(s) for s in input().split()]
fields = []
for _ in range(H):
    fields.append(list(input()))

fields_num = []
for i in range(H):
    for j in range(W):
        fields_num.append((i, j))


def get_search_obj(i, j):
    ret = []
    moving_range = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    for dx, dy in moving_range:
        if 0 <= (i + dx) <= (H - 1) and 0 <= (j + dy) <= (W - 1) and fields[i + dx][j + dy] == '.':
            ret.append((i + dx, j + dy))
    return ret


def bfs(start, end):
    start = [start[0], start[1], 0]
    dq = deque([start])
    visited = [[False] * W for _ in range(H)]
    while dq:
        sx, sy, cnt = dq.pop()
        for x, y in get_search_obj(sx, sy):
            if x == end[0] and y == end[1]:
                return cnt + 1
            if not visited[x][y]:
                dq.appendleft([x, y, cnt + 1])
                visited[x][y] = True
    return 0


max_hop = 0
for i in range(H * W):
    for j in range(i + 1, H * W):
        h1, w1 = fields_num[i]
        h2, w2 = fields_num[j]
        if abs(h1 - h2) + abs(w1 - w2) <= max_hop:
            continue
        if fields[h1][w1] == '.' and fields[h2][w2] == '.':
            max_hop = max(max_hop, bfs((h1, w1), (h2, w2)))

print(max_hop)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import deque

H, W = [int(s) for s in input().split()]
fields = []
for _ in range(H):
    fields.append(list(input()))

fields_num = []
for i in range(H):
    for j in range(W):
        fields_num.append((i, j))


def get_search_obj(i, j):
    ret = []
    moving_range = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    for dx, dy in moving_range:
        if 0 <= (i + dx) <= (H - 1) and 0 <= (j + dy) <= (W - 1) and fields[i + dx][j + dy] == '.':
            ret.append((i + dx, j + dy))
    return ret


def bfs(start, end):
    start = [start[0], start[1], 0]
    dq = deque([start])
    visited = [[False] * W for _ in range(H)]
    while dq:
        sx, sy, cnt = dq.pop()
        for x, y in get_search_obj(sx, sy):
            if x == end[0] and y == end[1]:
                return cnt + 1
            if not visited[x][y]:
                dq.appendleft([x, y, cnt + 1])
                visited[x][y] = True
    return 0


max_hop = 0
for i in range(H * W):
    for j in range(H * W):
        h1, w1 = fields_num[i]
        h2, w2 = fields_num[j]
        if fields[h1][w1] == '.' and fields[h2][w2] == '.':
            max_hop = max(max_hop, bfs((h1, w1), (h2, w2)))

print(max_hop)

Submission status: Wrong Answer

Solution code:
import os, sys, re, math


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


def set_moves(x, y, moves):
    if grid[y][x] >= 0 and grid[y][x] < moves:
        return
    grid[y][x] = moves

    if y > 0 and S[y - 1][x] == '.':
        set_moves(x, y - 1, moves + 1)
    if y < (H - 1) and S[y + 1][x] == '.':
        set_moves(x, y + 1, moves + 1)
    if x > 0 and S[y][x - 1] == '.':
        set_moves(x - 1, y, moves + 1)
    if x < (W - 1) and S[y][x + 1] == '.':
        set_moves(x + 1, y, moves + 1)


S = []
for i in range(H):
    S.append(input())

result = 0

for gy in range(H):
    for gx in range(W):
        grid = []
        for i in range(H):
            grid.append([-1] * W)
        set_moves(gx, gy, 0)

        result = max(result, max([max(row) for row in grid]))

print(result)

Submission status: Wrong Answer

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

def bfs(x, y):
    q = []
    dp = {}
    def qpush(x, y, t):
        if 0 <= x < w and 0 <= y < h and s[y][x] != '#' and (x, y) not in dp:
            q.append((x, y))
            dp[(x, y)] = t

    qpush(x, y, 0)
    while len(q) > 0:
        (x, y) = q.pop(0)
        qpush(x + 1, y, dp[(x, y)] + 1)
        qpush(x, y - 1, dp[(x, y)] + 1)
        qpush(x - 1, y, dp[(x, y)] + 1)
        qpush(x, y + 1, dp[(x, y)] + 1)
    return (dp[(x, y)], x, y)

y = 0
while s[y] == '#' * w:
    y += 1
x = s[y].index('.')
(t, x, y) = bfs(x, y)
(t, x, y) = bfs(x, y)
print(t)

Submission status: Wrong Answer

Solution code:
r, c = list(map(int, input().split(' ')))
matrix = []
for i in range(r):
    matrix.append(input())

ans = 0
cost = {}  # cost[(i, j), (p, q)]  -> (i,j) -> (p,q) の minコスト (20 * 20 * 20 * 20 = 1.6 * 1e4)
for i in range(r):
    for j in range(c):
        if matrix[i][j] == '#':  # !!!
            continue
        start = (i, j)
        cost[(i,j), (i,j)] = 0
        q = [start]
        while q:
            ti, tj = q.pop(0)
            for ni, nj in [(ti-1, tj), (ti, tj-1), (ti+1, tj), (ti, tj+1)]:
                if ni < 0 or nj < 0 or ni >= r or nj >= c or matrix[ti][tj] == '#':
                    continue
                if cost.get(((i,j), (ni, nj)), 99999999999999999) > cost[(i,j), (ti, tj)] + 1:
                    cost[(i,j), (ni, nj)] = cost[(i,j), (ti, tj)] + 1
                    ans = max(ans, cost[(i,j), (ni, nj)])
                    q.append((ni, nj))
print(ans)

Submission status: Wrong Answer

Solution code:
r, c = list(map(int, input().split(' ')))
matrix = []
for i in range(r):
    matrix.append(input())

ans = 0
cost = {}  # cost[(i, j), (p, q)]  -> (i,j) -> (p,q) の minコスト (20 * 20 * 20 * 20 = 1.6 * 1e4)
for i in range(r):
    for j in range(c):
        start = (i, j)
        cost[(i,j), (i,j)] = 0
        q = [start]
        while q:
            ti, tj = q.pop(0)
            for ni, nj in [(ti-1, tj), (ti, tj-1), (ti+1, tj), (ti, tj+1)]:
                if ni < 0 or nj < 0 or ni >= r or nj >= c or matrix[ti][tj] == '#':
                    continue
                if cost.get(((i,j), (ni, nj)), 99999999999999999) > cost[(i,j), (ti, tj)] + 1:
                    cost[(i,j), (ni, nj)] = cost[(i,j), (ti, tj)] + 1
                    ans = max(ans, cost[(i,j), (ni, nj)])
                    q.append((ni, nj))
print(ans)

Submission status: Wrong Answer

Solution code:
def resolve():
    H, W = list(map(int, input().split()))
    S = [list(input()) for _ in range(H)]
    import collections
    maxdist = 0
    for startx in range(H):
        for starty in range(W):
            visited = [[False for _ in range(W)] for __ in range(H)]
            q = collections.deque([(startx, starty, 0)])
            while q:
                x, y, dist = q.pop()
                visited[x][y] = True
                maxdist = max(maxdist, dist)
                for dx, dy in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                    nx = x + dx
                    ny = y + dy
                    if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "#" and visited[nx][ny] is False:
                        q.appendleft((nx, ny, dist+1))
    print(maxdist)
    

if '__main__' == __name__:
    resolve()

Submission status: Wrong Answer

Solution code:
import math
import collections
import fractions
import itertools
import functools
import operator
import numpy as np

def solve():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = 0
    can_move = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    for x in range(h):
        for y in range(w):
            if maze[x][y] == "#":
                continue
            dist = [[0]*w for _ in range(h)]
            stack = collections.deque()
            stack.append([x,y])
            while stack:
                h2, w2 = stack.popleft()
                for i, j in can_move:
                    newh, neww = h+i, w+j
                    if newh < 0 or neww < 0 or newh >= h or neww >= w:
                        continue
                    elif maze[newh][neww] != "#" and dist[newh][neww] == 0:
                        dist[newh][neww] = dist[h2][w2]+1
                        stack.append([newh, neww])
            dist[x][y] = 0
            ans = max(ans, np.max(dist))
    print(ans)
    return 0

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
h,w = map(int,input().split())
l=[]


for i in range(h):
  s=[x for x in input()]
  l.append(s)


move=[[1,0],[-1,0],[0,1],[0,-1]]

def bfs(x,y):
  done=[[0 for i in range(w)] for j in range(h)]
  ans,cnt = 0,0
  que=[[x,y,cnt]]
  done[y][x]=0

  while(que):
    nx,ny,cnt = que.pop(0)

    for dx,dy in move:
      mx=nx+dx
      my=ny+dy

      if 0<=mx<w and 0<=my<h and done[my][mx]==0 and l[my][mx]==".":
        done[my][mx]=cnt+1
        que.append([mx,my,cnt+1])
        
        ans=max(ans,cnt+1)
  return ans


ans_r=0
for i in range(w):
  for j in range(h):
    if l[j][i]==".":
      now=bfs(i,j)
      ans_r=max(now,ans_r)
print(ans_r)

Submission status: Wrong Answer

Solution code:
def solve():
    def bfs(maze, start):
        from collections import deque

        directions = ((-1,0), (1,0), (0,-1), (0, 1))
        H = len(maze)
        W = len(maze[0])
        nexts = deque()
        nexts.append((start, 0))
        x,y = start
        maze[x][y] = '#'
        longest_distance = 0
        while nexts:
            cur_pos,cur_distance = nexts.popleft()
            longest_distance = max(cur_distance, longest_distance)
            x,y = cur_pos
            for direction in directions:
                dx,dy = direction
                next_x = x + dx
                next_y = y + dy
                next_pos = (next_x, next_y)
                if 0 <= next_x < H and 0 <= next_y < W and next_pos:
                    if maze[next_x][next_y] == '.':
                        maze[next_x][next_y] = '#'
                        nexts.append(((next_x, next_y), cur_distance+1))
        return longest_distance

    H,W = [int(i) for i in input().split()]
    maze = []
    for i in range(H):
        row = [c for c in input()]
        maze.append(row)

    ans = 0
    for i in range(H):
        for j in range(W):
            if maze[i][j] == '.':
                start = (i,j)
                ans = max(bfs(maze, start), ans)

    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
def solve():
    def bfs(maze, start, distances):
        from collections import deque

        directions = ((-1,0), (1,0), (0,-1), (0, 1))
        H = len(maze)
        W = len(maze[0])
        nexts = deque()
        nexts.append((start, 0))
        x,y = start
        maze[x][y] = 0
        while nexts:
            cur_pos,cur_distance = nexts.popleft()
            x,y = cur_pos
            is_deadend = True
            for direction in directions:
                dx,dy = direction
                next_x = x + dx
                next_y = y + dy
                next_pos = (next_x, next_y)
                if 0 <= next_x < H and 0 <= next_y < W and next_pos:
                    next_symbol = maze[next_x][next_y]
                    if next_symbol == '.':
                        maze[next_x][next_y] = cur_distance + 1
                        nexts.append(((next_x, next_y), cur_distance+1))
                        is_deadend = False
                    elif next_symbol == '#':
                        continue
                    elif next_symbol > cur_distance:
                        is_deadend = False
            if is_deadend:
                distances[cur_pos] = cur_distance
            cur_distance += 1

    H,W = [int(i) for i in input().split()]
    # print(H,W)
    maze = []
    for i in range(H):
        row = [c for c in input()]
        maze.append(row)

    distances = {}
    for i in range(H):
        for j in range(W):
            if maze[i][j] == '.':
                start = (i,j)
                distances[start] = 0
                bfs(maze, start, distances)
                break

    sorted_distances = sorted(distances.values())
    # print(distances)
    # print(sorted_distances)
    print(sorted_distances[-1] + sorted_distances[-2])


if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
def solve():
    def bfs(maze, start, distances):
        from collections import deque

        directions = ((-1,0), (1,0), (0,-1), (0, 1))
        H = len(maze)
        W = len(maze[0])
        nexts = deque()
        nexts.append((start, 0))
        while nexts:
            cur_pos,cur_distance = nexts.popleft()
            x,y = cur_pos
            maze[x][y] = '#'
            is_dead_end = True
            for direction in directions:
                dx,dy = direction
                next_x = x + dx
                next_y = y + dy
                if 0 <= next_x < H and 0 <= next_y < W:
                    if maze[next_x][next_y] == '.':
                        nexts.append(((next_x, next_y), cur_distance+1))
                        is_dead_end = False
            if is_dead_end:
                distances[cur_pos] = cur_distance
            cur_distance += 1


    H,W = [int(i) for i in input().split()]
    # print(H,W)
    maze = []
    for i in range(H):
        maze.append([c for c in input()])

    distances = {}
    for i in range(H):
        for j in range(W):
            if maze[i][j] == '.':
                start = (i,j)
                distances[start] = 0
                bfs(maze, start, distances)
                break

    sorted_distances = sorted(distances.values())
    # print(distances)
    # print(sorted_distances)
    print(sorted_distances[-1] + sorted_distances[-2])


if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:

from collections import deque

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


def bfs(si, sj):
    offset = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    INF = 10 ** 9 + 7
    d = [[INF] * W for _ in range(H)]
    d[si][sj] = 0
    q = deque()
    q.append((si, sj))
    while q:
        u, v = q.popleft()
        for i, j in offset:
            if (0 <= u + i < H and 0 <= v + j < W and X[u + i][v + j] == "."
                    and d[u + i][v + j] > d[u][v] + 1):
                d[u + i][v + j] = d[u][v] + 1
                q.append((u + i, v + j))

    res = 0
    for x in d:
        for v in x:
            if v < INF:
                res = max(res, v)

    return res


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:
H, W = map(int, input().split())
# initialize maze
maze = []

for r in range(H):
  maze.append(list(input()))
maxVisit = 0
for row in maze:
  for road in row:
    if (road == "."):
      maxVisit += 1
# do bfs for each point and record maximum steps...
def findMaxBFS(start):
  # initialize BFS
  visitedCount = 1
  visitedPoints = []
  for r in range(H):
    visitedPoints.append([])
    for c in range(W):
      visitedPoints[r].append("N")
  points = [start]
  directions = [[0,1], [0,-1], [1,0], [-1,0]]
  steps = 0
  # BFS starts
  while (visitedCount <= maxVisit):
    steps += 1
    nextPoints = []
    for p in points:
      for d in directions:
        nextP = [p[0]+d[0], p[1]+d[1]]
        #check nextP is inside the maze
        if (0<=nextP[0] and nextP[0]<H) and (0<=nextP[1] and nextP[1]<W):
          road = maze[nextP[0]][nextP[1]]
          #check nextP is walkable = stone
          if (road == "."):
            # check if nextP is already visisted
            if (visitedPoints[nextP[0]][nextP[1]] == "N"):           
              nextPoints.append(nextP)
              visitedCount += 1
              visitedPoints[nextP[0]][nextP[1]] = "Y" 
    points = nextPoints
  # BFS ended
  # return max step
  return steps

max_steps = []
for r in range(H):
  for c in range(W):
    max_steps.append(findMaxBFS([r,c]))
print(max(max_steps))

Submission status: Wrong Answer

Solution code:
from collections import deque
import itertools

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


# x,yはスタートの座標
def bfs(x, y):
    # 最初は全て未訪問なので-1で初期化
    d = [[-1] * w for _ in range(h)]
    # スタート地点への距離は0
    d[x][y] = 0
    q = deque([(x, y)])
    while q:
        tx, ty = q.popleft()
        # 右、上、左、下
        for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
            nx, ny = tx + dx, ty + dy
            # グリッドの範囲内で、通路で、未訪問の場合
            if 0 <= nx < h and 0 <= ny < w and g[nx][ny] == '.' and d[nx][ny] < 0:
                d[nx][ny] = d[tx][ty] + 1
                q.append((nx, ny))
    # 最終的なdを平坦化して最大値を返す
    return max(list(itertools.chain.from_iterable(d)))

# 全てのマスについて
max_count = 0
for x in range(h):
    for y in range(w):
        max_count = max(max_count, bfs(x, y))

print(max_count)