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 queue

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):
        if s[i][j] == ".":
            t = [["."]*w for _ in range(h)]
            t[i][j] = 0
            q = queue.Queue()
            q.put((j, i))
            while True:
                x, y = q.get()
                for k, l in (1, 0), (-1, 0), (0, 1), (0, -1):
                    if (0 <= x+k and x+k < w and
                        0 <= y+l and y+l < h and
                        s[y+l][x+k] == "." and t[y+l][x+k] == "."):
                            t[y+l][x+k] = t[y][x] + 1
                            q.put((x+k, y+l))
                            
                if q.empty():
                    ans = max(ans, t[y][x])
                    break
print(ans)

Submission status: Accepted

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


from collections import deque
def bfs(maze, dist, sy, sx):
    d = deque()
    d.append([sy, sx])
    while d:
        y, x = d.popleft()
        for dy, dx in [1, 0], [-1, 0], [0, 1], [0, -1]:
            ny = y + dy
            nx = x + dx
            if ny < 0 or ny >= H or nx < 0 or nx >= W:
                continue
            if maze[ny][nx] == '#':
                continue
            if dist[ny][nx] == -1:
                dist[ny][nx] = dist[y][x] + 1
                d.append([ny, nx])

ans = -1
for sy in range(H):
    for sx in range(W):
        if maze[sy][sx] == '#':
            continue
        dist = [[-1] * W for _ in range(H)]
        for gy in range(H):
            for gx in range(W):
                if maze[gy][gx] == '#':
                    continue
                dist[sy][sx] = 0
                bfs(maze, dist, sy, sx)
                ans = max(ans, dist[gy][gx])
print(ans)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
data=[]
data.append(list("#"*(w+2)))
for i in range(h):
    s=input()
    s="#"+s+"#"
    lists=list(s)
    data.append(lists)
data.append("#"*(w+2))
s=0
uselist=[]
graph={i:[] for i in range(1,h*w+1)}
for i in range(1,h+1):
    for j in range(1,w+1):
        if data[i][j]==".":
            a=w*(i-1)+j
            uselist.append(a)
            if data[i+1][j]==".":
                b=w*(i)+j
                graph[b].append(a)
                graph[a].append(b)

            if data[i][j+1]==".":
                b=w*(i-1)+j+1
                graph[b].append(a)
                graph[a].append(b)

from collections import deque

def how_far_from(s,n):
    d=deque()
#頂点sからどのくらいの距離にあるのかを返す関数
    parent=[0 for i in range(n+1)]
    visited=[False for i in range(n+1)]
    visited[s]=True
    d.append((s,0))

    how_far={i:[] for i in range(n+1)}
    while d:
        node=d.popleft()
        for point in graph[node[0]]:
            if visited[point]==False:
      
                visited[point]=True

                d.append((point,node[1]+1))
                how_far[node[1]+1].append(point)

    return how_far
maxi=0
for s in uselist:
    Q=how_far_from(s,h*w)

    for i in range(h*w,-1,-1):
        if Q[i]:
            maxi=max(maxi,i)
            break
print(maxi)

Submission status: Accepted

Solution code:
import queue
h,w = map(int,input().split())
maze_ = []
ans = 0
for _ in range(h):
    maze = list(input())
    maze_.append(maze)
for i in range(h):
    for j in range(w):
        if maze_[i][j] == ".":
            dist = [[-1]*w for i in range(h)]
            dist[i][j] = 0
            q = queue.Queue()
            q.put([i,j])
            while not q.empty():
                now = q.get()
                y = now[0]
                x = now[1]
                if x>0 and maze_[y][x-1] == "." and dist[y][x-1] == -1:
                    dist[y][x-1] = dist[y][x] + 1
                    q.put([y,x-1])
                if y>0 and maze_[y-1][x] == "." and dist[y-1][x] == -1:
                    dist[y-1][x] = dist[y][x] + 1
                    q.put([y-1,x])
                if x<w-1 and maze_[y][x+1] == "." and dist[y][x+1] == -1:
                    dist[y][x+1] = dist[y][x] + 1
                    q.put([y,x+1])
                if y<h-1 and maze_[y+1][x] == "." and dist[y+1][x] == -1:
                    dist[y+1][x] = dist[y][x] + 1
                    q.put([y+1,x])
            saidai = 0
            for s in range(h):
                for t in range(w):
                    saidai = max(saidai,dist[s][t])
            ans = max(ans,saidai)
