简体   繁体   English

Python,Dijkstra 算法可视化

[英]Python, Dijkstra's Algorithm visualization

I'm trying to visualize Dijkstra's Algorithm in python where each node is a square - see picture below.我正在尝试在 python 中可视化 Dijkstra 算法,其中每个节点都是一个正方形 - 请参见下图。 but something feels a bit off.但感觉有点不对劲。 I compared the result of the shortest path with standard A* and im not getting exactly the same path.我将最短路径的结果与标准 A* 进行了比较,但我没有得到完全相同的路径。 I think my code is off but I don't realize how exactly.我认为我的代码已关闭,但我不知道具体情况如何。

I'm using PriorityQueue我正在使用 PriorityQueue

grid is a List of lists of objects -网格是对象列表的列表 -

each object represents a cube on the screen-每个 object 代表屏幕上的一个立方体 -

draw - draws the grid onto screen draw - 将网格绘制到屏幕上

the code inside ** -code- ** is the part I edited after posting the question. ** -code- ** 中的代码是我在发布问题后编辑的部分。


def dijkstra_algorithm(grid, start, end):
    # set up dist (distance to start) with infinity
    dist = {elem: float("inf") for row in grid for elem in row}

    # distance from start to start is 0.
    dist[start] = 0

    # set up prev dict - prev[V] = U - represents that the shortest current path to X is through U
    prev = {}

    # create Priority Queue based on distance from origin and insert start to PQ
    PQ = PriorityQueue()
    counter = 0
    # create hash table to check if element is inside PQ.
    PQ.put((0, counter, start))
    PQ_hash = {start}

    # insert every elem except start into PQ with distance infinity
    for row in grid:
        for elem in row:
            if elem != start:
                PQ.put((dist[elem],**float("inf")**, elem))
                PQ_hash.add(elem)


    # iterate untill PQ is empty
    while not PQ.empty():
        

        current = PQ.get()[1]  # get element with min distance - index 1 in (dist[elem], elem)

        # if what's left is infinitly far - there is no path from start to end
        if dist[current] == float('inf'):
            return False

        PQ_hash.remove(current)  # remove element from Hash table (PQ.get removes elem from PQ)
        current.set_closed() #(color - red)
        draw_func() #(draw the grid)
              
        if current == end: #end node found

            reconstruct_path(prev, current, draw_func) #draw path from end to start
            end.set_end()
            start.set_start()
            return True # found

        #iterate over all neighbors of current node

        for neighbor in current.neighbors:
            # if neighbor inside PQ

            if neighbor in PQ_hash: 
                #calculate distance if we go to neighbor through current (+1 distance)
                alt = dist[current] + 1

                #if quicker - update
                if alt < dist[neighbor]:
                    dist[neighbor] = alt
                    prev[neighbor] = current
                  **counter += 1 **
                    PQ.put((dist[neighbor],**counter**, neighbor))
                    neighbor.set_open() #color green
                    draw_func() #draw the grid
    #path not found
    return False

I think it has something to do with the fact that im Adding into PQ instead of editing, but I'm not sure.我认为这与我添加到 PQ 而不是编辑这一事实有关,但我不确定。 Also, I'm sorry about the lack of PEP8, I've tried to comment my thoughts as I went I hope it's understandable.另外,对于缺少 PEP8,我感到很抱歉,我试图在我去的时候评论我的想法,我希望它是可以理解的。

Tech with time - 黑色块是障碍,紫色是最短路径 - A* 搜索

Adding a counter to the elements that go into the PQ sorts everything out.向 PQ 中的 go 元素添加一个计数器,将所有内容都整理出来。 PQ.put((0, counter, start)), the counter starts at zero at the beggining of the program, and each time we put an element into the PQ (the last if statement) we increment the counter, thus reducing the priority. PQ.put((0, counter, start)),计数器在程序开始时从零开始,每次我们将一个元素放入 PQ(最后一个 if 语句)我们增加计数器,从而降低优先级.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM