【发布时间】:2020-04-15 03:27:05
【问题描述】:
我很难看到直接实现 Dijkstra 算法(没有堆)的 O(mn) 界限。在我的实现和其他实现中,我发现主循环迭代 n-1 次(对于不是源的每个顶点,n-1),然后在每次迭代中找到最小顶点是 O(n)(检查队列中的每个顶点并找到到源的最小距离),然后每个发现的最小顶点最多有 n-1 个邻居,因此更新所有邻居是 O(n)。在我看来,这会导致 O(n^2) 的界限。下面提供了我的实现
public int[] dijkstra(int s) {
int[] dist = new int[vNum];
LinkedList queue = new LinkedList<Integer>();
for (int i = 0; i < vNum; i++) {
queue.add(i); // add all vertices to the queue
dist[i] = Integer.MAX_VALUE; // set all initial shortest paths to max INT value
}
dist[s] = 0; // the source is 0 away from itself
while (!queue.isEmpty()) { // iterates over n - 1 vertices, O(n)
int minV = getMinDist(queue, dist); // get vertex with minimum distance from source, O(n)
queue.remove(Integer.valueOf(minV)); // remove Integer object, not position at integer
for (int neighbor : adjList[minV]) { // O(n), max n edges
int shortestPath = dist[minV] + edgeLenghts[minV][neighbor];
if (shortestPath < dist[neighbor]) {
dist[neighbor] = shortestPath; // a new shortest path have been found
}
}
}
return dist;
}
我不认为这是正确的,但我很难看到 m 因素在哪里。
【问题讨论】:
标签: algorithm time-complexity dijkstra