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: Accepted

Solution code:
import copy
from collections import deque


def bfs(s, f):
    f[s[0]][s[1]] = 0
    moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

    q = deque([s])
    while q:
        c = q.popleft()
        for m in moves:
            my, mx = c[0] + m[0], c[1] + m[1]

            if f[my][mx] == ".":
                f[my][mx] = f[c[0]][c[1]] + 1
                q.append([my, mx])
                goal = [my, mx]
            else:
                continue

    return goal, f[goal[0]][goal[1]]


def main():
    H, W = map(int, input().split())
    field = []

    for h in range(H + 2):
        field.append(["#"] * (W + 2))
        if 1 <= h <= (H):
            field[h][1:-1] = list(map(str, input().rstrip()))

    ans = 0
    for y in range(1, H + 1):
        for x in range(1, W + 1):
            if field[y][x] == ".":
                goal, tmp_ans = bfs([y, x], copy.deepcopy(field))
                ans = max(ans, tmp_ans)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import copy
from collections import deque


def bfs(s, f):
    f[s[0]][s[1]] = 0
    moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

    q = deque([s])
    while q:
        c = q.popleft()
        for m in moves:
            my, mx = c[0] + m[0], c[1] + m[1]

            if f[my][mx] == ".":
                f[my][mx] = f[c[0]][c[1]] + 1
                q.append([my, mx])
            else:
                continue

    f = sum(f, [])
    return max([x for x in f if type(x) == int])


def main():
    H, W = map(int, input().split())
    field = []

    for h in range(H + 2):
        field.append(["#"] * (W + 2))
        if 1 <= h <= (H):
            field[h][1:-1] = list(map(str, input().rstrip()))

    ans = 0
    for y in range(1, H + 1):
        for x in range(1, W + 1):
            if field[y][x] == ".":
                ans = max(ans, bfs([y, x], copy.deepcopy(field)))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import copy
from collections import deque


def bfs(s, f):
    f[s[0]][s[1]] = 0
    moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

    q = deque([s])
    while q:
        c = q.popleft()
        for m in moves:
            my, mx = c[0] + m[0], c[1] + m[1]

            if f[my][mx] == ".":
                f[my][mx] = f[c[0]][c[1]] + 1
                q.append([my, mx])
            else:
                continue

    f = sum(f, [])
    return max([x for x in f if type(x) == int])


def main():
    H, W = map(int, input().split())
    field_s = []

    for h in range(H + 2):
        field_s.append(["#"] * (W + 2))
        if 1 <= h <= (H):
            field_s[h][1:-1] = list(map(str, input().rstrip()))

    ans = 0
    for y in range(1, H + 1):
        for x in range(1, W + 1):
            if field_s[y][x] == ".":
                field = copy.deepcopy(field_s)
                ans = max(ans, bfs([y, x], field))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import copy
from collections import deque


def bfs(s, f):
    f[s[0]][s[1]] = 0
    moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

    q = deque([s])
    while q:
        c = q.popleft()
        for m in moves:
            my, mx = c[0] + m[0], c[1] + m[1]

            if f[my][mx] == ".":
                f[my][mx] = f[c[0]][c[1]] + 1
                q.append([my, mx])
            else:
                continue

    f = sum(f, [])
    return max([x for x in f if type(x) == int])


def main():
    H, W = map(int, input().split())
    field_s = []

    for h in range(H + 2):
        field_s.append(["#"] * (W + 2))
        if 1 <= h <= (H):
            field_s[h][1:-1] = list(map(str, input().rstrip()))

    start = []
    for y in range(1, H + 1):
        for x in range(1, W + 1):
            if field_s[y][x] == ".":
                start.append([y, x])

    ans = 0
    for s in start:
        field = copy.deepcopy(field_s)
        ans = max(ans, bfs(s, field))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import copy
from collections import deque

H, W = map(int, input().split())
field_s = []

# フィールドを作る
for h in range(H + 2):
    field_s.append(["#"] * (W + 2))
    if 1 <= h <= (H):
        field_s[h][1:-1] = list(map(str, input().rstrip()))

#　動き方のセットを準備
moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

# スタート座標を取得
start = []
for y in range(1, H + 1):
    for x in range(1, W + 1):
        if field_s[y][x] == ".":
            start.append([y, x])

# 答え
ans = 0

