Ich habe diese Codezeile, die testet, ob es einen Pfad in einem Labyrinth gibt, das durch eine Matrix repräsentiert wird. Wie drucke ich den Pfad am Ende, nachdem ich festgestellt habe, ob es einen Pfad gibt oder nicht. Ich habe versucht, einen Stapel zu machen, aber ich bin mir nicht sicher, wie es weitergehen soll. Python Breite-erste Suche Matrix Druckpfad
from queue import Queue
maze=open(input())
matrix=maze.readlines()
matrix=[i.strip() for i in matrix]
matrix=[i.split() for i in matrix]
numrows, numcols = len(matrix), len(matrix[0])
q=Queue()
row=0
col=0
q.put((row,col))
while not q.empty():
row, col = q.get()
if col+1 < numcols and matrix[row][col+1] == "0":
q.put((row, col+1))
matrix[row][col+1] = "2"
if row+1 < numrows and matrix[row+1][col] == "0":
q.put((row+1, col))
matrix[row+1][col] = "3"
if 0 <= col-1 and matrix[row][col-1] == "0":
q.put((row, col-1))
matrix[row][col-1] = "4"
if 0 <= row-1 and matrix[row-1][col] == "0":
q.put((row-1, col))
matrix[row-1][col] = "5"
row,col=numrows-1,numcols-1
var=matrix[row][col]
if var=="0":
print ("There is no path.")
else:
print ("There is a path.")
Hier ist eine Probenmatrix:
0 0 0 0 1 0 0 0
0 1 1 0 1 0 1 0
0 1 0 0 1 0 1 0
0 0 0 1 0 0 1 0
0 1 0 1 0 1 1 0
0 0 1 1 0 1 0 0
1 0 0 0 0 1 1 0
0 0 1 1 1 1 0 0
Mögliches Duplikat von [Wie funktioniert eine Breitensuche bei der Suche nach dem kürzesten Pfad?] (Https://stackoverflow.com/questions/8379785/how-does-a-breathth-first-search-work-when -Suche nach dem kürzesten Pfad) – alfasin
@ PM2Ring Dies ist eine breite erste Suche, es findet den kürzesten Pfad. – Arne
@ArneRecknagel Danke für diese Info. Es ist lange her, seit ich die Graphentheorie studiert habe. ;) –