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:
H,W = list(map(int,input().split()))

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

from collections import deque

out = 0
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

for sx in range(0,W):
    for sy in range(0,H):
        if M[sy][sx]=="#":
            continue
        d = [[10**4] * W for i in range(H)]
        que = deque([])
        que.append((sy, sx))
        d[sy][sx] = 0
        while que:
            p = que.popleft()
            for i in range(4):
                ny = p[0] + dy[i]
                nx = p[1] + dx[i]
                if (0<=nx<W)and(0<=ny<H)and(M[ny][nx]!="#")and(d[ny][nx]==10**4):
                    que.append((ny, nx))
                    d[ny][nx] = d[p[0]][p[1]] + 1
                    out = max(d[ny][nx],out)
print(out)

Submission status: Accepted

Solution code:
from collections import deque

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

dir = [[1,0], [-1,0], [0,1], [0,-1]]
ans = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == "#": continue
        ls = deque([[i, j]])
        dp = [[float("inf") for k in range(W)] for l in range(H)]
        dp[i][j] = 0
        while len(ls) > 0:
            x, y = ls.popleft()

            for dx, dy in dir:
                if x+dx < 0 or H-1 < x+dx: continue
                if y+dy < 0 or W-1 < y+dy: continue
                if S[x+dx][y+dy] == "#" or dp[x+dx][y+dy] != float("inf"): continue
                if dp[x+dx][y+dy] > dp[x][y] + 1:
                    dp[x+dx][y+dy] = dp[x][y] + 1
                    ls.append([x+dx,y+dy])

        for h in range(H):
            for w in range(W):
                if dp[h][w] == float("inf"): continue
                ans = max(ans, dp[h][w])

print(ans)

Submission status: Accepted

Solution code:
from collections import *

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

ans = 0
INF = float('inf')

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

        dist = [[INF for i in range(W)] for j in range(H)]
        visited = [[False for i in range(W)] for j in range(H)]

        q = deque()
        q.append((i, j, 0))
        
        while q:
            i, j, c = q.popleft()

            if visited[i][j]: continue
            visited[i][j] = True
            dist[i][j] = c
            ans = max(ans, c)
            for a, b in [(1,0), (-1,0), (0,1), (0,-1)]:
                x = i+a
                y = j+b

                if 0 <= x < H and 0 <= y < W and S[x][y] == '.' and not visited[x][y]:
                    q.append((x, y, c+1))

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
input = lambda: sys.stdin.readline().strip()

h, w = [int(x) for x in input().split()]
g = [input() for _ in range(h)]
ans = 0
for si in range(h):
    for sj in range(w):
        if g[si][sj] != '#':
            d = [[-1 for j in range(w)] for i in range(h)]
            d[si][sj] = 0
            q = [(si, sj)]
            for i, j in q:
                ans = max(ans, d[i][j])
                for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                    ni, nj = i + di, j + dj
                    if 0 <= ni < h and 0 <= nj < w and g[ni][nj] != '#' and d[ni][nj] == -1:
                        d[ni][nj] = d[i][j] + 1
                        q.append((ni, nj))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

def bfs(sh,sw):
  if s[sh][sw] == "#":
    return 0
  queue = deque([(sh,sw)]) #スタート地点をdequeに入れる
  dist = [[-1] * (W+1) for i in range(H+1)] #距離をメモするリストを作成
  dist[sh][sw] = 0 #スタート地点の距離を0にする
  while queue:
    h,w = queue.popleft() #queueの左から位置情報を取り出す
    d = dist[h][w] #現在のマスの数字を保持(移動距離)
    # print("dist", dist)
    for i in [h-1,h+1]: #x軸に前後する
      if s[i][w] == "." and dist[i][w] == -1: #行ける、かつ未踏破のマス
        dist[i][w] = d + 1 #移動距離をメモ
        queue.append((i,w)) #移動先のマスをqueueに格納
    for j in [w-1,w+1]: #y軸を行ったり来たり
      if s[h][j] == "." and dist[h][j] == -1:
        dist[h][j] = d + 1
        queue.append((h,j))
          
  max_dist = 0
  for i in dist:
    max_dist = max(max_dist,max(i)) #移動距離が多いマスを抽出
  return max_dist
      

