Mam labirynt i muszę go przejść (nieistotna liczba kroków), ale wpadam w pętlę i nie wiem jak z niej wyjść. Pomoże ktoś?
Kod w pythonie i załączone zdjęcie labiryntu:
board = [
[1 for i in range(8)],
[1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1],
[1 for i in range(8)]
]
soul = [3, 0] # row, column
end = [5, 7] # row, column
direction = 1 # n = 0, e = 1, s = 2, w = 3
path = []
while soul != end:
if board[soul[0] - 1][soul[1]] == 0 and direction == 0:
soul[0] -= 1
path.append('n')
elif board[soul[0]][soul[1] + 1] == 0 and direction == 1:
soul[1] += 1
path.append('e')
elif board[soul[0] + 1][soul[1]] == 0 and direction == 2:
soul[0] += 1
path.append('s')
elif board[soul[0]][soul[1] - 1] == 0 and direction == 3:
soul[1] -= 1
path.append('w')
print(path)
if board[soul[0] - 1][soul[1]] == 1 and direction == 0:
direction = 1
elif board[soul[0]][soul[1] + 1] == 1 and direction == 1:
direction = 2
elif board[soul[0] + 1][soul[1]] == 1 and direction == 2:
direction = 3
elif board[soul[0]][soul[1] - 1] == 1 and direction == 3:
direction = 0
[1 for i in range(8)],
[1, 0, 0, 0, 1, 0, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 1, 0, 1, 0, 1, 1],
[1, 0, 1, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1],
[1 for i in range(8)]
]
soul = [3, 0] # wiersz, kolumna
end = [5, 7] # wiersz, kolumna
direction = 1 # n = 0, e = 1, s = 2, w = 3
path = []
def can_move(direction):
if direction == 0:
return board[soul[0] - 1][soul[1]] == 0
elif direction == 1:
return board[soul[0]][soul[1] + 1] == 0
elif direction == 2:
return board[soul[0] + 1][soul[1]] == 0
elif direction == 3:
return board[soul[0]][soul[1] - 1] == 0
while soul != end:
moved = False
for _ in range(4):
if can_move(direction):
if direction == 0:
soul[0] -= 1
path.append('n')
elif direction == 1:
soul[1] += 1
path.append('e')
elif direction == 2:
soul[0] += 1
path.append('s')
elif direction == 3:
soul[1] -= 1
path.append('w')
moved = True
break
direction = (direction + 1) % 4
if not moved:
break
if soul == end:
print("Znaleziono wyjście.")
print("Ścieżka: ", path)
else:
print("Nie znaleziono wyjścia.")
Zmień kod na ten i powinno być cacy