問題
ポイント
解法
def C_BFS(R, C, sy, sx, gy, gx, c):
"""
R:行数
C:列数
sy,sx:スタートの座標(sy行sx列)
gy,gx:ゴールの座標(gy行gx列)
c:迷路の形状(.:通路,#:壁)
"""
INF = float('inf')
sy -= 1
sx -= 1
gy -= 1
gx -= 1
def bfs(maze, row, column, sy, sx, gy, gx):
queue = []
queue.insert(0, (sy, sx))
dist = [[INF for _ in range(column)] for _ in range(row)]
dist[sy][sx] = 0
dist_max = 0
while len(queue):
y, x = queue.pop()
for i in range(4):
nx, ny = x + [1, 0, -1, 0][i], y + \
[0, 1, 0, -1][i]
if 0 <= nx and nx < column and 0 <= ny and ny < row \
and maze[ny][nx] != '#' and dist[ny][nx] == INF:
queue.insert(0, (ny, nx))
dist[ny][nx] = dist[y][x] + 1
if dist_max < dist[ny][nx]:
dist_max = dist[ny][nx]
return dist_max
maze = [['' for _ in range(C)] for _ in range(R)]
for i, tmp in enumerate(c):
for j in range(C):
maze[i][j] = tmp[j]
ans = bfs(maze, R, C, sy, sx, gy, gx)
return ans
R , C = [int(i) for i in input().split()]
c = [input() for _ in range(R)]
dist_ans = 0
for sy in range(1, R+1):
for sx in range(1, C+1):
if c[sy-1][sx-1] != '#':
dist_tmp = C_BFS(R, C, sy, sx, 1, 1, c)
if dist_ans < dist_tmp:
dist_ans = dist_tmp
print(dist_ans)
感想