ans = 0          
for i in range(1,H+1):
  for j in range(1,W+1):
    now = bfs(i,j)
    ans = max(ans, now)
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

H, W = MAP()
S = [input() for _ in range(H)]
dy = (1, 0, -1, 0)
dx = (0, -1, 0, 1)

def diff_max(start_y, start_x):
	check = [[-1]*W for _ in range(H)]
	check[start_y][start_x] = 0
	q = deque([(start_y, start_x)])

	while q:
		y, x = q.popleft()
		for i in range(4):
			ny = y + dy[i]
			nx = x + dx[i]
			if 0 <= ny < H and 0 <= nx < W:
				if check[ny][nx] == -1 and S[ny][nx] == ".":
					check[ny][nx] = check[y][x] + 1
					q.append((ny, nx))

	return max([max(x) for x in check])



ans = -INF
for i in range(H):
	for j in range(W):
		if S[i][j] == ".":
			ans = max(ans, diff_max(i, j))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
import copy

digtmp = [[0, 1], [1, 0], [0, -1], [-1, 0]]

def bfs(maze, s):
    que = deque([s])
    maze[s[0]][s[1]] = 0
    ans = 0
    for _ in range(pow(10, 3)):
        fr = que.popleft()
        for d in digtmp:
            to = [fr[0] + d[0], fr[1] + d[1]]
            if maze[to[0]][to[1]] == '.':
                nxt = maze[fr[0]][fr[1]] + 1
                maze[to[0]][to[1]] = nxt
                ans = max(ans, nxt)
                que.append(to)
        if len(que) == 0:
            break
    return ans

def main():
    H, W = map(int, input().split())
    grid = []; road = []
    grid.append(['#']*(W+2))
    for i in range(H):
        tmp = list(input())
        for j in range(W):
            if tmp[j] == '.':
                road.append([i+1, j+1])
        grid.append(['#'] + tmp + ['#'])
    grid.append(['#']*(W+2))
    
    ans = 1
    for r in road:
        maze = copy.deepcopy(grid)
        ans = max(ans, bfs(maze, r))
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# すべてのスタートを試し、最大値の最大値を取る

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
grid = [readline().rstrip() for i in range(H)]

ans = 0
cases = ((0,1),(0,-1),(1,0),(-1,0))
from collections import deque
for i in range(H):
  for j in range(W):
    q = deque([[i,j,0]])
    visited = [[False] * W for i in range(H)]
    while q:
      y,x,d = q.popleft()
      if grid[y][x] == "#":
        continue
      if visited[y][x]:
        continue
      visited[y][x] = True
      if d > ans:
        ans = d
      for c in cases:
        if 0 <= y + c[0] < H and 0 <= x + c[1] < W:
          q.append([y + c[0],x + c[1],d + 1])
print(ans)

Submission status: Accepted

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

def bfs(field, sx, sy, seen):
    queue = deque([(sx, sy)])
    seen[sx][sy] += 1
    
    while queue:
        x, y = queue.popleft()

        for dx, dy in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
            nx = x + dx
            ny = y + dy
            
            if seen[nx][ny] == -1 and field[nx][ny] != "#":
                seen[nx][ny] = seen[x][y] + 1
                queue.append((nx, ny))

    return seen[x][y]


def main():
    H,W = map(int, readline().split())
    c = ["#" * (W + 2)]
    for _ in range(H):
        c.append("#" + readline().strip() + "#")
    c.append("#" * (W + 2))

    ans = 0
    for sx in range(1,H+1):
        for sy in range(1,W+1):
            if c[sx][sy] == ".":
                seen = [[-1] * (W + 2) for i in range(H+2)]
                dist = bfs(c, sx, sy, seen)
                ans = max(ans, dist)

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque

h,w = map(int, input().split())
grid = []
for i in range(h):
    s = list(input().rstrip())
    grid.append(s)
