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 sys
from io import StringIO
import unittest
import os
from collections import deque

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    # 数値取得サンプル
    #   1行1項目 n = int(input())
    #   1行2項目 h, w = map(int, input().split())
    #   1行N項目 x = list(map(int, input().split()))
    #   N行1項目 x = [int(input()) for i in range(n)]
    #   N行N項目 x = [list(map(int, input().split())) for i in range(n)]

    # 文字取得サンプル
    #   1行1項目 x = input()
    #   1行1項目(1文字ずつリストに入れる場合) x = list(input())
    h, w = map(int, input().split())
    maze = [list(input()) for i in range(h)]

    start_list = []
    for i_len, i in enumerate(range(h)):
        for j_len, j in enumerate(range(w)):
            route = 4
            # 自分が壁なら対象外
            if maze[i][j] == "#":
                continue

            # 上下端なら-1
            route -= 1 if i_len == 0 else 0
            route -= 1 if i_len + 1 == h else 0
            # 上下が壁なら-1
            route -= 1 if not i_len == 0 and maze[i - 1][j] == "#" else 0
            route -= 1 if not i_len + 1 == h and maze[i + 1][j] == "#" else 0
            # 左右端なら-1
            route -= 1 if j_len == 0 else 0
            route -= 1 if j_len + 1 == w else 0
            # 左右が壁なら-1
            route -= 1 if not j_len == 0 and maze[i][j - 1] == "#" else 0
            route -= 1 if not j_len + 1 == w and maze[i][j + 1] == "#" else 0
            if route <= 2:
                start_list.append((i, j))

    ans = 0
    que = deque()
    for start in start_list:
        que.append(start)
        ed_list = [[0 for i in range(w)] for j in range(h)]

        # BFS開始
        while len(que) is not 0:
            now = que.pop()

            # 各方向に移動
            for i, j in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
                # 処理対象の座標
                target = [now[0] + i, now[1] + j]

                # 処理対象のチェック
                # 外なら何もしない
                if not 0 <= target[0] < h or not 0 <= target[1] < w:
                    continue

                # 距離が設定されているなら何もしない

                if ed_list[target[0]][target[1]] > 0:
                    continue

                # 壁なら何もしない
                if maze[target[0]][target[1]] == "#":
                    continue

                # 処理対象に対する処理
                # キューに追加(先頭に追加するのでappendleft())
                que.appendleft(target)
                # 距離を設定(現在の距離+1)
                ed_list[target[0]][target[1]] = ed_list[now[0]][now[1]] + 1
                ans = max(ans, ed_list[target[0]][target[1]])

    print(ans)


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3 3
...
...
..."""
        output = """4"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """3 5
