Python广度优先搜索矩阵打印路径

标签 python matrix stack breadth-first-search

我有这行代码,用于测试在由矩阵表示的迷宫中是否可以找到一条路径。在确定是否存在路径后,如何在末尾打印路径。我尝试过做一个堆栈,但我不知道如何继续。

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.")

这是一个示例矩阵:

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

最佳答案

因为你是用BFS找路径,所以最终的逼近不可能是从起点到终点的最短路径,实际上你只能得到哪一点与起点相连的结果。

因此,要获得精确路径,可以使用 DFS 查找路径并使用堆栈保存访问过的点,或者使用 Dijkstra 查找从起点到终点的最短路径。

这是一个简单的 DFS 函数,它使用递归,路径用字符 2 表示

suc = 0

def dfs(row, col):
    global suc
    if suc == 1:
        return
    matrix[row][col] = "2"

    if (row, col) == (numrows - 1, numcols - 1):
        print("Success")
        suc = 1

    if col + 1 < numcols and matrix[row][col + 1] == "0":
        dfs(row, col + 1)

    if row + 1 < numrows and matrix[row + 1][col] == "0":
        dfs(row + 1, col)

    if 0 <= col - 1 and matrix[row][col - 1] == "0":
        dfs(row, col - 1)

    if 0 <= row - 1 and matrix[row - 1][col] == "0":
        dfs(row - 1, col)


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

dfs(0, 0)

var = matrix[numrows - 1][numcols - 1]

for m in matrix:
    print(m)

if var == "0":
    print("There is no path.")
else:
    print("There is a path.")

关于Python广度优先搜索矩阵打印路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177795/

相关文章:

c++ - CUDA 卷积 - 不可分离内核

c++ - 使用导致段错误的类在 C++ 中实现堆栈

java - 将字符串表达式计算为整数?

html - 相互堆叠的 div 标签

python - 论文 "Deep inside convolutional networks: Visualising image classification models and saliency maps"的实现,Simonyan 等人

c# - 如何找到给定方向向量和向上向量的 x、y 和 z 旋转角度?

python - Django - 根据用户组显示/隐藏基本 html 中的 url?

python - 大型 numpy 矩阵内存问题

python - 如何使用python计算数据框中特定行值之间的时间差?

python - os.path.join() 和 os.path.normpath() 都在 Windows 上添加双反斜杠