dydx = [[0, 1], [1,0], [-1, 0], [0, -1]]

def find_longest_path(xy):
    visited = [[0]*w for _ in range(h)]
    dist = [[0]*w for _ in range(h)]
    visited[xy[1]][xy[0]]=1
    que = deque()
    que.append(xy)
    while que:
        v = que.popleft()
        x,y = v[0],v[1]
        for i in dydx:
            dx = i[0]
            dy = i[1]
            if ((x+dx<w and y+dy<h) and ((x+dx)>-1)and(y+dy)>-1) and not visited[y+dy][x+dx]:
                if(grid[y+dy][x+dx]=="."):
                    que.append([x+dx, y+dy])
                    visited[y+dy][x+dx]=1
                    dist[y+dy][x+dx]=dist[y][x]+1
                    u,k = x+dx, y+dy
                    r = dist[y+dy][x+dx]

    return r

def main():
    k=0
    for i in range(h):
        for j in range(w):
            if grid[i][j]==".":
                k = max(k, find_longest_path([j,i]))
    print(k)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[list(input()) for _ in range(h)]
dy=[1, 0, -1, 0]
dx=[0, 1, 0 ,-1]

from collections import deque
ans=0
for i in range(h):
    for j in range(w):
        if s[i][j]=='#':
            continue
        d=[[-1]*w for _ in range(h)]
        queue=deque()
        queue.append((i,j))
        d[i][j]=0
        tmp_ans=-1
        while queue:
            y,x=queue.popleft()
            for d_y, d_x in zip(dx,dy):
                new_y=y+d_y
                new_x=x+d_x
                if new_y<0 or h<=new_y or new_x<0 or w<=new_x:
                    continue
                if s[new_y][new_x]=='.' and d[new_y][new_x]==-1:
                    d[new_y][new_x]=d[y][x]+1
                    queue.append((new_y, new_x))
                    tmp_ans=max(tmp_ans, d[new_y][new_x])
        ans=max(ans, tmp_ans)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
def bfs(maze,sy,sx):
  queue=deque([[sy,sx]])
  visited=[[0]*w for _ in range(h)]
  visited[sy][sx]=1
  mx=0
  while queue:
    y,x=queue.popleft()
    for j,k in ([1,0],[-1,0],[0,1],[0,-1]):
      n_y,n_x=y+j,x+k
      if not (0<=n_y<h and 0<=n_x<w):
        continue
      if maze[n_y][n_x]=='.' and visited[n_y][n_x]==0:
        visited[n_y][n_x]=visited[y][x]+1
        mx=max(mx,visited[n_y][n_x])
        queue.append([n_y,n_x])
  return mx

h,w=map(int,input().split())
s=[input() for _ in range(h)]
ans=0
for sy in range(h):
  for sx in range(w):
    if s[sy][sx]=='#':
      continue
    ans=max(ans,bfs(s,sy,sx)-1)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
h , w = map(int,input().split())
S = [input() for i in range(h)]
dxy = [(0,1),(1,0),(-1,0), (0,-1)]

ans = 0
for y in range(h):
    for x in range(w):
        if S[y][x] == '#': continue
        dist =[[0]*w for i in range(h)]
        visited = [[0]*w for i in range(h)]
        visited[y][x] = 1
        q = deque([(x,y)])
        while q:
            x,y = q.popleft()
            for dx, dy in dxy:
                nx, ny = x + dx, y+ dy
                if not 0 <= nx < w: continue
                if not 0 <= ny < h: continue 
                if visited[ny][nx]:continue
                if S[ny][nx] == '#':continue  
                visited[ny][nx] = 1
                dist[ny][nx] = dist[y][x] + 1
                q.append((nx,ny))
        ans = max(ans, max(max(row) for row in dist)) 
print(ans)

Submission status: Accepted