for s in start:

    # fieldの初期化
    field = copy.deepcopy(field_s)

    # startをキューに追加
    que = deque([s])

    # startの距離は0に
    field[s[0]][s[1]] = 0

    # キューに何かがある限り探索を続ける
    while que:
        c = que.popleft()

        # 今の距離
        dist = field[c[0]][c[1]]

        # 動いた先が「.」なら、距離を記録してキューに追加
        for m in moves:
            my = c[0] + m[0]
            mx = c[1] + m[1]

            if field[my][mx] == ".":
                field[my][mx] = dist + 1
                que.append([my, mx])
            else:
                continue

    # キューを消化したら最大値を取り出す
    field = sum(field, [])
    ans = max(ans, max([x for x in field if type(x) == int]))

print(ans)

Submission status: Accepted

Solution code:
import copy
from collections import deque

H, W = map(int, input().split())
field_s = []

# フィールドを作る
for h in range(H + 2):
    field_s.append(["#"] * (W + 2))
    if 1 <= h <= (H):
        field_s[h][1:-1] = list(map(str, input().rstrip()))

#　動き方のセットを準備
moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]

# スタート座標を取得
start = []
for y in range(1, H + 1):
    for x in range(1, W + 1):
        if field_s[y][x] == ".":
            start.append([y, x])

# 答え
ans = 0

for s in start:

    # fieldの初期化
    field = copy.deepcopy(field_s)

    # startをキューに追加
    que = deque([s])

    # startの距離は0に
    field[s[0]][s[1]] = 0

    # キューに何かがある限り探索を続ける
    while que:
        c = que.popleft()

        # 今の距離
        dist = field[c[0]][c[1]]

        # 動いた先が「.」なら、距離を記録してキューに追加
        for m in moves:
            my = c[0] + m[0]
            mx = c[1] + m[1]

            if field[my][mx] == ".":
                field[my][mx] = dist + 1
                que.append([my, mx])
            else:
                continue
    
    # キューを消化したら最大値を取り出す
    field = sum(field, [])
    ans = max(ans, max([x for x in field if type(x)==int]))

print(ans)

Submission status: Accepted

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

h, m = map(int, input().split())
s = [0] * h
for i in range(h):
    s[i] = list(input())

def bfs(st_h, st_w):
    alr = [[-1] * m for _ in range(h)]
    alr[st_h][st_w] = 0
    que = deque([[st_h, st_w]])
    while len(que) > 0:
        now = que.popleft()
        # UP
        if alr[max(0, now[0]-1)][now[1]] == -1 and s[max(0, now[0]-1)][now[1]] == '.':
            que.append([now[0]-1, now[1]])
            alr[now[0]-1][now[1]] = alr[now[0]][now[1]] + 1
        # DOWN
        if alr[min(h-1, now[0]+1)][now[1]] == -1 and s[min(h-1, now[0]+1)][now[1]] == '.':
            que.append([now[0]+1, now[1]])
            alr[now[0]+1][now[1]] = alr[now[0]][now[1]] + 1
        # LEFT
        if alr[now[0]][max(0, now[1]-1)] == -1 and s[now[0]][max(0, now[1]-1)] == '.':
            que.append([now[0], now[1]-1])
            alr[now[0]][now[1]-1] = alr[now[0]][now[1]] + 1
        # RIGHT
        if alr[now[0]][min(m-1, now[1]+1)] == -1 and s[now[0]][min(m-1, now[1]+1)] == '.':
            que.append([now[0], now[1]+1])
            alr[now[0]][now[1]+1] = alr[now[0]][now[1]] + 1
    res = 0
    for x in alr:
        for y in x:
            res = max(res, y)
    return res

ans = 0

for a in range(h):
    for b in range(m):
        if s[a][b] == '.':
            ans = max(ans, bfs(a, b))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import numpy as np


def bfs(i, j):
    queue = deque()
    queue.append((i, j))
    visited = [[0] * (w + 2) for _ in range(h + 2)]
    visited[i][j] = 1
    moves = [[0] * (w + 2) for _ in range(h + 2)]
    while queue:
        i, j = queue.popleft()
    
        next_points = (
            (i, j + 1),
            (i + 1, j),
            (i, j - 1),
            (i - 1, j)
        )
        
        for next_i, next_j in next_points:
            if not visited[next_i][next_j] and maze[next_i][next_j] == '.':
                queue.append((next_i, next_j))
                visited[next_i][next_j] = 1
                moves[next_i][next_j] = moves[i][j] + 1
    
    return moves