...#.
.#.#.
.#..."""
        output = """10"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Wrong Answer

Solution code:
import sys
from io import StringIO
import unittest
import os
from collections import deque

# 再帰処理上限(dfs作成時に設定するのが面倒なので限度近い値を組み込む)
sys.setrecursionlimit(999999999)


# 実装を行う関数
def resolve(test_def_name=""):
    # 数値取得サンプル
    #   1行1項目 n = int(input())
    #   1行2項目 h, w = map(int, input().split())
    #   1行N項目 x = list(map(int, input().split()))
    #   N行1項目 x = [int(input()) for i in range(n)]
    #   N行N項目 x = [list(map(int, input().split())) for i in range(n)]

    # 文字取得サンプル
    #   1行1項目 x = input()
    #   1行1項目(1文字ずつリストに入れる場合) x = list(input())
    h, w = map(int, input().split())
    maze = [list(input()) for i in range(h)]

    start_list = []
    for i_len, i in enumerate(range(h)):
        for j_len, j in enumerate(range(w)):
            route = 4
            # 上下端なら-1
            route -= 1 if i_len == 0 else 0
            route -= 1 if i_len + 1 == h else 0
            # 上下が壁なら-1
            route -= 1 if not i_len == 0 and maze[i - 1][j] == "#" else 0
            route -= 1 if not i_len + 1 == h and maze[i + 1][j] == "#" else 0
            # 左右端なら-1
            route -= 1 if j_len == 0 else 0
            route -= 1 if j_len + 1 == w else 0
            # 左右が壁なら-1
            route -= 1 if not j_len == 0 and maze[i][j - 1] == "#" else 0
            route -= 1 if not j_len + 1 == w and maze[i][j + 1] == "#" else 0

            if route <= 2:
                start_list.append((i, j))

    ans = 0
    que = deque()
    for start in start_list:
        que.append(start)
        ed_list = [[0 for i in range(w)] for j in range(h)]

        # BFS開始
        while len(que) is not 0:
            now = que.pop()

            # 各方向に移動
            for i, j in [(1, 0), (0, 1), (0, -1), (-1, 0)]:
                # 処理対象の座標
                target = [now[0] + i, now[1] + j]

                # 処理対象のチェック
                # 外なら何もしない
                if not 0 <= target[0] < h or not 0 <= target[1] < w:
                    continue

                # 距離が設定されているなら何もしない

                if ed_list[target[0]][target[1]] > 0:
                    continue

                # 壁なら何もしない
                if maze[target[0]][target[1]] == "#":
                    continue

                # 処理対象に対する処理
                # キューに追加(先頭に追加するのでappendleft())
                que.appendleft(target)
                # 距離を設定(現在の距離+1)
                ed_list[target[0]][target[1]] = ed_list[now[0]][now[1]] + 1
                ans = max(ans, ed_list[target[0]][target[1]])

    print(ans)


# テストクラス
class TestClass(unittest.TestCase):
    def assertIO(self, assert_input, output):
        stdout, sat_in = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(assert_input)
        resolve(sys._getframe().f_back.f_code.co_name)
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, sat_in
        self.assertEqual(out, output)

    def test_input_1(self):
        test_input = """3 3
...
...
..."""
        output = """4"""
        self.assertIO(test_input, output)

    def test_input_2(self):
        test_input = """3 5
...#.
.#.#.
.#..."""
        output = """10"""
        self.assertIO(test_input, output)

    # 自作テストパターンのひな形(利用時は「tes_t」のアンダーバーを削除すること
    def tes_t_1original_1(self):
        test_input = """データ"""
        output = """データ"""
        self.assertIO(test_input, output)


# 実装orテストの呼び出し
if __name__ == "__main__":
    if os.environ.get("USERNAME") is None:
        # AtCoder提出時の場合
        resolve()

    else:
        # 自PCの場合
        unittest.main()

Submission status: Wrong Answer

Solution code:
# 幅優先探索
from collections import deque
H, W = map(int, input().split())
dif = [(-1, 0), (1, 0), (0, 1), (0, -1)]
Map = [list(input()) for i in range(H)]
visited = [[False for i in range(W)] for j in range(H)]
deq = deque()


def bfs(node):
    nx, ny = node
    deq.append(node)
 
    visited[nx][ny] = True
    distance = [[float("inf") for i in range(W)] for j in range(H)]
    distance[nx][ny] = 0
    while deq:
        x, y = deq.popleft()
        for dx, dy in dif:
            if 0 <= x+dx < H and 0 <= y+dy < W and Map[x+dx][y+dy] == "." and visited[x+dx][y+dy] == False:
                visited[x+dx][y+dy] = True
                distance[x+dx][y+dy] = distance[x][y]+1
                deq.append((x+dx, y+dy))
    return distance

def s_bfs(node):
    nx, ny = node
    deq.append(node)
    Visited = [[False for i in range(W)] for j in range(H)]
    Visited[nx][ny] = True
    distance = [[float("inf") for i in range(W)] for j in range(H)]
    distance[nx][ny] = 0
    while deq:
        x, y = deq.popleft()
        for dx, dy in dif:
            if 0 <= x+dx < H and 0 <= y+dy < W and Map[x+dx][y+dy] == "." and Visited[x+dx][y+dy] == False:
                Visited[x+dx][y+dy] = True
                distance[x+dx][y+dy] = distance[x][y]+1
                deq.append((x+dx, y+dy))
    return distance
ans = 1
roads = deque()
for i in range(H):
    for j in range(W):
        if Map[i][j] == ".":
            roads.append((i, j))