Solution code:
h,w=[int(x) for x in input().rstrip().split()]
l=[list(input()) for i in range(h)]
move=[[1,0],[-1,0],[0,-1],[0,1]]
def bfs(x,y):
  stack=[[x,y]]
  done=[[False]*w for i in range(h)]
  dist=[[0]*w for i in range(h)]
  max_val=0
  while(stack):
    nx,ny=stack.pop(0)
    done[ny][nx]=True
    for dx,dy in move:
      mx=nx+dx
      my=ny+dy
      if not(0<=mx<=w-1) or not(0<=my<=h-1) or done[my][mx]==True or l[my][mx]=="#":
        continue
      done[my][mx]=True
      dist[my][mx]=dist[ny][nx]+1
      max_val=max(max_val,dist[my][mx])
      stack.append([mx,my])
  return max_val

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

Submission status: Accepted

Solution code:
# BFS
from collections import deque

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

ans = 0

for i in range(h):
    for j in range(w):
        if s[i][j] == '#': continue
        q = deque([(i, j)])
        dist = [[-1]*w for _ in range(h)]
        dist[i][j] = 0
        while q:
            x, y = q.popleft()
            for k, l in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                if 0 <= x+k < h and 0 <= y+l < w and dist[x+k][y+l] < 0 and s[x+k][y+l] == '.':
                    dist[x+k][y+l] = dist[x][y] + 1
                    ans = max(ans, dist[x+k][y+l])
                    q.append((x+k, y+l))
print(ans)

Submission status: Accepted

Solution code:
h,w = map(int,input().split())
s = [input() for i in range(h)]
ans = 0
from collections import deque
for i in range(h):
    for j in range(w):
        if s[i][j]=='#':continue
        q = deque([(i,j)])
        reach = [[-1]*w for _ in range(h)]
        reach[i][j] = 0
        c = 0
        while q:
            x,y = q.popleft()
            for k,l in[[-1,0],[0,1],[1,0],[0,-1]]:
                if 0<=x+k<h and 0<=y+l<w:
                    if reach[x+k][y+l]<0 and s[x+k][y+l]=='.':
                        reach[x+k][y+l] = reach[x][y]+1
                        ans = max(ans,reach[x+k][y+l])
                        q.append((x+k,y+l))
            
print(ans)

Submission status: Accepted

Solution code:
def main():
    import numpy as np
    h,w = map(int,input().split())
    maize = []
    for i in range(h):
        s = input()
        maize.append(s)
    ans = 0
    for i in range(h):
        for j in range(w):
            que = [[i,j]]
            if maize[i][j] == '.':
                dis = [[-1 for i in range(w)] for i in range(h)]
                dis[i][j] = 0
                while len(que)>0:
                    q = que.pop(0)
                    if q[0]>0:
                        n = [q[0]-1,q[1]]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                    if q[0] < h-1:
                        n = [q[0]+1,q[1]]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                    if q[1] > 0:
                        n = [q[0],q[1]-1]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                    if q[1] < w-1:
                        n = [q[0],q[1]+1]
                        if maize[n[0]][n[1]]=='.':
                            if dis[n[0]][n[1]]==-1:
                                dis[n[0]][n[1]] = dis[q[0]][q[1]]+1
                                que.append(n)
                dis = np.array(dis)
                if np.max(dis)>ans:
                    ans = np.max(dis)
    print(ans)
    

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import deque
def main():
    H,W = map(int, input().split())
    S = [[0]*W for _ in range(H)]
    for i in range(H):
        # 1は道,0は壁
        tmp = list(map(lambda x:1 if x=='.' else 0, input()))
        S[i] = tmp
    # BFS
    ans = 0
    for i in range(H):
        for j in range(W):
            # (i,j)がスタート地点
            # (i,j)が壁
            if S[i][j] == 0:
                continue
            dist = [[-1]*W for _ in range(H)]
            dist[i][j] = 0
            que = deque([(i,j)])
            while que:
                si,sj = que.pop()
                for r,b in [(1,0),(0,1),(-1,0),(0,-1)]: # 右,下,左,上(移動方向)
                    gi = si+r
                    gj = sj+b
                    # 枠外
                    if gi<0 or (H-1)<gi or gj<0 or (W-1)<gj:
                        continue
                    # 壁
                    if S[gi][gj] == 0:
                        continue
                    # 探索済み
                    if dist[gi][gj]!=-1:
                        continue
                    dist[gi][gj] = dist[si][sj]+1
                    que.appendleft((gi,gj))
            ans = max(ans,max([max(d) for d in dist]))
    print(ans)