print(ans)

Submission status: Accepted

Solution code:
H,W = map(int,input().split())
graph = [[i for i in input()] for j in range(H)]

def bfs(sx,sy):
  queue = [[sx,sy,0]]
  visited = [[False for i in range(W)] for j in range(H)]
  while queue:
    now = queue.pop(0)
    visited[now[0]][now[1]] = True
    for next in [[1,0],[-1,0],[0,1],[0,-1]]:
      if now[0]+next[0] < 0 or now[1]+next[1] < 0: continue
      if now[0]+next[0] > H-1 or now[1]+next[1] > W-1: continue
      if visited[now[0]+next[0]][now[1]+next[1]]: continue
      if graph[now[0]+next[0]][now[1]+next[1]]=='#': continue
      queue.append([now[0]+next[0],now[1]+next[1],now[2]+1])
      visited[now[0]+next[0]][now[1]+next[1]] = True
  return now[2]

ans = -1
for i in range(H):
  for j in range(W):
    if graph[i][j]=='#': continue
    ans = max(ans,bfs(i,j))
    
print(ans)

Submission status: Accepted

Solution code:
from collections import deque
inf = -1

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

def bfs(sx,sy):
    d = [[inf] * w for _ in range(h)]
    que = deque()
    que.append([sx,sy])
    d[sx][sy] = 0
    while que:
        p = que.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != '#' and d[nx][ny] == inf:
                que.append([nx,ny])
                d[nx][ny] = d[p[0]][p[1]] + 1
    cnt = 0
    for i in range(h):
        for j in range(w):
            cnt = max(cnt, d[i][j])
    return cnt

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

Submission status: Accepted

Solution code:
from collections import deque

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


def bfs(x, y):
    d = [[-1] * w for _ in range(h)]
    q = deque()
    q.append([x, y])
    d[x][y] = 0
    while q:
        p = q.popleft()
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != '#' and d[nx][
                    ny] == -1:
                q.append([nx, ny])
                d[nx][ny] = d[p[0]][p[1]] + 1
    cnt = 0
    for i in range(h):
        for j in range(w):
            cnt = max(cnt, d[i][j])
    return cnt


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

Submission status: Accepted

Solution code:
import collections
from collections import deque

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

# 枠を囲う
for i in range(h):
    maze[i]=['#']+maze[i]+['#']
maze=[['#' for i in range(w+2)]]+maze+[['#' for i in range(w+2)]]

def clear_maze(sx, sy):

    INF=-10**9
    distance = [[INF for i in range(w+2)] for j in range(h+2)]
    #    distance = [[None]*field_x_length]*field_y_length
    def bfs():
        d = deque()
        d.append((sx, sy))
        distance[sx][sy] = 0
        ans=0

        while len(d):
            x, y = d.popleft()

            for i in range(0, 4):
                nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i]

                if (0 <= nx and  0 <= ny  and maze[nx][ny] != '#' and distance[nx][ny] == INF):
                    d.append((nx, ny))
                    distance[nx][ny] = distance[x][y] + 1
                    ans=max(distance[nx][ny],ans)


        return ans

    return bfs()

m=0
for i in range(1,h+1):
    for j in range(1,w+1):
        if maze[i][j] == '.':
            x=clear_maze(i,j)
            m=max(x,m)
print(m)

Submission status: Accepted

Solution code:
h,w=map(int,input().split())
s=[input() for _ in range(h)]
from collections import deque
ans=0
dd=[(1,0),(-1,0),(0,1),(0,-1)]
for i in range(h):
  for j in range(w):
    if  s[i][j]=="#":
          continue
    
    g=[[0]*w for _ in range(h)]
    v=[[0]*w for _ in range(h)]
    g[i][j]=1
    q=deque([(j,i)])
    while q:
      x,y=q.popleft()
      for dx,dy in dd:
        nx=x+dx
        ny=y+dy
        if not 0<=nx<w:
          continue
        if not 0<=ny<h:
          continue
        if g[ny][nx]:
          continue
        if s[ny][nx]=="#":
          continue
        g[ny][nx]=1
        v[ny][nx]=v[y][x]+1
        q.append((nx,ny))
    for ii in v:
      ans=max(ans,max(ii))

print(ans)

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
G=[["#"]*(w+2) for i in range(h+2)]
for i in range(1,h+1):
  G[i]=["#"]+list(input())+["#"]
ans=0
for sx in range(1,h+1):
  for sy in range(1,w+1):
    if G[sx][sy]==".":
      B=[[0]*(w+2) for i in range(h+2)]
      for i in range(h+2):
        for j in range(w+2):
          if G[i][j]=="#":
            B[i][j]=1
      INF=10**4
      A=[[INF]*(w+2) for i in range(h+2)]
      C=[-1,1,0,0]
      D=[0,0,-1,1]
      A[sx][sy]=0
      E=deque([sx,sy])
      while len(E)>0:
        x=E[0]
        E.popleft()
        y=E[0]
        E.popleft()
        B[x][y]=1
        for i in range(4):
          if B[x+C[i]][y+D[i]]==0:
            A[x+C[i]][y+D[i]]=A[x][y]+1
            a=A[x+C[i]][y+D[i]]
            B[x+C[i]][y+D[i]]=1
            E.append(x+C[i])
            E.append(y+D[i])
      if ans<a:
        ans=a
    else:
      continue
print(ans)

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)]

def bfs(s, start_x, start_y, h, w):
    que = deque()
    que.append((start_x, start_y))
    
    d = [[-1]*w for i in range(h)]
    d[start_y][start_x] = 0
    
    while que:
        (x, y) = que.popleft()
        for (nx, ny) in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
            if 0 <= nx and nx<w and 0<=ny and ny<h and s[ny][nx]!='#' and d[ny][nx]==-1:
                que.append((nx, ny))
                d[ny][nx] = d[y][x] + 1
                
    answer = 0    
    for i in range(h):
        for j in range(w):
            answer = max(answer, d[i][j])
                        
    return answer

answer = 0
for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            new_answer = bfs(s, j, i, h, w)
            answer = max(new_answer, answer) 
            
print(answer)

Submission status: Accepted

Solution code:
from collections import deque

def bfs(h,w,s,sx,sy):
    dx = [1,0,-1,0]
    dy = [0,1,0,-1]
    d = [[-1] * w for _ in range(h)]
    d[sx][sy] = 0
    que = deque()
    que.append((sx,sy))
    
    while que:
        x,y = que.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != '#' and d[nx][ny] == -1:
                que.append((nx,ny))
                d[nx][ny] = d[x][y] + 1
    
    md = 0
    for i in range(h):
        for j in range(w):
            md = max(md,d[i][j])
    return md

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

for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            ans = max(ans,bfs(h,w,s,i,j))
            
print(ans)

Submission status: Accepted

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


def BFS(x, y, M):
    dist = [[-1] * W for i in range(H)]
    quex = deque([x])
    quey = deque([y])
    dist[x][y] = 0

    while quex:
        vx = quex.popleft()
        vy = quey.popleft()
        d = dist[vx][vy]
        for w in D:
            nx = w[0] + vx
            ny = w[1] + vy
            if nx < 0 or H <= nx or ny < 0 or W <= ny:
                continue
            elif dist[nx][ny] > -1 or S[nx][ny] == "#":
                continue
            dist[nx][ny] = d + 1
            M = max(M, d+1)
            quex.append(nx)
            quey.append(ny)

    return M


M = 0
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            M = BFS(i, j, M)
print(M)

Submission status: Accepted

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

V = H*W
maze = [[INF]*V for _ in range(V)]

#隣接行列（対角成分）
for i in range(V):
    maze[i][i] = 0

#隣接行列（経路があれば1）
for py in range(H):
    for px in range(W):
        if s[py][px] == '#': continue
        target = [(px+1, py), (px-1, py), (px, py+1), (px, py-1)]
        for x, y in target:
            if not (0<=x<W and 0<=y<H): continue
            if s[y][x] == '#': continue
            maze[W*py+px][W*y+x] = 1

#ワーシャル・フロイド
for k in range(V):
    for i in range(V):
        for j in range(V):
            maze[i][j] = min(maze[i][j], maze[i][k]+maze[k][j])

print(max([j for i in maze for j in i if j!=INF]))

Submission status: Accepted

Solution code:
from collections import deque
 
def bfs(h, w, s, sx, sy):
    dx = [1, 0, -1, 0]
    dy = [0, 1, 0, -1]
    d = [[-1] * w for _ in range(h)]
    d[sx][sy] = 0
    que = deque()
    que.append((sx, sy))
 
    while que:
        x, y = que.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < h and 0 <= ny < w and s[nx][ny] != '#' and d[nx][ny] == -1:
                que.append((nx, ny))
                d[nx][ny] = d[x][y] + 1
 
    md = 0
    for i in range(h):
        for j in range(w):
          md = max(md, d[i][j])
 
    return md
 
h, w = [int(_) for _ in input().split()]
s = [0] * h
for i in range(h):
    s[i] = list(input())
 
ans = 0
 
for i in range(h):
    for j in range(w):
        if s[i][j] == '.':
            ans = max(ans, bfs(h, w, s, i, j))
 
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

def bfs(sy,sx):
    dist[sy][sx]=0
    q=deque([[sy,sx]])
    while q:
        cy,cx=q.popleft()
        for i,j in ([1,0],[-1,0],[0,1],[0,-1]):
            ny,nx=cy+i,cx+j
            if ny<0 or h-1<ny or nx<0 or w-1<nx or path[ny][nx]=='#':continue
            if path[ny][nx]=='.' and dist[ny][nx]==-1:
                dist[ny][nx]=dist[cy][cx]+1
                q.append([ny,nx])
    max_dist=-1
    for i in range(h):
        for j in range(w):
            if path[i][j]=='#':continue
            max_dist=max(max_dist,dist[i][j])
    return max_dist

h,w=map(int,input().split())
path=[input() for i in range(h)]
ans=0
for i in range(h):
    for j in range(w):
        if path[i][j]=='#':
            continue
        dist=[[-1]*w for i in range(h)]
        t=bfs(i,j)
        ans=max(ans,t)
print(ans)

Submission status: Accepted

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

#迷路と始点を引数に、最も遠い点までの距離を返す
def bfs(maze, sx, sy):
    d = [[-float("inf")] * w for i in range(h)]

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

    que = deque([])
    que.append((sy, sx))
    d[sy][sx] = 0

    while que:
        p = que.popleft()
        # if p[0] == gy and p[1] == gx:
        #     break
        for i in range(4):
            nx = p[0] + dx[i]
            ny = p[1] + dy[i]
            if 0 <= nx < h and 0 <= ny < w and maze[nx][ny] != "#" and d[nx][ny] == -float("inf"):
                que.append((nx, ny))
                d[nx][ny] = d[p[0]][p[1]] + 1
    an = 0
    for i in d:
        an = max(an,max(i))
    return an

# 取りうる全ての始点と終点の最短経路の最大値を求める
ans = 0
for i in range(h):
    for j in range(w):
        if maze[i][j]!="#":
            ans = max(ans, bfs(maze, j, i))

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
read = sys.stdin.buffer.read 
input = sys.stdin.buffer.readline
def inputS(): return input().rstrip().decode()
readlines = sys.stdin.buffer.readlines 

from collections import deque

def bfs(grid, start):
  dist = [[-1]*(W+2) for _ in range(H+2)]
  queue = deque([start])
  dist[start[0]][start[1]] = 0
  while queue:
    x, y = queue.popleft()
    
    for i, j in ((1, 0), (-1, 0), (0, 1), (0, -1)):
      nx, ny = x+i, y+j
      if grid[nx][ny] == "." and dist[nx][ny] == -1:
        dist[nx][ny] = dist[x][y]+1
        queue.append((nx, ny))
    if not queue:
      return dist[x][y]
    