h, w = map(int, input().split())
end = '#' * (w + 2)
maze = [end]
for _ in range(h):
    s = input()
    maze.append('#' + s + '#')
maze.append(end)

max_move = 0
for i in range(1, h+1):
    for j in range(1, w+1):
        if maze[i][j] == '#':
            continue
        moves = np.array(bfs(i, j))
        max_move = max(max_move, np.max(moves))
        
print(max_move)

Submission status: Accepted

Solution code:
from collections import deque
H,W=map(int,input().split())
S=[list(input()) for _ in range(H)]
ma = 0
for i in range(H):
    for j in range(W):
        d=deque()
        if S[i][j]==".":
            dp=[[float("inf") for _ in range(W)] for _ in range(H)]
            dp[i][j]=0
            d.append([i,j])
            while len(d)>0:
                x,y=d.popleft()
                if x!=0:
                    if S[x-1][y]==".":
                        if dp[x-1][y]>(dp[x][y]+1):
                            dp[x-1][y]=dp[x][y]+1
                            d.append([x-1,y])
                if x!=H-1:
                    if S[x+1][y]==".":
                        if dp[x+1][y]>(dp[x][y]+1):
                            dp[x+1][y]=dp[x][y]+1
                            d.append([x+1,y])
                if y!=0:
                    if S[x][y-1]==".":
                        if dp[x][y-1]>(dp[x][y]+1):
                            dp[x][y-1]=dp[x][y]+1
                            d.append([x,y-1])
                if y!=W-1:
                    if S[x][y+1]==".":
                        if dp[x][y+1]>(dp[x][y]+1):
                            dp[x][y+1]=dp[x][y]+1
                            d.append([x,y+1])
                #print(dp,d)
            for k in range(H):
                for l in range(W):
                    if dp[k][l]!=float("inf"):
                        ma=max(ma,dp[k][l])
print(ma)

Submission status: Accepted

Solution code:
from collections import deque

h,w = map(int,input().split())
s = [list(input()) for j in range(h)]
path = [[[]for i in range(w)]for j in range(h)]
sg = []
for i in range(h):
    for j in range(w):
        if s[i][j] == '#':
            continue
        else:
            sg.append((i,j))
        if j != w-1 and s[i][j+1] == '.':
            path[i][j].append((i,j+1))
        if i != h-1 and s[i+1][j] == '.':
            path[i][j].append((i+1,j))
        if j != 0 and s[i][j-1] == '.':
            path[i][j].append((i,j-1))
        if i != 0 and s[i-1][j] == '.':
            path[i][j].append((i-1,j))
que = deque([])
ans = 0
for x,y in sg:
    passed = [[0 for ii in range(w)] for jj in range(h)]
    que = deque([])
    que.append((x,y))
    depth = [[-1 for ii in range(w)] for jj in range(h)]
    depth[x][y] = 0
    while len(que) > 0:
        vx,vy = que.popleft()
        d = depth[vx][vy]
        for wx,wy in path[vx][vy]:
            if depth[wx][wy] > -1:
                continue
            depth[wx][wy] = d + 1
            que.append((wx,wy))
        ans = max(ans,d)
print(ans)

Submission status: Accepted

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


def main():
    H, W = map(int, input().split())
    S = [None for _ in range(H)]
    for i in range(H):
        S[i] = input()

    adj = [[] for _ in range(H * W)]
    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]

    for i in range(H):
        for j in range(W):
            if S[i][j] == '.':
                for k in range(4):
                    y = i + dy[k]
                    x = j + dx[k]
                    if 0 <= y < H and 0 <= x < W:
                        if S[y][x] == '.':
                            adj[W*i + j].append(W*y + x)

    # スタート
    ans = 0
    for i in range(H*W):
        queue = deque([i])
        visit = [-1] * (H * W)
        visit[i] = 0

        while queue:
            now = queue.popleft()
            for u in adj[now]:
                if visit[u] < 0:
                    queue.append(u)
                    visit[u] = visit[now] + 1
        ans = max(ans, max(visit))
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

mx = [0,0,1,-1]
my = [1,-1,0,0]