main()

Submission status: Accepted

Solution code:
from copy import deepcopy
from collections import deque
import sys

M = []
H = 0
W = 0
qx = deque()
qy = deque()
qc = deque()

def main():
    global M,H,W
    H,W = map(int, input().split())  
    for i in range(H):
        M.append(list(input()))

    startX = 0
    startY = 0
    mx = 0
    for i in range(H):
        for j in range(W):
            if M[i][j]=='.':
                rv =  bfs(i,j)
                if rv > mx:
                    mx = rv


    print(mx)

def bfs(y,x):
    global M,H,W
    Mtemp = deepcopy(M)
    Mtemp[y][x] = '#'
    qx.append(x)
    qy.append(y)
    qc.append(0)
    cnt = 0

    while len(qx) !=0:
        x =  qx.popleft()
        y =  qy.popleft()
        cnt = qc.popleft()

        if x-1>=0:
            if Mtemp[y][x-1] == '.':
                Mtemp[y][x-1] = '#'
                qx.append(x-1)
                qy.append(y)
                qc.append(cnt+1)
        if x+1<W:
            if Mtemp[y][x+1] == '.':
                Mtemp[y][x+1] = '#'
                qx.append(x+1)
                qy.append(y)
                qc.append(cnt+1)
        if y-1>=0:
            if Mtemp[y-1][x] == '.':
                Mtemp[y-1][x] = '#'
                qx.append(x)
                qy.append(y-1)
                qc.append(cnt+1)
        if y+1<H:
            if Mtemp[y+1][x] == '.':
                Mtemp[y+1][x] = '#'
                qx.append(x)
                qy.append(y+1)
                qc.append(cnt+1)

    return cnt




if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import copy
sys.setrecursionlimit(9**9)
H,W=map(int,input().split())
M=[list(input()) for _ in range(H)]
N=copy.deepcopy(M)
m=x=y=0
def d(c,P):
    global m,x,y
    Q=[]
    for p in P:
        h=p[0]
        w=p[1]
        if h!=H-1 and M[h+1][w]=='.':
            M[h+1][w]='#'
            Q.append([h+1,w])
        if h!=0 and M[h-1][w]=='.':
            M[h-1][w]='#'
            Q.append([h-1,w])
        if w!=W-1 and M[h][w+1]=='.':
            M[h][w+1]='#'
            Q.append([h,w+1])
        if w!=0 and M[h][w-1]=='.':
            M[h][w-1]='#'
            Q.append([h,w-1])
    if len(Q)!=0:
      c+=1
      return d(c,Q)
    else:
        m=max(m,c)
f=False
for i in range(H):
    for j in range(W):
        if M[i][j]=='.':
            M[i][j]='#'
            d(0,[[i,j]])
            M=copy.deepcopy(N)
print(m)

Submission status: Accepted

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

state = [[-1]*W for _ in range(H)]
start_list = []
for i in range(H):
    for j in range(W):
        if s[i][j] == '.':
            start_list.append((i,j))
            state[i][j] = 0

def dfs(black_cells,state):
    d = 0
    dist = [[0]*W for _ in range(H)]
    while black_cells:
        h, w =  black_cells.popleft()
        d = dist[h][w]
        for dy, dx in ((1,0), (0,1), (-1,0), (0,-1)):
            new_h = h+dy
            new_w = w+dx
            if new_h < 0 or H <= new_h or new_w < 0 or W <= new_w:
                continue
            if state[new_h][new_w] == 0 and dist[new_h][new_w] == 0:
                dist[new_h][new_w] = d+1
                if d == 0:dist[h][w] = 1
                black_cells.append((new_h, new_w))
    #print(dist)
    return np.array(dist).max()