#roads : 通れるところ
while roads:
    x, y = roads.popleft()
    if visited[x][y] == False:
        B = bfs((x, y))
        s = -1
        most_far_distance = 0
        for i in range(H):
            for j in range(W):
                if B[i][j] != float("inf") and B[i][j] >= most_far_distance:
                    s = (i, j)
                    most_far_distance = B[i][j]
        C = s_bfs(s)
        for i in range(H):
            for j in range(W):
                if C[i][j] != float("inf"):
                    ans = max(ans, C[i][j])
print(ans)

Submission status: Wrong Answer

Solution code:
# 幅優先探索
from collections import deque
H, W = map(int, input().split())
dif = [(-1, 0), (1, 0), (0, 1), (0, -1)]
Map = [list(input()) for i in range(H)]
visited = [[False for i in range(W)] for j in range(H)]
deq = deque()


def bfs(node):
    nx, ny = node
    deq.append(node)
 
    visited[nx][ny] = True
    distance = [[float("inf") for i in range(W)] for j in range(H)]
    distance[nx][ny] = 0
    while deq:
        x, y = deq.popleft()
        for dx, dy in dif:
            if 0 <= x+dx < H and 0 <= y+dy < W and Map[x+dx][y+dy] == "." and visited[x+dx][y+dy] == False:
                visited[x+dx][y+dy] = True
                distance[x+dx][y+dy] = distance[x][y]+1
                deq.append((x+dx, y+dy))
    return distance

def s_bfs(node):
    nx, ny = node
    deq.append(node)
    Visited = [[False for i in range(W)] for j in range(H)]
    Visited[nx][ny] = True
    distance = [[float("inf") for i in range(W)] for j in range(H)]
    distance[nx][ny] = 0
    while deq:
        x, y = deq.popleft()
        for dx, dy in dif:
            if 0 <= x+dx < H and 0 <= y+dy < W and Map[x+dx][y+dy] == "." and Visited[x+dx][y+dy] == False:
                Visited[x+dx][y+dy] = True
                distance[x+dx][y+dy] = distance[x][y]+1
                deq.append((x+dx, y+dy))
    return distance
ans = 0
roads = deque()
for i in range(H):
    for j in range(W):
        if Map[i][j] == ".":
            roads.append((i, j))
#roads : 通れるところ
while roads:
    x, y = roads.popleft()
    if visited[x][y] == False:
        B = bfs((x, y))
        s = -1
        most_far_distance = 0
        for i in range(H):
            for j in range(W):
                if B[i][j] != float("inf") and B[i][j] > most_far_distance:
                    s = (i, j)
                    most_far_distance = B[i][j]
        C = s_bfs(s)
        for i in range(H):
            for j in range(W):
                if C[i][j] != float("inf"):
                    ans = max(ans, C[i][j])
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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


def solve_maze(s):
    bias = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    inf = 10 ** 9

    d = [[inf] * W for _ in range(H)]
    d[s[0]][s[1]] = 0

    q = deque()
    q.append(s)
    while q:
        u, v = q.popleft()
        for i, j in bias:
            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 i in range(H):
        for j in range(W):
            if d[i][j] < inf:
                res = max(res, d[i][j])
                
    return res


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

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

def solve_maze(s, t):
    bias = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    inf = 10 ** 9

    d = [[inf] * W for _ in range(H)]
    d[s[0]][s[1]] = 0

    q = deque()
    q.append(s)
    while q:
        u, v = q.pop()
        for i, j in bias:
            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))

    if d[t[0]][t[1]] < inf:
        return d[t[0]][t[1]]
    return -1


ans = 0
for i in range(H):
    for j in range(W):
        for x in range(H):
            for y in range(W):
                ans = max(ans, solve_maze((i, j), (x, y)))

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

def solve_maze(s, t):
    bias = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    inf = 10 ** 9

    d = [[inf] * W for _ in range(H)]
    d[s[0]][s[1]] = 0

    q = deque()
    q.append(s)
    while q:
        u, v = q.popleft()
        for i, j in bias:
            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))

    if d[t[0]][t[1]] < inf:
        return d[t[0]][t[1]]
    return -1


ans = 0
for i in range(H):
    for j in range(W):
        for x in range(H):
            for y in range(W):
                ans = max(ans, solve_maze((i, j), (x, y)))

print(ans)

Submission status: Wrong Answer

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

