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:
class Grid:
    def __init__(self, H, W, grid, road_wall=(".", "#"), destroy=False):
        self.road, self.wall = road_wall
        self.H = H
        self.W = W
        self.destroy = destroy
        self.grid = grid
        self.parent = [[(-1,-1)] * self.W for _ in range(self.H)]
        self.move = [(1, 0), (-1, 0), (0, 1), (0, -1)]     # 動ける場所の候補

    def bfs(self, start=(0,0), goal=(-1,-1), time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: （ループがあっても）最短距離。存在しなければ -1
        """
        if not save:
            self.parent = [[-1] * self.W for _ in range(self.H)]
        p, t = start, time
        self.parent[p[0]][p[1]] = (-2,-2)
        next_set = deque([(p, t)])

        while next_set:
            p, t = next_set.popleft()
            h, w = p
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         # 壁があったら進まない
                    continue
                if self.parent[q[0]][q[1]] != (-1, -1):
                    continue
                #### (debug code) ######
                # debug(start, goal, q, t)
                ########################
                if q == goal:
                    return t + 1
                self.parent[q[0]][q[1]] = p
                next_set.append((q, t + 1))
        return -1

    def connection_counter(self):
        """
        :return: 連結成分の個数。有効グラフではあまり意味がない。
        """
        cnt = 0
        self.parent = [[(-1,-1)] * self.W for _ in range(self.H)]
        for h in range(self.H):
            for w in range(self.W):
                if self.parent[h][w] == (-1, -1):
                    cnt += 1
                    self.bfs(start=(h,w), save=True)
        return cnt

    def distance_list(self, start=(0,0), save=False):
        """
        :param start: スタート地点
        :return: スタート地点から各点への距離のリスト
        """
        dist = [[-1] * self.W for _ in range(self.H)]
        if not save:
            self.parent = [[(-1, -1)] * self.W for _ in range(self.H)]
        p, t = start, 0
        self.parent[p[0]][p[1]] = (-2, -2)
        dist[p[0]][p[1]] = 0
        next_set = deque([(p, t)])

        while next_set:
            p, t = next_set.popleft()
            h, w = p
            for dh, dw in self.move:
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         # 壁があったら進まない
                    continue
                if self.parent[q[0]][q[1]] != (-1, -1):
                    continue
                dist[q[0]][q[1]] = t + 1
                self.parent[q[0]][q[1]] = p
                next_set.append((q, t + 1))
        return dist

    def most_distant_point(self, start=(0, 0), save=False):
        res = (start, 0)
        temp = 0
        dist = self.distance_list(start, save=save)
        for h in range(self.H):
            for w in range(self.W):
                if dist[h][w] > temp:
                    temp = dist[h][w]
                    res = ((h, w), temp)
        return res

    def diameter(self, start=(0,0), save=False):
        """
        :return:　木の直系（最も離れた二頂点間の距離）を返す
        """
        p = self.most_distant_point(start, save=save)
        res = self.most_distant_point(start=p[0], save=save)
        return res[1]

    def diameter2(self, save=False):
        """
        :return:　連結ではない時に、最大の直系を返す
        """
        res = 0
        for h in range(self.H):
            for w in range(self.W):
                if self.grid[h][w] == self.road and self.parent[h][w] == (-1, -1):
                    temp = self.diameter(start=(h, w), save=save)
                    if temp > res:
                        res = temp
        return res

    def dfs(self, start=(0, 0), goal=(-1, -1), time=0, save=False):
        """
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: ゴール地点までの距離。存在しなければ -1。ループがある時は最短距離とは限らないため注意。
        """

        if not save:
            self.parent = [[(-1, -1)] * self.W for _ in range(self.H)]
        move2 = [[marshal.loads(marshal.dumps(self.move)) for _ in range(self.W)] for _ in range(self.H)]

        p, t = start, time
        self.parent[p[0]][p[1]] = (-2, -2)
        while True:
            if move2[p]:
                dh, dw = move2[p].pop()
                q = (h + dh, w + dw)
                if q[0] < 0 or q[0] >= self.H or q[1] < 0 or q[1] >= self.W:
                    continue
                if self.grid[q[0]][q[1]] == self.wall:         # 壁があったら進まない
                    continue
                if q == self.parent[p[0]][p[1]]:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if self.parent[q[0]][q[1]] != (-1, -1):
                    """ サイクルで同一点を訪れた時の処理 """
                    """"""""""""""""""""
                    continue
                #### (debug code) ######
                # debug(start, goal, q, t)
                ########################
                if q == goal:
                    """ ゴール時の処理"""
                    return t + 1
                    """"""""""""""""""""
                """ p から q への引継ぎ"""
                """"""""""""""""""""
                self.parent[q[0]][q[1]] = p
                p, t = q, t + 1
            else:
                """ p から進める点がもう無い時の点 p における処理 """
                """"""""""""""""""""
                if p == start and t == time:
                    break
                p, t = self.parent[p[0]][p[1]], t-1
                """ 点 p から親ノードに戻ってきた時の親ノードにおける処理 """
                """"""""""""""""""""
        return -1



    def debug(self, start, goal, p, t):
        player = p
        debug_grid = list(list(self.grid[h]) for h in range(self.H))
        if start != (None, None):
            debug_grid[start[0]][start[1]] = "S"
        if goal != (None, None):
            debug_grid[goal[0]][goal[1]] = "G"
        debug_grid[player[0]][player[1]] = "P"
        print("~~~~~~~~~ t = " + str(t + 1) + "  ~~~~~~~~")
        for debug_h in range(self.H):
            print("".join(str(debug_grid[debug_h][debug_w]) for debug_w in range(self.W)))

############################################################################################

from collections import deque
import sys
import marshal
input = sys.stdin.readline



road_wall = (".", "#")                         # (進行可能を意味する記号, 進行不可を意味する記号)

H, W = map(int,input().split())                # 左上は(h,w)=(0,0)、右下は(h,w)=(H-1,W-1)

grid = []
for h in range(H):
    grid.append(input().rstrip())                

g = Grid(H, W, grid, road_wall, destroy=False)

print(g.diameter2())

Submission status: Wrong Answer

Solution code:
# D - Maze Master
# https://atcoder.jp/contests/abc151/tasks/abc151_d
from collections import deque


def main():
    height, width = [int(num) for num in input().split()]
    maze = [input() for _ in range(height)]

    ans = 0
    next_to = ((0, 1), (1, 0), (0, -1), (-1, 0))

    for start_x in range(height):
        for start_y in range(width):
            if maze[start_x][start_y] == '#':
                continue
            queue = deque()
            queue.append((start_x, start_y))
            reached = [[-1] * width for _ in range(height)]
            reached[start_x][start_y] = 0

            while queue:
                now_x, now_y = queue.pop()
                for move_x, move_y in next_to:
                    adj_x, adj_y = now_x + move_x, now_y + move_y
                    # Python は index = -1 が通ってしまうことに注意。
                    # except IndexError では回避できない。
                    if not 0 <= adj_x < height:
                        continue
                    if not 0 <= adj_y < width:
                        continue
                    if maze[adj_x][adj_y] == '#':
                        continue
                    if reached[adj_x][adj_y] != -1:
                        continue
                    queue.append((adj_x, adj_y))
                    reached[adj_x][adj_y] = reached[now_x][now_y] + 1
            most_distant = max(max(row) for row in reached)
            ans = max(most_distant, ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# D - Maze Master
# https://atcoder.jp/contests/abc151/tasks/abc151_d
from collections import deque


def main():
    height, width = [int(num) for num in input().split()]
    maze = [input() for _ in range(height)]

    ans = 0
    next_to = ((0, 1), (1, 0), (0, -1), (-1, 0))

    for start_x in range(height):
        for start_y in range(width):
            if maze[start_x][start_y] == '#':
                continue
            queue = deque()
            queue.append((start_x, start_y))
            reached = [[-1] * width for _ in range(height)]
            reached[start_x][start_y] = 0

            while queue:
                now_x, now_y = queue.pop()
                for move_x, move_y in next_to:
                    adj_x, adj_y = now_x + move_x, now_y + move_y
                    # Python は index = -1 が通ってしまうことに注意。
                    # except IndexError では回避できない。
                    if not 0 <= adj_x < height:
                        continue
                    if not 0 <= adj_y < width:
                        continue
                    if maze[adj_x][adj_y] == '#':
                        continue
                    if reached[adj_x][adj_y] != -1:
                        continue
                    queue.append((adj_x, adj_y))
                    reached[adj_x][adj_y] = reached[now_x][now_y] + 1
            most_distant = max(max(row) for row in reached)
            print(most_distant, 'start', start_x, start_y, reached)
            ans = max(most_distant, ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
# D - Maze Master
# https://atcoder.jp/contests/abc151/tasks/abc151_d
from collections import deque


def main():
    height, width = [int(num) for num in input().split()]
    maze = [input() for _ in range(height)]

    ans = 0
    next_to = ((0, 1), (1, 0), (0, -1), (-1, 0))

    for start_x in range(height):
        for start_y in range(width):
            if maze[start_x][start_y] == '#':
                continue
            queue = deque()
            queue.append((start_x, start_y))
            reached = [[-1] * width for _ in range(height)]
            reached[start_x][start_y] = 0

            while queue:
                now_x, now_y = queue.popleft()
                for move_x, move_y in next_to:
                    adj_x, adj_y = now_x + move_x, now_y + move_y
                    try:
                        if maze[adj_x][adj_y] == '#':
                            continue
                        if reached[adj_x][adj_y] != -1:
                            continue
                    except IndexError:
                        continue
                    queue.append((adj_x, adj_y))
                    reached[adj_x][adj_y] = reached[now_x][now_y] + 1
            most_distant = max(max(row) for row in reached)
            ans = max(most_distant, ans)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from queue import Queue
import copy

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

f = [["#"] * (w + 2)] + \
    [list("#" + input() + "#") for i in range(h)] + \
    [["#"] * (w + 2)]
dxy = [(0,1), (0,-1), (1,0), (-1,0)]

d = [[0]*(w+2) for i in range(h+2)]
for iy in range(h+2):
    for ix in range(w+2):
        if f[iy][ix] == '#':
            d[iy][ix] = 1000

ans = 0
for sy in range(h+2):
    for sx in range(w+2):
        if f[sy][sx] == '#':
            continue
        dist = copy.deepcopy(d)
        cnt = 0
        cnt_max = 0
        q = Queue()
        q.put([sy, sx])
        dist[sy][sx] = 0
        while q.qsize():
            y, x = q.get()
            cnt = dist[y][x]
            
            # print(sx, sy, x, y)
            cnt_max = max(cnt_max, cnt)
            for dy, dx in dxy:
                ny, nx = y + dy, x + dx
                if dist[ny][nx] == 1000:
                    continue
                if dist[ny][nx] == 0:
                    q.put([ny, nx])
                    dist[ny][nx] = cnt + 1
        # print(sx, sy, x, y, cnt)
        ans = max(ans, cnt_max)
print(ans)

Submission status: Wrong Answer

Solution code:
from queue import Queue
import copy

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

f = [["#"] * (w + 2)] + \
    [list("#" + input() + "#") for i in range(h)] + \
    [["#"] * (w + 2)]
dxy = [(0,1), (0,-1), (1,0), (-1,0)]

d = [[0]*(w+2) for i in range(h+2)]
for iy in range(h+2):
    for ix in range(w+2):
        if f[iy][ix] == '#':
            d[iy][ix] = 1000

ans = 0
for sy in range(1, h+1):
    for sx in range(1, w+1):
        if f[sy][sx] == '#':
            continue
        dist = copy.deepcopy(d)
        cnt = 0
        cnt_max = 0
        q = Queue()
        q.put([sy, sx])
        dist[sy][sx] = 0
        while q.qsize():
            y, x = q.get()
            cnt = dist[y][x]
            
            # print(sx, sy, x, y)
            cnt_max = max(cnt_max, cnt)
            for dy, dx in dxy:
                ny, nx = y + dy, x + dx
                if dist[ny][nx] == 1000:
                    continue
                if dist[ny][nx] == 0:
                    q.put([ny, nx])
                    dist[ny][nx] = cnt + 1
        ans = max(ans, cnt_max)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

def bfs(start, goal):
    queue = deque([start])
    visited = [[0] * w for u in range(h)]

    while  len(queue) > 0:
        now_loc = queue.popleft()
        cx = now_loc[0]
        cy = now_loc[1]
        for d in [[1,0],[-1,0],[0,1],[0,-1]]:
            #nx, nyは次の位置
            #cx, cyは現在の位置
            nx = cx + d[0]
            ny = cy + d[1]

            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and visited[nx][ny] == 0:
                visited[nx][ny] = visited[cx][cy] + 1
                queue.append([nx, ny])

        if visited[goal[0]][goal[1]] != 0:
            return visited[goal[0]][goal[1]]

    return 0

step = []
for i in range(h):
    for j in range(w):
        if maze[i][j] == "#":
            continue
        start = [i, j]
        for s in range(h):
            for t in range(w):
                if maze[s][t] == "#":
                    continue
                goal = [s,t]

                step.append(bfs(start, goal))

print(step)
ans = max(step)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

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

def bfs(start, goal):
    queue = deque([start])
    visited = [[0] * w for u in range(h)]

    while  len(queue) > 0:
        now_loc = queue.popleft()
        cx = now_loc[0]
        cy = now_loc[1]
        for d in [[1,0],[-1,0],[0,1],[0,-1]]:
            #nx, nyは次の位置
            #cx, cyは現在の位置
            nx = cx + d[0]
            ny = cy + d[1]

            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and visited[nx][ny] == 0:
                visited[nx][ny] = visited[cx][cy] + 1
                queue.append([nx, ny])

        if visited[goal[0]][goal[1]] != 0:
            return visited[goal[0]][goal[1]]

    return 0

step = []
for i in range(h):
    for j in range(w):
        start = [i, j]

        for s in range(h):
            for t in range(w):
                goal = [s,t]

                step.append(bfs(start, goal))

print(step)
ans = max(step)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque

def main():
    h, w = map(int, input().split())
    maze = [input() for i in range(h)]
    # 行ったかどうかのフラグ
    visited = [[-1]*w for j in range(h)]
    sg = []
    for i in range(h):
        for j in range(w):
            if maze[i][j] == '.':
                sy = i
                sx = j
                for k in range(h):
                    for l in range(w):
                        if maze[i][j] == '.' and (k != i and l != j):
                            gy = k
                            gx = l
                            sg.append([sy, sx, gy, gx])

    # 移動パターン
    mv = [[1, 0], [-1, 0], [0, 1], [0, -1]]
    ans = 0
    #for sy, sx, gy, gx in [[0, 0, h-1, w-1]]:
    for sy, sx, gy, gx in sg:
        visited = [[-1]*w for j in range(h)]
        q = deque([[sy, sx]])
        visited[sy][sx] = 0 
        while q:
            y, x = q.popleft()
            if y == gy and x == gx:
                ans = max(ans, visited[y][x])
                break
            for i, j in mv:
                if (0 <= y + i < h) and (0 <= x + j < w):  
                    ny = y+i
                    nx = x+j
                    if visited[ny][nx] != -1:
                        continue
                    if maze[ny][nx] == '.':
                        visited[ny][nx] = visited[y][x] + 1 
                        q.append([ny, nx])
                else:
                    continue
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
import sys
sys.setrecursionlimit(10**7)

H,W = map(int,input().split())
S = [input().rstrip() for _ in range(H)]
ans = 0
for hi in range(H):
    for wi in range(W):
        flag = 0
        if S[hi][wi] =='.':
            flag = 1
            tmp = [hi,wi]
    
            cost = [[-1]*W for _ in range(H)]
            q = collections.deque([tmp])
            cost[tmp[0]][tmp[1]] = 0
            while q:
                now = q.popleft()
                if 0<= now[0]+1 < H:
                    if cost[now[0]+1][now[1]] == -1 and S[now[0]+1][now[1]] =='.':
                        cost[now[0]+1][now[1]] = cost[now[0]][now[1]] +1
                        q.append([now[0]+1,now[1]])

                if 0<= now[0]-1 < H:
                    if cost[now[0]-1][now[1]] == -1 and S[now[0]-1][now[1]] =='.':
                        cost[now[0]-1][now[1]] = cost[now[0]][now[1]] +1
                        q.append([now[0]-1,now[1]])

                if 0<=now[1]+1 < W:
                    if cost[now[0]][now[1]+1] == -1 and S[now[0]][now[1]+1] =='.':
                        cost[now[0]][now[1]+1] = cost[now[0]][now[1]] +1
                        q.append([now[0],now[1]+1])

                if 0<=now[1]-1 < W:
                    if cost[now[0]][now[1]-1] == -1 and S[now[0]][now[1]-1] =='.':
                        cost[now[0]][now[1]-1] = cost[now[0]][now[1]] +1
                        q.append([now[0],now[1]-1])
    if flag == 1:
        ans = max(ans,cost[now[0]][now[1]])
        
print(ans)

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
import sys
sys.setrecursionlimit(10**7)

H,W = map(int,input().split())
S = [input().rstrip() for _ in range(H)]
flag = 0
#かりスタート点を決める
for hi in range(H):
    for wi in range(W):
        if S[hi][wi] =='.':
            tmp = [hi,wi]
            flag = 1
            break
    if flag ==1:
        break
cost = [[-1]*W for _ in range(H)]
q = collections.deque([tmp])
cost[tmp[0]][tmp[1]] = 0
while q:
    now = q.popleft()
    if 0<= now[0]+1 < H:
        if cost[now[0]+1][now[1]] == -1 and S[now[0]+1][now[1]] =='.':
            cost[now[0]+1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]+1,now[1]])

    if 0<= now[0]-1 < H:
        if cost[now[0]-1][now[1]] == -1 and S[now[0]-1][now[1]] =='.':
            cost[now[0]-1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]-1,now[1]])

    if 0<=now[1]+1 < W:
        if cost[now[0]][now[1]+1] == -1 and S[now[0]][now[1]+1] =='.':
            cost[now[0]][now[1]+1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]+1])

    if 0<=now[1]-1 < W:
        if cost[now[0]][now[1]-1] == -1 and S[now[0]][now[1]-1] =='.':
            cost[now[0]][now[1]-1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]-1])

cost = [[-1]*W for _ in range(H)]
q = collections.deque([now])
cost[now[0]][now[1]] = 0
while q:
    now = q.popleft()
    if 0<= now[0]+1 < H:
        if cost[now[0]+1][now[1]] == -1 and S[now[0]+1][now[1]] =='.':
            cost[now[0]+1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]+1,now[1]])

    if 0<= now[0]-1 < H:
        if cost[now[0]-1][now[1]] == -1 and S[now[0]-1][now[1]] =='.':
            cost[now[0]-1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]-1,now[1]])

    if 0<=now[1]+1 < W:
        if cost[now[0]][now[1]+1] == -1 and S[now[0]][now[1]+1] =='.':
            cost[now[0]][now[1]+1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]+1])

    if 0<=now[1]-1 < W:
        if cost[now[0]][now[1]-1] == -1 and S[now[0]][now[1]-1] =='.':
            cost[now[0]][now[1]-1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]-1])


cost = [[-1]*W for _ in range(H)]
q = collections.deque([now])
cost[now[0]][now[1]] = 0
while q:
    now = q.popleft()
    if 0<= now[0]+1 < H:
        if cost[now[0]+1][now[1]] == -1 and S[now[0]+1][now[1]] =='.':
            cost[now[0]+1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]+1,now[1]])

    if 0<= now[0]-1 < H:
        if cost[now[0]-1][now[1]] == -1 and S[now[0]-1][now[1]] =='.':
            cost[now[0]-1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]-1,now[1]])

    if 0<=now[1]+1 < W:
        if cost[now[0]][now[1]+1] == -1 and S[now[0]][now[1]+1] =='.':
            cost[now[0]][now[1]+1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]+1])

    if 0<=now[1]-1 < W:
        if cost[now[0]][now[1]-1] == -1 and S[now[0]][now[1]-1] =='.':
            cost[now[0]][now[1]-1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]-1])

print(cost[now[0]][now[1]])

Submission status: Wrong Answer

Solution code:
import bisect,collections,copy,heapq,itertools,math,numpy,string
import sys
sys.setrecursionlimit(10**7)

H,W = map(int,input().split())
S = [input().rstrip() for _ in range(H)]
flag = 0
#かりスタート点を決める
for hi in range(H):
    for wi in range(W):
        if S[hi][wi] =='.':
            tmp = [hi,wi]
            flag = 1
            break
    if flag ==1:
        break
cost = [[-1]*W for _ in range(H)]
q = collections.deque([tmp])
cost[tmp[0]][tmp[1]] = 0
while q:
    now = q.popleft()
    if 0<= now[0]+1 < H:
        if cost[now[0]+1][now[1]] == -1 and S[now[0]+1][now[1]] =='.':
            cost[now[0]+1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]+1,now[1]])

    if 0<= now[0]-1 < H:
        if cost[now[0]-1][now[1]] == -1 and S[now[0]-1][now[1]] =='.':
            cost[now[0]-1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]-1,now[1]])

    if 0<=now[1]+1 < W:
        if cost[now[0]][now[1]+1] == -1 and S[now[0]][now[1]+1] =='.':
            cost[now[0]][now[1]+1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]+1])

    if 0<=now[1]-1 < W:
        if cost[now[0]][now[1]-1] == -1 and S[now[0]][now[1]-1] =='.':
            cost[now[0]][now[1]-1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]-1])

cost = [[-1]*W for _ in range(H)]
q = collections.deque([now])
cost[now[0]][now[1]] = 0
while q:
    now = q.popleft()
    if 0<= now[0]+1 < H:
        if cost[now[0]+1][now[1]] == -1 and S[now[0]+1][now[1]] =='.':
            cost[now[0]+1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]+1,now[1]])

    if 0<= now[0]-1 < H:
        if cost[now[0]-1][now[1]] == -1 and S[now[0]-1][now[1]] =='.':
            cost[now[0]-1][now[1]] = cost[now[0]][now[1]] +1
            q.append([now[0]-1,now[1]])

    if 0<=now[1]+1 < W:
        if cost[now[0]][now[1]+1] == -1 and S[now[0]][now[1]+1] =='.':
            cost[now[0]][now[1]+1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]+1])

    if 0<=now[1]-1 < W:
        if cost[now[0]][now[1]-1] == -1 and S[now[0]][now[1]-1] =='.':
            cost[now[0]][now[1]-1] = cost[now[0]][now[1]] +1
            q.append([now[0],now[1]-1])


print(cost[now[0]][now[1]])

Submission status: Wrong Answer

Solution code:
from collections import deque

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

dx = [0, 1, -1, 0]
dy = [1, 0, 0, -1]
           
def bfs(sx, sy):
    q = deque([])
    d = [[-1 for _ in range(W)] for _ in range(H)]
    q.append([sx, sy])
    d[sy][sx] = 0
    
    while(q):
        pop = q.popleft()
        x, y = pop[0], pop[1]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx and nx < W and ny >= 0 and ny < H:
                if s[ny][nx] != "#" and d[ny][nx] == -1:
                    q.append([nx, ny])
                    d[ny][nx] = d[y][x] + 1
    return d

def max_dim2(d):
    ret = 0
    for i in range(len(d)):
        for j in d[i]:
            ret = max(ret, j)
    return ret

ans = 0
for i in range(H):
    for j in range(W):
        ret = bfs(j, i)
        temp = max_dim2(ret)
        ans = max(ans, temp)
print(ans)

Submission status: Wrong Answer

Solution code:
# sr,sc,gr,gcの総当りでTLEした
# goalは各startに対して最も遠い地点とすればよい

def main():
    from collections import deque

    dd = 0, 1, 0, -1

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

    def dist(sr, sc):
        if G[sr][sc] == '#':
            return -1

        memo = [[-1] * W for _ in range(H)]

        dq = deque()
        dq.append((sr, sc, 0))
        while dq:
            r, c, d = dq.popleft()
            nd = d + 1
            for i in range(4):
                nr = r + dd[i]
                nc = c + dd[i ^ 1]
                if not (0 <= nr < H and 0 <= nc < W):
                    continue
                if ~memo[nr][nc]:
                    continue
                if G[nr][nc] == '#':
                    continue
                dq.append((nr, nc, nd))
                memo[nr][nc] = nd

        return d

    ans = 0
    for sr in range(H):
        for sc in range(W):
            ans = max(ans, dist(sr, sc))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

def bfs(s):
    que = deque([s])
    m = [[-1]*w for _ in range(h)]
    sh, sw = s
    m[sh][sw] = 0
    ret = 0
    while que:
        now_h, now_w = que.popleft()
        for dh, dw in [(1,0), (-1,0), (0,-1), (0,1)]:
            nh = now_h + dh
            nw = now_w + dw
            if not (0<=nh<h and 0<=nw<w) or m[nh][nw] != -1 or hw[nh][nw] == '#':
                continue
            m[nh][nw] = m[now_h][now_w] + 1
            que.append((nh,nw))
            ret = max(ret, m[now_h][now_w] + 1)
    return ret

ans = 0
for y in range(h):
    for x in range(w):
        s = (y, x)
        ans = max(bfs(s), ans)

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque

H,W = map(int,input().split())
field = ["#"*(W+2)]
field += ["#"+input()+"#" for _ in range(H)]
field += ["#"*(W+2)]

s = []

for i in range(H+2):
  for j in range(W+2):
    if field[i][j] == ".":
      s = [i,j]
      
q = deque()
q.append(s)
dist = [[10**10]*(W+2) for _ in range(H+2)]
dist[s[0]][s[1]] = 0
d = ((0,1),(0,-1),(1,0),(-1,0))
far = []

while len(q)>0:
  i,j = q.popleft()
  for di,dj in d:
    if field[i+di][j+dj] == "." and dist[i+di][j+dj] == 10**10:
      q.append([i+di,j+dj])
      dist[i+di][j+dj] = dist[i][j]+1
  s = [i,j]

q.append(s)
dist = [[10**10]*(W+2) for _ in range(H+2)]
dist[s[0]][s[1]] = 0

while len(q)>0:
  i,j = q.popleft()
  for di,dj in d:
    if field[i+di][j+dj] == "." and dist[i+di][j+dj] == 10**10:
      q.append([i+di,j+dj])
      dist[i+di][j+dj] = dist[i][j]+1
  res = dist[i][j]
      
print(res)

Submission status: Wrong Answer

Solution code:
import sys
from copy import deepcopy
from itertools import combinations_with_replacement, product
from collections import deque
def input(): return sys.stdin.readline().rstrip()


def main():
    h, w = map(int, input().split())
    s = [list(input()) for i in range(h)]
    ans = 0
    for H, W in product(range(h), range(w)):
        if s[H][W] == '#':
            continue
        s2 = deepcopy(s)
        s2[H][W] = 0
        d = deque()
        d.append([H, W])
        while d:
            Hn,Wn = d.popleft()
            for i, j in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
                try:
                    k = s2[Hn+i][Wn+j]
                except IndexError:
                    pass
                else:
                    if k != '.':
                        continue
                    s2[Hn+i][Wn+j] = s2[Hn][Wn] + 1
                    d.append([Hn+i, Wn+j])
                    if ans < s2[Hn+i][Wn+j]:
                        ans = s2[Hn+i][Wn+j]
        del s2

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
H, W = map(int, input().split())
S = []

for ix in range(H):
    S.append(list(input()))


Dt = [(0,1), (1,0), (-1, 0), (0, -1)]
ans = 0
for x in range(H):
    for y in range(W):

        if S[x][y] == '#':
            continue
        # traverse
        sp = (x, y, 0)
        q = [sp]
        mxp = 0
        DP = [[0 for _ in range(W+1)] for __ in range(H+1)]

        while len(q) != 0:

            x, y, p = q[0]
            q.pop(0)

            if DP[x][y] != 0:
                continue
            else:
                DP[x][y] = 1

            if p > ans:
                ans = p

            for d in Dt:
                nx = x + d[0]
                ny = y + d[1]

                # if nx < 0 or ny < 0 or nx >= H or ny >= W or S[nx][ny] == '#':
                if not (0 <= nx < H) or not (0 <= ny < W) or S[nx][ny] == '#':
                    continue

                q.append((nx, ny, p + 1))

print(ans)