Python breadth-first search matrix print path

前端 未结 3 1861
深忆病人
深忆病人 2021-01-23 23:16

I have this line of code that tests wether or not there is a path to be found in a labyrinth represented by a matrix. How do I print the path at the end after I\'ve determined w

3条回答
  •  一个人的身影
    2021-01-24 00:01

    Because you are using BFS to find the path, the final approach cannot be the shortest path from the start point to the finish point, and actually, you can only get the result that which point is connected to the start point.

    So, to get an exact path, you may use DFS to find a path and use a stack to save the points visited or use Dijkstra to find the shortest path from the start point to the finish point.

    Here is a simple DFS function which uses recursion and the path is represented in character 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.")
    

提交回复
热议问题