for i in range(H):
    for j in range(W):
        c=0
        sy=i
        sx=j
        route=deque([(sy,sx,0)])
        while route:
            a,b,n=route.popleft()
            if 0<=a<=H-1 and 0<=b<=W-1:
                if S[a][b]=='.':
                    S[a][b]='#'
                    route.append((a+1,b,n+1))
                    route.append((a-1,b,n+1))
                    route.append((a,b+1,n+1))
                    route.append((a,b-1,n+1))
        ans.append(n-1)

print(max(ans))

Submission status: Wrong Answer

Solution code:
import queue

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

def bfs(dist, i, j):
    q = queue.Queue()
    q.put((i, j, 0))
    while not q.empty():
        i, j, c = q.get()
        # print(i, j, c, dist)
        if i != 0 and dist[i-1][j] == 0:
            dist[i-1][j] = c+1
            q.put((i-1, j, c+1))
        if j != 0 and dist[i][j-1] == 0:
            dist[i][j-1] = c+1
            q.put((i, j-1, c+1))
        if i != h-1 and dist[i+1][j] == 0:
            dist[i+1][j] = c+1
            q.put((i+1, j, c+1))
        if j != w-1 and dist[i][j+1] == 0:
            dist[i][j+1] = c+1
            q.put((i, j+1, c+1))
    return dist

ans = 0
for i in range(h):
    for j in range(w):
        if maze[i][j] == '.':
            dist = [[(maze[y][x] == '#')*-1 for x in range(w)] for y in range(h)]
            dist[i][j] = -1
            dist = bfs(dist, i, j)
            tmp_ans = max(max(dist))
            if ans < tmp_ans:
                ans = tmp_ans
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque

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

maze_o = [0]*h
for i in range(h):
    maze_o[i] = list(input())

dy = [1, -1, 0, 0]
dx = [0, 0, 1, -1]
#すべての "." をスタート位置にする
ans = 0
for y in range(h):
    for x in range(w):
        if maze_o[y][x] == "#":
            continue
        maze = copy.deepcopy(maze_o)
        distance = deque([0])
        rireki = deque([])
        stack = deque([(y, x)])
        while stack:
            yy, xx = stack.popleft()
            d = distance.popleft()
            rireki.append(d)
            for dxi,dyi in zip(dx, dy):
                if not (0<=dxi+xx<w and 0<=dyi+yy<h):
                    continue
                if maze[dyi+yy][dxi+xx] == "#":
                    continue
                distance.append(d+1)
                stack.append((dyi+yy,dxi+xx))
                maze[dyi+yy][dxi+xx] = "#"
        ans = max(ans, max(rireki))
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque

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

maze_o = [0]*h
for i in range(h):
    maze_o[i] = list(input())

dy = [1, -1, 0, 0]
dx = [0, 0, 1, -1]
#すべての "." をスタート位置にする
ans = 0
for y in range(h):
    for x in range(w):
        if maze_o[y][x] == "#":
            continue
        maze = copy.deepcopy(maze_o)
        distance = deque([0])
        rireki = deque([])
        stack = deque([(y, x)])
        while stack:
            yy, xx = stack.pop()
            d = distance.popleft()
            rireki.append(d)
            for dxi,dyi in zip(dx, dy):
                if not (0<=dxi+xx<w and 0<=dyi+yy<h):
                    continue
                if maze[dyi+yy][dxi+xx] == "#":
                    continue
                distance.append(d+1)
                stack.append((dyi+yy,dxi+xx))
                maze[yy][xx] = "#"
        ans = max(ans, max(rireki))
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque

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

maze_o = [0]*h
for i in range(h):
    maze_o[i] = list(input())

dy = [1, -1, 0, 0]
dx = [0, 0, 1, -1]
#すべての "." をスタート位置にする
ans = 0
for y in range(h):
    for x in range(w):
        if maze_o[y][x] == "#":
            continue
        maze = copy.deepcopy(maze_o)
        distance = deque([0])
        rireki = deque([])
        stack = deque([(y, x)])
        while stack:
            yy, xx = stack.pop()
            d = distance.popleft()
            for dxi,dyi in zip(dx, dy):
                if not (0<=dxi+xx<w and 0<=dyi+yy<h):
                    continue
                if maze[dyi+yy][dxi+xx] == "#":
                    continue
                distance.append(d+1)
                rireki.append(d+1)
                stack.append((dyi+yy,dxi+xx))
                maze[yy][xx] = "#"
        ans = max(ans, max(rireki))
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque

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

