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:
from collections import deque
from copy import deepcopy
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
ans=0
for i in range(h):
    for j in range(w):
        
        count=[[0]*w for _ in range(h)]
        if s[i][j]==".":
            s_copy=deepcopy(s)
            que=deque()
            que.append([i,j])
            s_copy[i][j]="#"
            
            while que:
                
                x,y=tuple(que.popleft())
                dx_dy=[[1,0],[0,1],[-1,0],[0,-1]]
                for k in range(4):
                    nx=x+dx_dy[k][0]
                    ny=y+dx_dy[k][1]
                    if 0<=nx<=h-1 and 0<=ny<=w-1:
                        if s_copy[nx][ny]==".":
                            s_copy[nx][ny]="#"
                            count[nx][ny]=count[x][y]+1
                            que.append([nx,ny])
        
            temp=0
            for l in range(h):
              temp=max(temp,max(count[l]))
            ans=max(temp,ans)
print(ans)

Submission status: Accepted

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
    table[i][j] = "#"
    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: Accepted

Solution code:
from collections import deque
 
def main():
    H,W=map(int,input().split())
    S=[]
    for i in range(H):
        s=input()
        S.append(s)
 
    G=[]
    for i in range(H):
        for j in range(W):
            tmp=[]
            if S[i][j]=="#":
                G.append(tmp)
                continue
            if i-1>=0:
                if S[i-1][j]==".":
                    tmp.append((i-1)*W+j)
            if i+1<=H-1:
                if S[i+1][j]==".":
                    tmp.append((i+1)*W+j)
            if j-1>=0:
                if S[i][j-1]==".":
                    tmp.append(i*W+j-1)
            if j+1<=W-1:
                if S[i][j+1]==".":
                    tmp.append(i*W+j+1)
            G.append(tmp)
 
    res=0
 
    for start in range(H*W):
        dist = 0
        v = [-1 for _ in range(H * W)]
        que=deque([])
        que.append(start)
        v[start]=dist
        while len(que)>0:
            next_index=que.popleft()
            next=G[next_index]
            for i in next:
                if v[i]==-1:
                    que.append(i)
                    v[i]=v[next_index]+1
 
        if max(v)>=res:
            res=max(v)
 
    print(res)
 
 
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import os, sys, re, math


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


def set_moves(x, y, moves):
    if S[y + 1][x + 1] != '.':
        return
    if 0 <= grid[y][x] < moves:
        return

    grid[y][x] = moves
    set_moves(x, y - 1, moves + 1)
    set_moves(x, y + 1, moves + 1)
    set_moves(x - 1, y, moves + 1)
    set_moves(x + 1, y, moves + 1)


S = []
S.append('#' * (W + 2))
has_wall = False
for i in range(H):
    s = input()
    has_wall |= '#' in s
    S.append('#' + s + '#')
S.append('#' * (W + 2))

if not has_wall:
    result = W + H - 2
else:
    result = 0
    for gy in range(H):
        for gx in range(W):
            if S[gy + 1][gx + 1] != '.':
                continue
            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: Accepted

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.get((x, y), 0)

t = 0
for y in range(h):
    for x in range(w):
        t = max(t, bfs(x, y))
print(t)

Submission status: Accepted

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):
            if S[startx][starty] == "#":
                continue
            visited = [[-1 for _ in range(W)] for __ in range(H)]
            visited[startx][starty] = 0
            q = collections.deque([(startx, starty)])
            while q:
                x, y = q.pop()
                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] == -1:
                        visited[nx][ny] = visited[x][y] + 1
                        q.appendleft((nx, ny))
            maxdist = max(maxdist,max(sum(visited, [])))
    print(maxdist)
    

if '__main__' == __name__:
    resolve()

Submission status: Accepted

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[ni][nj] == '#':
                    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)])
                    #print('i,j = ', (i,j), 'ni,nj = ', (ni,nj), 'ans = ', cost[(i,j), (ni, nj)])
                    q.append((ni, nj))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H, W = map(int, input().split())
S_raw = [list(input()) for _ in range(H)]
m = 0
def calc(h,w):
    S = [list(S_raw[i][j] for j in range(W)) for i in range(H)]
    S[h][w]=0
    queue = deque([(h,w)])
    while queue:
        q = queue.popleft()
        for x in ((q[0]-1, q[1]),(q[0]+1, q[1]), (q[0], q[1]-1), (q[0], q[1]+1)):
          if 0<=x[0]<=H-1 and 0<=x[1]<=W-1:
            if S[x[0]][x[1]]==".":
              S[x[0]][x[1]] = S[q[0]][q[1]]+1
              queue.append(x)
    return max(S[h][w] for w in range(W) for h in range(H) \
                    if str(S[h][w]).isdigit())    
for h in range(H):
  for w in range(W):
    if S_raw[h][w]==".":
        m = max(m, calc(h,w))
print(m)

Submission status: Accepted

Solution code:
from collections import deque