H, W = map(int, input().split())
# 番兵
grid = [["#"] + list(inputS()) + ["#"] for _ in range(H)]
grid = ["#"*(W+2)] + grid + ["#"*(W+2)] # 上下に番兵

ans = 0
for i in range(1, H+1):
  for j in range(1, W+1):
    if grid[i][j] == "#":
      continue
    ans = max(ans, bfs(grid, (i, j)))  
    
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

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

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

def bfs(i,j): # 幅優先探索、マス i,j から始まる時の最長経路
    if S[i][j] == '#': # そのマスが壁ならスタート地点にならないのでパス
        return 0
    
    visited=[[0]*w for _ in range(h)] # 探索済のリスト
    visited[i][j]=1 # 最初のマスは探索済へ
    
    que=deque([(i,j,0)]) # キュー（queueは待ち行列）,各マスの情報をタプルにしてる
    
    while len(que)>0:
        ci,cj,d = que.popleft() #キューの左側から取り出してキューから削除

        for mi,mj in move: #moveで定義したそれぞれの動きについて
            ni,nj = ci+mi,cj+mj # 移動先の座標をni,njとしている。
            if 0 <= ni < h and 0 <= nj < w and visited[ni][nj]==0:
                if S[ni][nj] == '.':
                    visited[ni][nj] = 1
                    que.append((ni, nj, d+1))
    return d
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:
#python3
from collections import deque         
INF = int(1e9)
dd = [(-1, 0), (1, 0), (0, 1), (0, -1)]

def main():
    h, w = map(int, input().split())
    maze = [input() for _ in range(h)]
    ans = -1 
    
    for i in range(h):
        for j in range(w):
            if maze[i][j] == '#':
                continue
            g = [[INF for _ in range(w)] for _ in range(h)] 
            q = deque()
            q.append((i, j))
            g[i][j] = 0
            while len(q) > 0:
                pi, pj = q.popleft()
                for dx, dy in dd:
                    x = pi + dx
                    y = pj + dy
                    if (x < 0) | (y < 0) | (x >= h) | (y >= w): 
                        continue
                    if maze[x][y] == '#':
                        continue
                    if g[x][y] != INF:
                        continue
                    q.append((x, y))
                    g[x][y] = g[pi][pj]+1 
            

            for k in range(h):
                for l in range(w):
                    if g[k][l] == INF:
                        continue
                    ans = max(ans, g[k][l])
    print(ans)
main()

Submission status: Accepted

Solution code:
import math
import fractions
import bisect
import collections
import itertools
import heapq
import string
import sys
import copy
from collections import deque
sys.setrecursionlimit(10**7)
MOD = 10**9+7
def gcd(a,b):return fractions.gcd(a,b) #最大公約数
def lcm(a,b):return (a*b) // fractions.gcd(a,b) #最小公倍数
def iin(): return int(input()) #整数読み込み
def ifn(): return float(input()) #浮動小数点読み込み
def isn(): return input().split() #文字列読み込み
def imn(): return map(int, input().split()) #整数map取得
def fmn(): return map(float, input().split()) #浮動小数点map取得
def iln(): return list(map(int, input().split())) #整数リスト取得
def iln_s(): return sorted(iln()) # 昇順の整数リスト取得
def iln_r(): return sorted(iln(), reverse=True) # 降順の整数リスト取得
def fln(): return list(map(float, input().split())) # 浮動小数点リスト取得
def join(l, s=''): return s.join(l) #リストを文字列に変換
def perm(l, n): return itertools.permutations(l, n) # 順列取得
def perm_count(n, r): return math.factorial(n) // math.factorial(n-r) # 順列の総数
def comb(l, n): return itertools.combinations(l, n) # 組み合わせ取得
def comb_count(n, r): return math.factorial(n) // (math.factorial(n-r) * math.factorial(r)) #組み合わせの総数
def two_distance(a, b, c, d): return ((c-a)**2 + (d-b)**2)**.5 # 2点間の距離
def m_add(a,b): return (a+b) % MOD

def sieves_of_e(n):
    is_prime = [True] * (n+1)
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2, int(n**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i * 2, n+1, i): is_prime[j] = False
    return is_prime


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