maze_o = [0]*h
for i in range(h):
    maze_o[i] = list(input())

dy = [1, -1, 0, 0]
dx = [0, 0, 1, -1]
#すべての "." をスタート位置にする
ans = 0
for y in range(h):
    for x in range(w):
        if maze_o[y][x] == "#":
            continue
        maze = copy.deepcopy(maze_o)
        distance = deque([0])
        rireki = deque([0])
        stack = deque([(y, x)])
        while stack:
            yy, xx = stack.pop()
            d = distance.popleft()
            for dxi,dyi in zip(dx, dy):
                if not (0<=dxi+xx<w and 0<=dyi+yy<h):
                    continue
                if maze[dyi+yy][dxi+xx] == "#":
                    continue
                distance.append(d+1)
                rireki.append(d+1)
                stack.append((dyi+yy,dxi+xx))
                maze[dyi+yy][dxi+xx] = "#"
        ans = max(ans, max(rireki))
print(ans)

Submission status: Wrong Answer

Solution code:
import copy
from collections import deque

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

maze_o = [0]*h
for i in range(h):
    maze_o[i] = list(input())

dy = [1, -1, 0, 0]
dx = [0, 0, 1, -1]
#すべての "." をスタート位置にする
ans = 0
for y in range(h):
    for x in range(w):
        if maze_o[y][x] == "#":
            continue
        maze = copy.deepcopy(maze_o)
        distance = deque([0])
        rireki = deque([0])
        stack = deque([(y, x)])
        while stack:
            yy, xx = stack.pop()
            d = distance.popleft()
            for dxi,dyi in zip(dx, dy):
                if not (0<=dxi+xx<w and 0<=dyi+yy<h):
                    continue
                if maze[dyi+yy][dxi+xx] == "#":
                    continue
                distance.append(d+1)
                rireki.append(d+1)
                stack.append((dyi+yy,dxi+xx))
                maze[yy][xx] = "#"
        ans = max(ans, max(rireki))
print(ans)

Submission status: Wrong Answer

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

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

maze_o = [0]*h
for i in range(h):
    maze_o[i] = list(input())

dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
#すべての "." をスタート位置にする
ans = 0
for y in range(h):
    for x in range(w):
        if maze_o[y][x] == "#":
            continue
        maze = copy.deepcopy(maze_o)
        distance = np.array([[0]*w for _ in range(h)])
        stack = deque([(y, x)])
        while stack:
            yy, xx = stack.pop()
            maze[yy][xx] = "#"
            for dxi, dyi in zip(dx, dy):
                if not (0<=xx+dxi<w and 0<=yy+dyi<h):
                    continue
                if maze[dyi+yy][dxi+xx] == "#":
                    continue
                if distance[dyi+yy][dxi+xx] != 0:
                    distance[dyi+yy][dxi+xx] = min(distance[dyi+yy][dxi+xx], distance[yy][xx] + 1)
                else:
                    distance[dyi+yy][dxi+xx] = distance[yy][xx] + 1
                stack.append((dyi+yy, dxi+xx))
        ans = max(ans, np.max(distance))
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque 
from copy import deepcopy
# 初期入力
import sys
input = sys.stdin.readline
H,W = (int(i) for i in input().split())
map_initial =[["#"]*(W+2) for i in range(H+2)] #周囲を壁にするため＋２
for h in range(1,H+1):
    map_initial[h] =["#"] +list(input().strip()) +["#"]

def BSF(x,y):
    dist =0
    map =deepcopy(map_initial)
    if map[x][y] =="#":
        return dist 
    dq =deque()
    dq.append((x,y))
    dq_sarch =deque()
    while len(dq) >0:
        h,w =dq.popleft()
        map[h][w] ="#" #通り済を壁にする
        if map[h+1][w]==".":
            dq_sarch.append((h+1,w))
        if map[h-1][w]==".":
            dq_sarch.append((h-1,w))
        if map[h][w+1]==".":
            dq_sarch.append((h,w+1))
        if map[h][w-1]==".":
            dq_sarch.append((h,w-1))
        if len(dq)==0:
            dq =deepcopy(dq_sarch)
            dq_sarch.clear()
            dist +=1
        #print(h,w,dist,end="\t")
    return dist-1