ans = 0
for i in range(h):
    for j in range(w):
        if s_input[i][j]=='#':
            continue
        queue = deque()
        queue.append([j,i])

        visited = [[-1]*w for i in range(h)]
        visited[i][j]=0

        res = 0
        while queue:
            x,y = queue.popleft()
            for k in range(4):
                nx = x+mx[k]
                ny = y+my[k]
                if 0<=nx<w and 0<=ny<h:
                    if visited[ny][nx]!=-1:
                        continue
                    if s_input[ny][nx]=='#':
                        continue
                    visited[ny][nx]=visited[y][x]+1
                    queue.append([nx,ny])
                    res = max(res,visited[ny][nx])
        ans = max(ans,res)
print(ans)

Submission status: Accepted

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

steps = [0, 1, 0, -1, 0]
ans = 0
for y in range(h):
    for x in range(w):
        if table[y][x] == "#":
            continue
        t = deepcopy(table)
        t[y][x] = 0
        queue = deque()
        queue.append((y, x))
        while len(queue) > 0:
            cur = queue.popleft()
            for i in range(4):
                ny, nx = cur[0] + steps[i], cur[1] + steps[i + 1]
                if 0 <= ny and ny < h and 0 <= nx and nx < w and t[ny][
                        nx] == ".":
                    t[ny][nx] = t[cur[0]][cur[1]] + 1
                    queue.append((ny, nx))
        tmp = 0
        for i in range(h):
            for j in range(w):
                if str(t[i][j]).isnumeric():
                    tmp = max(tmp, t[i][j])
        ans = max(ans, tmp)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
from copy import deepcopy


def bfs(maze, s):
    que = deque()
    que.append(s)
    nx = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    while que:
        x, y, c = que.popleft()
        if maze[x][y] != ".":
            continue
        maze[x][y] = c
        for u, v in nx:
            que.append((x + u, y + v, c + 1))
    ll = sum(maze, [])
    s = set(ll) - {"#"}

    return max(s)


def main():
    h, w = map(int, input().split())
    wall = ["#"] * (w + 2)
    maze = [wall]
    road = []
    for i in range(1, h + 1):
        line = ["#"] + list(input()) + ["#"]
        maze.append(line)
        for j, k in enumerate(line):
            if k == ".":
                road.append((i, j, 0))
    maze.append(wall)

    ans = 0
    for p in road:
        m = deepcopy(maze)
        ans = max(ans, bfs(m, p))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from copy import deepcopy
from collections import deque


def bfs(maze, x, y):
    res = 0
    que = deque([])
    que.append((x, y, 0))

    while que:
        i, j, c = que.popleft()
        if maze[i][j] == "#":
            continue
        maze[i][j] = "#"
        res = max(res, c)
        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            que.append((i + dx, j + dy, c + 1))

    return res


def main():
    h, w = map(int, input().split())
    wall = ["#"] * (w + 2)
    maze = [wall]
    for _ in range(h):
        line = ["#"] + list(input()) + ["#"]
        maze.append(line)
    maze.append(wall)

    ans = 0
    for i in range(1, h + 1):
        for j in range(1, w + 1):
            if maze[i][j] == "#":
                continue
            m = deepcopy(maze)
            ans = max(ans, bfs(m, i, j))

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import deque

def matrix(H,W, fill = False):
    return [[fill for x in range(W)] for j in range(H)]

def get_n(v):
    i,j = v

    li, lj = [i,j-1] if j>0 else [None,None]
    di, dj = [i+1,j] if i<H-1 else [None,None]
    ri, rj = [i,j+1] if j<W-1 else [None,None]
    ui, uj = [i-1,j] if i>0 else [None,None]

    pp = [(li,lj), (di,dj), (ri,rj), (ui,uj)]
    res = []

    for (i,j) in pp:
        if i!= None and maze[i][j] != "#":
            res.append((i,j))

    return res

H, W = map(int, input().split())
maze = []

prep = lambda x: 1 if x == "." else 0
for i in range(H):
    l  = input()
    maze.append(list(l))

max_d = 0

for i in range(H):
    for j in range(W):
        if maze[i][j] == "#":
            continue

        distance = matrix(H,W, 0)
        is_visited = matrix(H,W, 0)

        d = deque()
        d.append((i,j))
        is_visited[i][j] = 1

        while(d):
            v = d.popleft()
            for ni,nj in get_n(v):
                if is_visited[ni][nj]:
                    continue
                is_visited[ni][nj] = True
                distance[ni][nj] = distance[v[0]][v[1]] + 1
                max_d = max(distance[ni][nj], max_d)
                d.append((ni,nj))