def main():
    h, w = map(int, input().split())
    ls = [input() for _ in range(h)]

    def trans(a, b):
        return a * w + b

    ls2 = [[] for _ in range(h * w)]

    for i in range(h):
        for j in range(w):
            # check ij
            if ls[i][j] == '#':
                continue
            if i >= 1 and ls[i-1][j] != '#':
                ls2[trans(i, j)].append(trans(i-1, j))
            if i <= h-2 and ls[i+1][j] != '#':
                ls2[trans(i, j)].append(trans(i + 1, j))
            if j <= w-2 and ls[i][j+1] != '#':
                ls2[trans(i, j)].append(trans(i, j + 1))
            if j >= 1 and ls[i][j-1] != '#':
                ls2[trans(i, j)].append(trans(i, j - 1))


    #print(ls2)


    def route(i):
        count = 1
        ss = deque(ls2[i])
        next = deque()
        explored = {i}
        while ss or next:
            if not ss:
                count +=1
                ss = next
                next = deque()
            now =ss.popleft()
            if now in explored:
                continue
            else:
                explored.add(now)
                next.extend(ls2[now])
        return count-1
    ans = 0
    for i in range(h * w - 1):
        if ls2[i] == []:
            continue
        ans = max(ans, route(i))

    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

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 = h2+i, w2+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: Accepted

Solution code:
import sys
from collections import defaultdict, deque, Counter
import math

# import copy
from bisect import bisect_left, bisect_right
import heapq

sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline

getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = 10 ** 20
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)


def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD


def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD


def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def kaijyo(n):
    ret = [1]
    for i in range(1, n + 1):
        ret.append((ret[-1] * i)% MOD)
    return ret

def warshall_floyd(d, n):
    #d[i][j]: iからjへの最短距離
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid

    def pos(self, x, y):
        return y * (self.w + 2) + x + 1

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]

        ans = 0
        for i in range(1, self.h + 1):
            for j in range(1, self.w + 1):
                # pass # ここから何か書いてね
                cx, cy = j, i
                if grid[cy][cx] == ".":
                    ret = self.search_each(cx, cy)
                    ans = max(ans, ret)
        print(ans)

    def search_each(self, x, y):
        grid = self.grid
        d = deque()
        d.append((x,y))
        dist = [INF for i in range(self.size)]
        # print(x,y, self.size, self.pos(x,y))
        dist[self.pos(x,y)] = 0
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        ret = 0
        while d:
            cx, cy = d.pop()
            ccos = dist[self.pos(cx, cy)]
            ret = max(ret, ccos)
            for mv in move:
                dx, dy = mv
                nx, ny = cx + dx, cy + dy
                # print(nx, ny)
                if grid[ny][nx] == ".":
                    if dist[self.pos(nx, ny)] > ccos + 1:
                        dist[self.pos(nx, ny)] = ccos + 1
                        d.append((nx, ny))

        return max([r for r in dist if r != INF])


def solve():
    h, w = getList()
    G = TwoDimGrid(h, w)
    G.search()
    return



def main():
    n = getN()
    for _ in range(n):
        solve()


if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
from collections import deque

n , m = map(int, input().split())
maze = [['#']+list(input())+['#'] for i in range(n)]
maze = [['#']*(m+2)]+maze+[['#']*(m+2)]

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

costma=0
for i in range(1,n+1):
    for j in range(1,m+1):
        v = [[0]*(m+2) for i in range(n+2)]
        d = deque()
        d.append((i,j,0))
        v[i][j]=1
        while d:
            y,x,cost=d.popleft()
            if maze[y][x]=='.':
                for dy,dx in step:
                    if maze[y+dy][x+dx]=='.' and v[y+dy][x+dx]==0:
                        v[y+dy][x+dx]=1
                        d.append((y+dy,x+dx,cost+1))
                        costma=max(cost+1,costma)
print(costma)

Submission status: Accepted

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=[[-1 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]==-1 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: Accepted

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])
        visited = []
        for i in range(H):
            visited.append(maze[i][:])

        nexts = deque()
        nexts.append((start, 0))
        x,y = start
        visited[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 visited[next_x][next_y] == '.':
                        visited[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)
                longest_distance = bfs(maze, start)
                ans = max(longest_distance, ans)

    print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

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 if X[si][sj] == "." else INF
    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: Accepted

Solution code:
from collections import deque
import math
import copy
#https://qiita.com/ophhdn/items/fb10c932d44b18d12656

def max_dist(input_maze,startx,starty,mazex,mazey):
    input_maze[starty][startx]=0
    que=deque([[starty,startx]])
#    print(que)
    while que:
#        print(que,input_maze)
        y,x=que.popleft()
        for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            nexty,nextx=y+i,x+j
            if (nexty>=0) & (nextx>=0) & (nextx<mazex) & (nexty<mazey):
                dist=input_maze[nexty][nextx]
                if dist!=-1:
                    if (dist>input_maze[y][x]+1) & (dist > 0):
                        input_maze[nexty][nextx]=input_maze[y][x]+1
                        que.append([nexty,nextx])
#    print(que)
#    print(max(list(map(lambda x: max(x),copy_maze))))
    return max(list(map(lambda x: max(x),copy_maze)))

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

# Maze preprocess
for y in range(h):
    for x in range(w):
        if maze[y][x]=='.':
            maze[y][x]=math.inf
        elif maze[y][x] == '#':
            maze[y][x]=int(-1)

results = []

for y in range(h):
    for x in range(w):
        if maze[y][x]==math.inf:
            copy_maze = copy.deepcopy(maze)
            max_dist_result = max_dist(copy_maze,x,y,w,h)
            results.append(int(max_dist_result))
            #print(max_dist_result)

print(max(results))

Submission status: Accepted

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):
  #check start point is valid
  if (maze[start[0]][start[1]] == "#"):
    return 0
  # initialize BFS
  visitedCount = 1
  visitedPoints = []
  for r in range(H):
    visitedPoints.append([])
    for c in range(W):
      if (r == start[0]) and (c == start[1]):
        visitedPoints[r].append("Y")
      else:
        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: Accepted

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