ans = 0
for start in start_list:
    black_cells = deque()
    black_cells.append((start))
    ans = max(ans, dfs(black_cells,state))
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
H, W = [int(_) for _ in input().split()]
e = "#" * (W + 2)
maze = [e]
for i in range(H):
    s = input()
    maze.append("#" + s + "#")
maze.append(e)
max_count = 0
for h in range(H):
    for w in range(W):
        visited = [[False for i in range(W+2)] for j in range(H+2)]
        visited[h+1][w+1] = True
        if maze[h+1][w+1] == '#':
            continue
        q = deque([[w+1, h+1, 0]])
        def search(x, y, c):
            if maze[y][x] == '.' and not visited[y][x]:
                q.append([x, y, c+1])
                visited[y][x] = True
        count = 0
        while len(q) != 0:
            p = q.popleft()
            search(p[0]+1, p[1], p[2])
            search(p[0]-1, p[1], p[2])
            search(p[0], p[1]+1, p[2])
            search(p[0], p[1]-1, p[2])
            count = p[2]
        max_count = max(max_count, count)
print(max_count)

Submission status: Accepted

Solution code:
H, W = map(int, input().split())
s = [list(input()) for _ in range(H)]

INF = 10**9
di = [-1, 0, 1, 0]
dj = [0, -1, 0, 1]
def update(v, h, d, dist, q):
    if dist[W*v+h] != INF:
        return
    dist[W*v+h] = d
    q.append((v, h))

ans = 0
for si in range(H):
    for sj in range(W):
        if s[si][sj] == "#":
            continue
        dist = [INF]*H*W
        dist[W*si+sj] = 0
        q = [(si, sj)]
        while len(q) > 0:
            current = q.pop(0)
            v = current[0]
            h = current[1]
            for dir in range(4):
                ni = v+di[dir]
                nj = h+dj[dir]
                
                if ni<0 or H<=ni or nj<0 or W<= nj:
                    continue
                if s[ni][nj] == "#":
                    continue
                update(ni, nj, dist[W*v+h]+1,dist, q)
        for v in dist:
            if v == INF:
                continue
            ans = max(ans, v)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = lambda: sys.stdin.readline().rstrip()


def bfs(H, W, start, s):

    q = deque()
    q.append(start)
    d = [[-1 for _ in range(W)] for _ in range(H)]
    d[start[1]][start[0]] = 0
    move = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    while q:
        now = q.popleft()
        x, y = now
        for m in move:
            n_x, n_y = x + m[0], y + m[1]
            if (0 <= n_x and n_x < W) and (0 <= n_y and n_y < H):
                if d[n_y][n_x] == -1 and s[n_y][n_x] == '.':
                    d[n_y][n_x] = d[y][x] + 1
                    q.append((n_x, n_y))

    r = 0
    for t in d:
        r = max(r, max(t))

    return r


def solve():
    H, W = map(int, input().split())
    s = [list(input()) for _ in range(H)]

    ans = 0
    for x in range(W):
        for y in range(H):
            if s[y][x] == '.':
                start = (x, y)
                d = bfs(H, W, start, s)
                ans = max(ans, d)

    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
s = []
for _ in range(H):
    s.append(input())
dh = [0, 0, 1, -1]
dw = [1, -1, 0, 0]
ans = 0
for i in range(H):
    for j in range(W):
        if s[i][j] == "#":
            continue
        dismax = 0
        dist = [[-1 for j in range(W)] for i in range(H)]
        queue = deque([[i, j]])
        dist[i][j] = 0
        while len(queue) != 0:
            now = queue.popleft()
            h = now[0]
            w = now[1]
            for k in range(4):
                nh = h + dh[k]
                nw = w + dw[k]
                if nh < 0 or nw < 0 or nh >= H or nw >= W:
                    continue
                if dist[nh][nw] != -1 or s[nh][nw] == "#":
                    continue
                else:
                    dist[nh][nw] = dist[h][w] + 1
                    dismax = max(dist[nh][nw], dismax)
                    queue.append([nh, nw])
        ans = max(ans, dismax)