print(max_d)

Submission status: Accepted

Solution code:
import queue
H, W = map(int, input().split())
S = []
for i in range(H):
  ss = input()
  S.append(ss)
rs = []
for n in range(H*W):
  sx, sy = n//W, n%W
  if S[sx][sy] == "#":
    continue
  M = [[-1]*W for i in range(H)]
  M[sx][sy] = 0
  q = queue.Queue()
  q.put((sx, sy, 0))
  while not q.empty():
    x, y, c = q.get()
    if x > 0 and S[x-1][y] == "." and M[x-1][y] < 0:
      M[x-1][y] = c+1
      q.put((x-1, y, c+1))
    if x+1 < H and S[x+1][y] == "." and M[x+1][y] < 0:
      M[x+1][y] = c+1
      q.put((x+1, y, c+1))
    if y > 0 and S[x][y-1] == "." and M[x][y-1] < 0:
      M[x][y-1] = c+1
      q.put((x, y-1, c+1))
    if y+1 < W and S[x][y+1] == "." and M[x][y+1] < 0:
      M[x][y+1] = c+1
      q.put((x, y+1, c+1))
  #print(M)
  r = max(map(max, M))
  rs.append(r)
r = max(rs)
print(r)

Submission status: Accepted

Solution code:
from collections import deque
import numpy as np

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

ans = 0
for x in range(H):
    for y in range(W):
        #壁からはスタートできない
        if maze[x][y] == "#":
            continue

        #初期化
        distance = [[0]*W for _ in range(H)]
        #start位置
        stack = deque([[x,y]])

        while stack:
            h,w = stack.popleft()
            for i,j in [[1,0],[-1,0],[0,1],[0,-1]]:
                new_h, new_w = h+i, w+j
                if new_h < 0 or new_w < 0 or new_h >= H or new_w >= W:
                    continue
                elif maze[new_h][new_w] != "#" and distance[new_h][new_w] == 0:
                    distance[new_h][new_w] = distance[h][w]+1
                    stack.append([new_h, new_w])

        #start位置は0で初期化
        distance[x][y] = 0
        ans = max(ans, np.max(distance))

print(ans)

Submission status: Accepted

Solution code:
import sys
from heapq import *
stdin=sys.stdin
    
ns = lambda:stdin.readline().rstrip()
ni = lambda:int(stdin.readline().rstrip())
nm = lambda:map(int,stdin.readline().split())
nl = lambda:list(map(int,stdin.readline().split()))
    
H,W=nm()
    
INF=10**18
def dijkstra(start,edge):
    d=[[INF]*W for i in range(H)]
    d[start[0]][start[1]]=0
    q=[(0,start[0],start[1])]
    while(len(q)!=0):
        ci,i,j=heappop(q)
        #if(d[start[0]][start[1]]<ci):
        #    continue 
        for p in edge[i][j]:
            if(d[p[0]][p[1]]>d[i][j]+1):
                d[p[0]][p[1]]=d[i][j]+1
                heappush(q,(d[p[0]][p[1]],p[0],p[1]))
    return d
    
E=[[[] for _ in range(W)] for _ in range(H)] 
S=[] 
    
for i in range(H):
    tmp=ns()
    S.append(tmp)
    
    
for i in range(H):
    for j in range(W):
        if( j+1<=W-1 and S[i][j+1]=='.'):
            E[i][j].append((i,j+1))
        if( i+1<=H-1 and S[i+1][j]=='.'):
            E[i][j].append((i+1,j))
        if(S[i][j-1]=='.' and 0<=j-1):
            E[i][j].append((i,j-1))
        if(S[i-1][j]=='.' and 0<=i-1):
            E[i][j].append((i-1,j))
    
    
    
ans=0
    
d=[[0]*W for i in range(H)]
for i in range(H):
    for j in range(W):
        if(S[i][j]!='.'):
            continue
        d=dijkstra((i,j),E)
        for k in range(H):
            for l in  range(W):
                if(ans<d[k][l] and d[k][l]<10**18):
                    ans=d[k][l]
                    
print(ans)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
#典型的なBFS
s = ["#"*(w+2) for _ in range(h+2)]
setroad = set([])
#額縁コーティング
for i in range(1, h+1):
	s[i] = "#"+input()+"#"

for i in range(h+2):
	for j in range(w+2):
		if s[i][j]==".":
			setroad.add((i,j))


#
def isroad(n, m):
	if (n, m) in setroad:
		return True
	else:
		return False


# 全探索
ans = 0

for shokix, shokiy in setroad:
	kaisuu = 0
	settansaku = set([])
	listmada = [(shokix, shokiy)]
	setmada = set([(shokix,shokiy)])
	while len(setmada) != 0:
		for i, j in listmada[:]:
			settansaku.add((i,j))
			listmada.remove((i, j))
			setmada.remove((i, j))
			for k,l in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
				if isroad(k,l):
					if not (k,l) in setmada:
						if not (k,l) in settansaku:
							listmada.append((k,l))
							setmada.add((k,l))
		kaisuu += 1
	kaisuu -= 1
	if kaisuu >= ans:
		ans = kaisuu
print(ans)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
#典型的なBFS
s = ["#"*(w+2) for _ in range(h+2)]
road = []
setroad = set([])
#額縁コーティング
for i in range(1, h+1):
	s[i] = "#"+input()+"#"

for i in range(h+2):
	for j in range(w+2):
		if s[i][j]==".":
			road.append((i,j))
			setroad.add((i,j))


#
def isroad(n, m):
	if (n, m) in setroad:
		return True
	else:
		return False


# 全探索
ans = 0

for shokix, shokiy in road:
	kaisuu = 0
	listtansaku = []
	settansaku = set([])
	listmada = [(shokix, shokiy)]
	setmada = set([(shokix,shokiy)])
	while len(setmada) != 0:
		for i, j in listmada[:]:
			listtansaku.append((i,j))
			settansaku.add((i,j))
			listmada.remove((i, j))
			setmada.remove((i, j))
			for k,l in [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]:
				if isroad(k,l):
					if not (k,l) in setmada:
						if not (k,l) in settansaku:
							listmada.append((k,l))
							setmada.add((k,l))
		kaisuu += 1
	kaisuu -= 1
	if kaisuu >= ans:
		ans = kaisuu
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
INF = 10**18
h,w = map(int,input().split())
li = [list(input()) for i in range(h)]


def bfs(sy,sx):
    #頂点をINFで初期化
    d = [[INF]*w for i in range(h)]
    
    #移動４方向のベクトル
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]

    #スタート位置とゴール位置を探す
    """
    for i in range(h):
        for j in range(w):
            if li[i][j]  == "s":
                sx = i
                sy = j
            if li[i][j] == "g":
                gx = i
                gy = j
    """
    if li[sy][sx] == "#":
        return 0
    #スタート地点をキューにいれ、頂点を０にする
    que = deque([])
    que.append((sy,sx))
    d[sy][sx] = 0
    
    #キューが空になるまでループ（行ける要素がなくなるまで）
    while que:
        # キューの先頭を取り出す
        p = que.popleft()
        # 取り出してきた状態がゴールなら探索をやめる
        """
        if p[0] == gx and p[1] == gy:
            break
        """
        # 移動4方向をループ
        for i in range(4):
            nx = p[1] + dx[i]
            ny = p[0] + dy[i]

            #壁との判定とすでに訪れたかどうかをチェック
            if 0<=nx and nx < w and 0 <= ny and ny < h:
                if li[ny][nx] != "#" and d[ny][nx] == INF:
                    #移動できる点なのでキューについか
                    que.append((ny,nx))
                    #前の点+1で移動できる
                    d[ny][nx] = d[p[0]][p[1]] + 1
    dmax = 0
    for i in range(h):
        for j in range(w):
            if d[i][j] == INF:
                continue
            dmax = max(dmax,d[i][j])
    return dmax
ans = 0
for i in range(h):
    for j in range(w):
        c = bfs(i,j)
        ans = max(ans,c)
print(ans)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
Inf = 10**9

S = [input() for i in range(H)]
dis = [[Inf]*(H*W) for i in range(H*W)]

for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            continue
        if i - 1 >= 0 and S[i-1][j] == ".":
            dis[i*W+j][(i-1)*W+j] = 1
        if i + 1 < H and S[i+1][j] == ".":
            dis[i*W+j][(i+1)*W+j] = 1
        if j - 1 >= 0 and S[i][j-1] == ".":
            dis[i*W+j][i*W+j-1] = 1
        if j + 1 < W and S[i][j+1] == ".":
            dis[i*W+j][i*W+j+1] = 1

