背景
我想在O(mlogn)時間編碼Dijkstra算法,其中m是邊數,n是節點數。我正在使用查找給定起始節點和給定結束節點之間的最短路徑。我在這方面很新穎。優先隊列插入鍵值對java
這裏是算法我已經想出:
假設圖由鄰接矩陣來表示,並且每個節點都有一個行索引。
Initialize starting node distance to zero, and all other nodes to inifinity, in the heap.
Create a list of shortest paths, equal to the number of nodes in the graph, set to 0.
While the index of the node that corresponds to the minimum element in the heap
has no value in the list of shortest paths and heap has node distances, do:
Remove the minimum node distance from the heap, and bubble as necessary to fill the removed node.
Put the minimum node distance into the list of shortest paths at its row index.
For all nodes that were adjacent to the node with the minimum distance (that was just removed), do:
Update the distances in the heap for the current node, using the following calculation:
min((deleted node distance + adjacent edge weight), current node's distance)
Reorganize the heap to be a minimum heap.
Return value in the list of shortest paths at the location of the end node.
這是O(mlogn),因爲你只能每更新一次邊緣的距離。
「這需要線性時間 初始化堆,然後我們在澳的成本執行米更新(log n)的每一個用於O(管理記錄n)的總時間。」 - http://www.cs.cmu.edu/~avrim/451f07/lectures/lect1011.pdf
問題
爲了更新從在堆正確的位置開始頂點的距離,插入到堆必須是鍵 - 值對 - 鍵爲節點(行索引),值是距離。
有演講稿online是說,在優先級隊列ADT的每個條目是一個鍵值對(否則,它怎麼可能優先級?)。
問題
的爲PriorityQueue方法最多隻能有一個參數,那麼你如何插入一個值相關聯的密鑰?
這必須在具有特定名稱的單個文件中完成(即,我的理解是我無法制作KeyValuePair
類實現Comparator
)。
我很想聽聽你的看法。
@recprogrammer,我不熟悉Map接口。這可能是一個愚蠢的問題,但我能夠通過導入java.util。*來使用Map,並且可以在一個文件中使用文件名Dijkstra.java來做到這一點(即,是否必須更改文件名,就像我必須改爲一個類)? – jessicaraygun
是的,你可以通過簡單的導入'java.util。*'來使用'Map'類。 – reprogrammer