4

Right now I'm performing Dijkstra's algorithm on the entire graph and forming a min-heap of the nodes by total distance from the origin node. I then remove the top n elements from the heap.

This strikes me as seriously inefficient. Suppose I need to find the 10 closest nodes and my graph has over over 100000 nodes. Then performing Dijkstra's on the entire graph seems like a waste of time. But the problem is I'm not sure of any other way I can find the top 10 closest nodes without calculating the shortest path to each and every node in the graph.

Is there a better way?

ask
  • 1,934
  • 7
  • 29
  • 38

1 Answers1

5

Dijkstra works by iteratively adding the node which has the smallest distance to the source. This is the node whose distance we are sure of, there can never be a shorter path. So if we want to find the 10 closest nodes, we can simply terminate the search after we have added 10 nodes to our closed set.

JSQuareD
  • 4,076
  • 2
  • 15
  • 25
  • I see. Since Dijsktra's is greedy, we always have the shortest path to a node once its visited. Any nodes added after that have longer paths. Is that right? – ask Nov 28 '13 at 00:21