Рассчитать минимальное расстояние по прямой, используя BFS
Попытка решить эту проблему с помощью BFS.
Суть задачи: Начальная и конечная позиция дана для ладьи, помещенной в матрицу. Вам необходимо выяснить минимальное количество шагов, чтобы ладья достигла финальной позиции. Некоторые позиции, отмеченные знаком "X", не должны пересекаться, тогда как "." допустимые позиции.
Matrix:
.X.
.X.
...
source position: 0,0
target position: 0,2
answer:3 (0,0) -> (2,0) - > (2,2) -> (0,2)
Мое решение в основном делает следующее: я начинаю делать BFS с исходного узла, и после того, как я удаляю узел с узла, я добавляю все вертикальные и горизонтальные узлы в памяти с текущим расстоянием этого узла плюс 1. После этого я проверяю, является ли целевой узел присутствует в памяти, и если он присутствует, я возвращаю это расстояние.
Это решение ниже не работает в некоторых случаях. Какие-либо предложения?
def update_distance(memoize_dist, current, n, count, matrix):
directions = [1, -1, 1, -1]
current_x, current_y = current
temp_x, temp_y = current
for direction in directions:
while temp_x < n and temp_x >= 0:
temp_x += direction
temp = (temp_x, current_y)
if temp_x >= n or temp_x < 0 or matrix[temp_x][current_y] == 'X':
temp_x, temp_y = (current_x, current_y)
break
if temp not in memoize_dist.keys():
memoize_dist[temp] = count
for direction in directions:
while temp_y < n and temp_y >= 0:
temp_y += direction
temp = (current_x, temp_y)
if temp_y >= n or temp_y < 0 or matrix[current_x][temp_y] == 'X':
temp_x, temp_y = (current_x, current_y)
break
if temp not in memoize_dist.keys():
memoize_dist[temp] = count
def get_shortest(n, src, target, matrix):
queue, memoize, memoize_dist = [], {}, {}
queue.append((src[0], src[1], 0))
memoize_dist[(src[0], src[1])] = 0
while len(queue):
x, y, count = queue.pop(0)
cur = (x, y)
if cur in memoize.keys() and memoize[cur] != -1:
continue
memoize[cur] = 1
update_distance(memoize_dist, cur, n, count+1, matrix)
if target in memoize_dist.keys():
return memoize_dist[target]
directions = [1, -1, 1, -1]
for direction in directions:
if cur[0]+direction < n and cur[0]+direction >= 0 and matrix[cur[0]+direction][cur[1]] != 'X':
queue.append((cur[0]+direction, cur[1], memoize_dist[(cur[0]+direction, cur[1])]))
if cur[1]+direction < n and cur[1]+direction >= 0 and matrix[cur[0]][cur[1]+direction] != 'X':
queue.append((cur[0], cur[1]+direction, memoize_dist[(cur[0], cur[1]+direction)]))
n = int(input())
matrix = []
for i in range(n):
matrix.append(input())
start_x, start_y, dest_x, dest_y = map(int, input().split(" "))
print(get_shortest(n, (start_x, start_y), (dest_x, dest_y), matrix))