#スタート位置を全探索し、最長距離を探す
dist_all =[]
for i in range(1,H+1):
    for j in range(1,W+1):
        dist_all.append(BSF(i,j) )
        #print((i,j))
print(dist_all)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
#外壁として障害物置く
H += 2
W += 2
P = [[] for _ in range(H*W)]

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

for y in range(1, H-1):
  for x in range(1, W-1):
    for z in move:
      P[x+W*y].append(x+z[0]+W*(y+z[1]))

for y in range(H-2):
  L = input()
  for x, s in enumerate(L):
    if s == "#":
      P[x+1 + W*(y+1)] = []

def bfs(x, y):
    s = x + W*y
    d = [-1] * (H*W)
    d[s] = 0
    p_old = [s]
    cnt = 1
    m_cnt = 0
    last = 1
    #print(d, p_old)
    while p_old:
      p_new = []
      for i in p_old:
        for j in P[i]:
          if d[j] == -1:
            d[j] = cnt
            m_cnt = max(m_cnt, cnt)
            p_new.append(j)
          if all(d[j] == -1 for j in P[i]):
          	last -= 1
      p_old = p_new
      cnt += 1
      #print(d, p_old)
    return m_cnt - last

#print(P)
#print(bfs(1, 1))

ans = 0

for y in range(1, H-1):
  for x in range(1, W-1):
    ans = max(ans, bfs(x, y))

print(ans)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
#外壁として障害物置く
H += 2
W += 2
P = [[] for _ in range(H*W)]

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

for y in range(1, H-1):
  for x in range(1, W-1):
    for z in move:
      P[x+W*y].append(x+z[0]+W*(y+z[1]))

for y in range(H-2):
  L = input()
  for x, s in enumerate(L):
    if s == "#":
      P[x+1 + W*(y+1)] = []

def bfs(x, y):
    s = x + W*y
    d = [-1] * (H*W)
    d[s] = 0
    p_old = [s]
    cnt = 1
    m_cnt = 0
    #print(d, p_old)
    while p_old:
      p_new = []
      for i in p_old:
        for j in P[i]:
          if d[j] == -1:
            d[j] = cnt
            m_cnt = max(m_cnt, cnt)
            p_new.append(j)
      p_old = p_new
      cnt += 1
      #print(d, p_old)
    return m_cnt

#print(P)
#print(bfs(1, 1))

ans = 0

for y in range(1, H-1):
  for x in range(1, W-1):
    ans = max(ans, bfs(x, y))

print(ans)

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
#外壁として障害物置く
H += 2
W += 2
P = [[] for _ in range(H*W)]

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

for y in range(1, H-1):
  for x in range(1, W-1):
    for z in move:
      P[x+W*y].append(x+z[0]+W*(y+z[1]))

for y in range(H-2):
  L = input()
  for x, s in enumerate(L):
    if s == "#":
      P[x+1 + W*(y+1)] = []

def bfs(x, y):
    s = x + W*y
    d = [-1] * (H*W)
    d[s] = 0
    p_old = [s]
    cnt = 1
    m_cnt = 0
    #print(d, p_old)
    while p_old:
      p_new = []
      for i in p_old:
        for j in P[i]:
          if d[j] == -1:
            d[j] = cnt
            m_cnt = max(m_cnt, cnt)
            p_new.append(j)
      p_old = p_new
      cnt += 1
      #print(d, p_old)
    return m_cnt - 1

ans = 0

for y in range(1, H-1):
  for x in range(1, W-1):
    ans = max(ans, bfs(x, y))

print(ans)

Submission status: Wrong Answer

Solution code:
from networkx import*
_,*s=open(i:=0)
g=[]
for t in s:
 i+=1;j=0
 for u in t:g+=[(k:=i*20+j,k+20)]*(u>'#'<(s+['#'*k])[i][j]);j+=1;g+=[(k,k+1)]*(u>'#'<t[j])
print('!?',max(t[i]for _,t in shortest_path_length(Graph(g))for i in t))