for h in range(H):
    for w in range(W):
        if S[h][w] == '#': continue
        d = [[-1 for _ in range(W)] for _ in range(H)]
        d[h][w] = 0
        max_s = 0
        queue = deque([(w, h)])
        while len(queue) > 0:
            p = queue.popleft()
            for i in range(4):
                x = p[0] + dx[i]
                y = p[1] + dy[i]
                if x < 0 or y < 0 or x >= W or y >= H or S[y][x] == '#' or d[y][x] != -1: continue
                d[y][x] = d[p[1]][p[0]] + 1
                queue.append((x,y))
                max_s = max(max_s, d[y][x])
        ans = max(ans, max_s)
print(ans)

Submission status: Accepted

Solution code:
from collections import deque

H, W = map(int, input().split())
#print("H={}, W={}".format(H, W))
S = [list(input()) for _ in range(H)] # input().split()だと分割されない！！！
#print(S)

def maxCost(s0, s1):
    """
    (s0, s1)から任意の道に最短経路で移動するとして、その中での最大コストを算出する
    """
    maxCost = 0
    visited = [[10**9 for _ in range(W)] for _ in range(H)] # そのマスへの移動の最小コスト
    q = deque([(s0, s1, 0)])
    visited[s0][s1] = 0

    while q:
        u0, u1, cost = q.popleft()
        #print("({}, {}), cost={}".format(u0, u1, cost))
        if u0 < H - 1 and S[u0+1][u1] == "." and visited[u0+1][u1] > cost+1:
            #print("first")
            visited[u0+1][u1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0+1, u1, cost+1))
        if u0 > 0 and S[u0-1][u1] == "." and visited[u0-1][u1] > cost+1:
            #print("second")
            visited[u0-1][u1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0-1, u1, cost+1))
        if u1 < W - 1 and S[u0][u1+1] == "." and visited[u0][u1+1] > cost+1:
            #print("third")
            visited[u0][u1+1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0, u1+1, cost+1))
        if u1 > 0 and S[u0][u1-1] == "." and visited[u0][u1-1] > cost+1:
            #print("fourth")
            visited[u0][u1-1] = cost+1
            maxCost = max(maxCost, cost+1)
            q.append((u0, u1-1, cost+1))

    return maxCost

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

Submission status: Accepted

Solution code:
import sys
import math
from math import sqrt
from collections import deque
input=lambda: sys.stdin.readline().strip()
sys.setrecursionlimit(11451419)

h,w=map(int,input().split())
miti=[]
for i in range(h):
    miti.append(input())
    

def bfs(x,y):
    for i,j in [[x+1,y],[x,y+1],[x-1,y],[x,y-1]]:
        if i<0 or h<=i or j<0 or w<=j :continue
        if dist[i][j] != -1:continue
        if miti[i][j]=="#":continue
        dist[i][j]=dist[x][y]+1
        queue.append([i,j])
    while queue:
        t,r=queue.popleft()
        bfs(t,r)
ans=0
for i in range(h):
    for j in range(w):
        if miti[i][j]=="#":continue
        dist=[[-1 for i in range(w)] for j in range(h)]
        dist[i][j]=0
        queue=deque([])
        bfs(i,j)
        
        
        for s in range(h):
            for t in range(w):
                ans=max(ans,dist[s][t])
print(ans)

Submission status: Accepted

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def build_grid(H, W, intv, _type, space=True, padding=False):
    # 入力がスペース区切りかどうか
    if space:
        _input = lambda: input().split()
    else:
        _input = lambda: input()
    _list = lambda: list(map(_type, _input()))
    # 余白の有無
    if padding:
        offset = 1
    else:
        offset = 0
    grid = list2d(H+offset*2, W+offset*2, intv)
    for i in range(offset, H+offset):
        row = _list()
        for j in range(offset, W+offset):
            grid[i][j] = row[j-offset]
    return grid

def bfs(grid, src):
    """ BFS(グリッド、重みなし) """
    from collections import deque

    H, W = len(grid), len(grid[0])
    h, w = src
    directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
    que = deque([(h, w, 0)])
    dist = list2d(H+2, W+2, -1)
    while que:
        h, w, c = que.popleft()
        if dist[h][w] != -1:
            continue
        dist[h][w] = c
        for dh, dw in directions:
            h2 = h + dh
            w2 = w + dw
            if grid[h2][w2] == '#':
                continue
            que.append((h2, w2, c+1))
    return dist