# すべての.についてスタート地点と仮定してBFS
def bfs(i, j):
    dq = deque()
    maze_c = copy.deepcopy(maze)
    maze_c[i][j] = 0
    dq.appendleft([i, j])
    res = 0
    while len(dq) > 0:
        ni, nj = dq.pop()
        if maze_c[ni][nj] == "#":
            continue
        for di, dj in ((1, 0), (0, 1), (-1, 0), (0, -1)):
            if ni + di < 0 or nj + dj < 0 or ni + di >= H or nj + dj >= W:
                continue
            if maze_c[ni + di][nj + dj] == ".":
                maze_c[ni + di][nj + dj] = maze_c[ni][nj] + 1
                res = max(res, maze_c[ni + di][nj + dj])
                dq.appendleft([ni + di, nj + dj])
    return res

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

Submission status: Accepted

Solution code:
H,W = list(map(int,input().split()))
N=H*W

#壁のノード
wall=[]
for h in range(H):
    for w_idx,w in enumerate(list(input())):
        if w == '#':
            wall.append(W*h+w_idx+1)
#道のノード        
path=[_ for _ in range(1,N+1) if _ not in wall]

#隣接リスト
ad = {}
for n in range(N):
    ad[n+1]=[]
    
for n in range(N):
    n=n+1
    if n not in wall:
        up = n-W
        if up > 0 and up not in wall:
            ad[n].append(up)
            
        down = n+W
        if down <= N and down not in wall:
            ad[n].append(down)
            
        left = n-1
        if n % W != 1 and left not in wall and left > 0:
            ad[n].append(left)
        
        right = n+1
        if n % W != 0 and right not in wall:
            ad[n].append(right)      

from collections import deque

def BFS(start):
    que = deque([start])
    visit = deque([])

    color = {}
    for n in range(N):
        color[n+1] = -1
    color[start] = 0

    depth = {}
    for n in range(N):
        depth[n+1] = -1

    depth[start] = 0
    while len(que) > 0:
        start = que[0]
        for v in ad[start]:
            if color[v] == -1:
                que.append(v)
                color[v] = 0
                depth[v] = depth[start]+1

        color[start] = 1
        visit.append(que.popleft())

    return depth[start]

ans=-1
for start in path:
    ans_=BFS(start)
    if ans < BFS(start):
        ans = ans_
    
#     print(start,ans_)
    
print(ans)

Submission status: Accepted

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

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

def bfs(x,y):
    if M[x][y]=='#':
        return 0
    q=deque()
    q.append((x,y))
    count = [[-1]*w for _ in range(h)]
    count[x][y]=0

    while q:
        x,y=q.pop()
        for i,j in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
            if 0<=i<h and 0<=j<w and count[i][j]==-1 and M[i][j]=='.':
                count[i][j]=count[x][y]+1
                q.appendleft((i,j))

    return max([max(c) for c in count])
        
ans = 0
for i in range(h):
    for j in range(w):
        ans = max(ans,bfs(i,j))
print(ans)

Submission status: Accepted

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):
        if g[x][y] == ".":
            max_count = max(max_count, bfs(x, y))

print(max_count)

Submission status: Accepted

Solution code:
from queue import Queue
def isSafe(row, col):
    return row >= 0 and col >= 0 and row<h and col<w and mat[row][col] != '#'


def bfs(row, col):
    visited = [[False]*w for _ in range(h)]
    que = Queue()
    dst = 0
    que.put([row, col, 0])
    visited[row][col] = True
    moves = [[-1, 0],[1, 0], [0, -1], [0, 1]]
    while not que.empty():
        root = que.get()
        row, col, dst = root
        for nrow, ncol in moves:
            row2 = row + nrow
            col2 = col + ncol 
            if isSafe(row2, col2) is True and visited[row2][col2] is False:
                visited[row2][col2] = True
                que.put([row2, col2, dst+1])
                 
    return dst 

h, w = map(int, input().split())
mat = [input() for _ in range(h)]
ans = 0
for row in range(h):
    for col in range(w):
        if mat[row][col] == '.':
            ans = max(ans, bfs(row, col))

print(ans)