for i in range(H*W):
    for j in range(H*W):
        for k in range(H*W):
            dis[j][k] = min(dis[j][i] + dis[i][k], dis[j][k])

max_ans = 0
for i in range(H*W):
    for j in range(H*W):
        if i == j or dis[i][j] == Inf:
            continue        
        max_ans = max(dis[i][j], max_ans)

print(max_ans)

Submission status: Accepted

Solution code:
import queue

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

def nexts(h, w):
    l = []
    if h > 0   and S[h-1][w] == '.':
        l.append((h-1, w))
    if h < H-1 and S[h+1][w] == '.':
        l.append((h+1, w))
    if w > 0   and S[h][w-1] == '.':
        l.append((h, w-1))
    if w < W-1 and S[h][w+1] == '.':
        l.append((h, w+1))
    return l

def bfs(h, w):
    d = [[0]*W for _ in range(H)]
    q = queue.Queue()
    q.put((h,w))

    while not q.empty():
        v = q.get()
        vh, vw = v[0], v[1]

        for nxt in nexts(vh, vw):
            nh, nw = nxt[0], nxt[1]
            if d[nh][nw] > 0:
                continue
            d[nh][nw] = d[vh][vw] + 1
            q.put((nh, nw))
    d[h][w] = 0
    return d

ans = 0
for h in range(H):
    for w in range(W):
        if S[h][w] == '#':
            continue

        d = bfs(h,w)
        mx = 0
        for th in range(H):
            for tw in range(W):
                mx = max(mx, d[th][tw])
        ans = max(ans, mx)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

# 入力を整数に変換して受け取る
def input_int():
    return int(input())


# マイナス1した値を返却
def int1(x):
    return int(x) - 1


# 半角スペース区切り入力をIntに変換してMapで受け取る
def input_to_int_map():
    return map(int, input().split())


# 半角スペース区切り入力をIntに変換して受け取る
def input_to_int_tuple():
    return tuple(map(int, input().split()))


# 半角スペース区切り入力をIntに変換してマイナス1した値を受け取る
def input_to_int_tuple_minus1():
    return tuple(map(int1, input().split()))


def main():
    h, w = input_to_int_map()
    mz = [input() for i in range(h)]

    from collections import deque

    ret = 0
    for x in range(h):
        for y in range(w):
            # 壁からはスタートできない
            if mz[x][y] == "#":
                continue

            # 初期化
            distance = [[0] * w for _ in range(h)]
            # start位置
            dq = deque([[x, y]])

            while dq:
                now_h, now_w = dq.popleft()
                for i, j in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
                    new_h, new_w = now_h + i, now_w + j
                    if new_h < 0 or new_w < 0 or new_h >= h or new_w >= w:
                        continue

                    if mz[new_h][new_w] != "#" and distance[new_h][new_w] == 0:
                        distance[new_h][new_w] = distance[now_h][now_w] + 1
                        dq.append([new_h, new_w])

            distance[x][y] = 0
            ret = max(max(list(map(max, distance))), ret)

    return ret


if __name__ == "__main__":
    print(main())

Submission status: Accepted

Solution code:
import sys

# import re
# import math
# import collections
# import decimal
# import bisect
# import itertools
# import fractions
# import functools
# import copy
# import heapq
# import decimal
# import statistics
import queue

sys.setrecursionlimit(10000001)
INF = 10 ** 10
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===


def main():
    h, w = ns()
    mat = [list(sys.stdin.readline()) for _ in range(h)]

    def bfs(x, y):
        arrived_mat = [[False for i in range(w)] for j in range(h)]

        que = queue.Queue()
        que.put((x, y, 1))
        arrived_mat[y][x] = True
        res = 0

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

        while que.qsize() > 0:
            xi, yi, cnt = que.get()

            for dx, dy in direc:
                next_x = xi + dx
                next_y = yi + dy
                if -1 < next_x < w and -1 < next_y < h:
                    if mat[next_y][next_x] == "." and arrived_mat[next_y][next_x] != True:
                        que.put((next_x, next_y, cnt + 1))
                        arrived_mat[next_y][next_x] = True                        
                        res = max(res, cnt + 1)

        return res

    ans = 0
    for y in range(h):
        for x in range(w):
            if mat[y][x] == ".":
                ans = max(ans, bfs(x, y) - 1)

    print(ans)


if __name__ == '__main__':
    main()