H, W = MAP()
grid = build_grid(H, W, '#', str, space=0, padding=1)

ans = 0
for i in range(1, H+1):
    for j in range(1, W+1):
        if grid[i][j] != '#':
            # 有効な全マスから最短距離試す
            res = bfs(grid, (i, j))
            for k in range(1, H+1):
                for l in range(1, W+1):
                    # 一番遠い場所
                    ans = max(ans, res[k][l])
print(ans)

Submission status: Accepted

Solution code:
#縦がx，横がy

from collections import deque

H, W = map(int, input().split())
S = []
maxlen = 0

for _ in range(H):
    S.append(input())

#i,jはスタートする場所，x,yはi,jスタートで現在どこにいるか．
#i2,j2は四近傍，new_x,new_yは次に移動する場所
for i in range(H):
    for j in range(W):
        if S[i][j] == ".":
            queue = deque([[i,j]])
            distance = [[-1]*W for _ in range(H)]
            distance[i][j] = 0
            mazemax = 0
            #print()
            while len(queue): #queueが無くなるまで
                #print(*distance,sep="\n",end="\n")
                x, y = queue.popleft()
                for i2, j2 in ([1, 0], [-1, 0], [0, 1], [0, -1]): #四方向を見る
                    new_x, new_y = x+i2, y+j2
                    if new_x < 0 or new_x >= H or new_y < 0 or new_y >= W: #範囲外を飛ばす
                        continue
                    elif S[new_x][new_y] == "." and distance[new_x][new_y] == -1:
                        distance[new_x][new_y] = max(distance[new_x][new_y], distance[x][y] + 1)
                        mazemax = max(mazemax, distance[new_x][new_y])
                        queue.append([new_x, new_y])
                if len(queue) == 0:
                    maxlen = max(maxlen,mazemax)

print(maxlen)

"""
5 5
...#.
.#.#.
...#.
#.##.
#....
"""

Submission status: Accepted

Solution code:
from collections import deque
h,w=map(int,input().split())
S=[input() for _ in range(h)]
inf=float("inf")
ans=0
for i in range(h):
   for j in range(w):
      if S[i][j]!="#":
         dp=[[inf for _ in range(w)]for _ in range(h)]
         dp[i][j]=0
         que=deque([(i,j)])
         while que:
            si,sj=que.popleft()
            for ni,nj in [(si+1,sj),(si-1,sj),(si,sj+1),(si,sj-1)]:
               if 0<=ni<h and 0<=nj<w and S[ni][nj]!="#":
                  if dp[ni][nj]>dp[si][sj]+1:
                     dp[ni][nj]=dp[si][sj]+1
                     que.append((ni,nj))
                     ans=max(ans,dp[si][sj]+1)
print(ans)

Submission status: Accepted

Solution code:
R,C = map(int,input().split())
graph = [[i for i in input()] for j in range(R)]
visited = [[False for i in range(C)] for j in range(R)]

def dfs(start_y,start_x):
  queue = [[start_y,start_x,0]]
  while queue:
    now = queue.pop(0)
    visited[now[0]][now[1]] = True
    for next in [[1,0],[-1,0],[0,1],[0,-1]]:
      if now[0]+next[0] < 0 or now[1]+next[1] < 0: continue
      if now[0]+next[0] > R-1 or now[1]+next[1] > C-1: continue
      if visited[now[0]+next[0]][now[1]+next[1]]: continue
      if graph[now[0]+next[0]][now[1]+next[1]]=='#': continue
      queue.append([now[0]+next[0],now[1]+next[1],now[2]+1])
      visited[now[0]+next[0]][now[1]+next[1]] = True
  return now[2]

ans = 0
for row_s in range(R):
  for column_s in range(C):
      if graph[row_s][column_s]=='#': continue
      visited = [[False for i in range(C)] for j in range(R)]
      ans = max(ans,dfs(row_s,column_s))
    
print(ans)