print(ans)

Submission status: Accepted

Solution code:

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
from collections import Counter,deque,defaultdict
import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
# from heapq import heapify,heappush,heappop

h,w=n1()
s=s4(h)
def make_around(s):
    sss=[[-1]*(w+2)]
    for line in s:
        sss.append([-1]+[-1 if i=="#" else 0 for i in line ]+[-1])
    sss.append([-1]*(w+2))
    return sss

s=make_around(s)
d=[]
for i in range(1,h+1):
    for j in range(1,w+1):
        if s[i][j]==0:
            d.append((i,j))

from copy import deepcopy
ans=0
for i in range(len(d)):
    ss=deepcopy(s)
    x,y=d[i]
    q=deque([(x,y)])
    ss[x][y]=1
    while len(q)>0:
        x,y=q.popleft()
        if ss[x+1][y]==0:
            ss[x+1][y]=ss[x][y]+1
            q.append((x+1,y))
        if ss[x-1][y]==0:
            ss[x-1][y]=ss[x][y]+1
            q.append((x-1,y))
        if ss[x][y+1]==0:
            ss[x][y+1]=ss[x][y]+1
            q.append((x,y+1))
        if ss[x][y-1]==0:
            ss[x][y-1]=ss[x][y]+1
            q.append((x,y-1))
    ans=max(ans,max(list(itertools.chain.from_iterable(ss))))
print(ans-1)

Submission status: Accepted

Solution code:

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
from collections import Counter,deque,defaultdict
import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
# from heapq import heapify,heappush,heappop

h,w=n1()
s=s4(h)
def make_around(s,h):
    sss=[[-1]*(w+2)]
    for line in s:
        sss.append([-1]+[-1 if i=="#" else 0 for i in line ]+[-1])
    sss.append([-1]*(w+2))
    return sss

s=make_around(s,h)
d=[]
for i in range(1,h+1):
    for j in range(1,w+1):
        if s[i][j]==0:
            d.append((i,j))

from copy import deepcopy
ans=0
for i in range(len(d)):
    ss=deepcopy(s)
    x,y=d[i]
    q=deque([(x,y)])
    ss[x][y]=1
    while len(q)>0:
        x,y=q.popleft()
        if ss[x+1][y]==0:
            ss[x+1][y]=ss[x][y]+1
            q.append((x+1,y))
        if ss[x-1][y]==0:
            ss[x-1][y]=ss[x][y]+1
            q.append((x-1,y))
        if ss[x][y+1]==0:
            ss[x][y+1]=ss[x][y]+1
            q.append((x,y+1))
        if ss[x][y-1]==0:
            ss[x][y-1]=ss[x][y]+1
            q.append((x,y-1))
    ans=max(ans,max(list(itertools.chain.from_iterable(ss))))
print(ans-1)

Submission status: Accepted

Solution code:
#bfs(両端キュー)
from collections import deque
import copy

h,w=map(int, input().split())
d=[list(input()) for i in range(h)]
inf=10**7

def bfs(sx,sy):
    a=copy.deepcopy(d)
    for i in range(h):
        for j in range(w):
            if a[i][j]=='.':
                a[i][j]=inf
    que=deque([[sy,sx]])
    a[sy][sx]=0

    while que:
        y,x=que.popleft()
        for i,j in [(1,0),(0,1),(-1,0),(0,-1)]:
            ny,nx=y+i,x+j
            if nx>=0 and nx<w and ny>=0 and ny<h:
                dist=a[ny][nx]
                if dist!='#':
                    if dist>a[y][x]+1:
                        a[ny][nx]=a[y][x]+1
                        que.append([ny,nx])

    m=0
    for i in range(h):
        for j in range(w):
            if a[i][j]!='#' and a[i][j]!=inf:
                if a[i][j]>m:
                    m=a[i][j]
    return m
    
# BFSのstartを決める
ans=0
for i in range(h):
    for j in range(w):
        if d[i][j]=='.':
            if ans<bfs(j,i):
                ans=bfs(j,i)
print(ans)