Dijkstra Algorithm in Java - java

I have some troubles implementing Dijkstra algorithm in Java.
I use this (first) pseudocode: http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
Line 15 you need to get the vertex with the lowest distance.
But how can I save the distance with the according distance.
Note: vertex is defined as an Integer.
My solutions that didn't work properly:
Map with K = vertex, V = distance, Problem: long searching to get min dist
SortedMap with K = distance, V = vertex, Problem: almost every distance is defined as Integer.MAX_VALUE
So I am looking for a fast way to save a vertex to a distance and it should be easy to get the vertex with min dist.

Try using a PriorityQueue. That way, you can simply remove the head, as it would have the minimum distance of all vertices.
See more information about PriorityQueue here:
http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

Related

Minimum distance between two polygons [duplicate]

I want to find the minimum distance between two polygons with million number of vertices(not the minimum distance between their vertices). I have to find the minimum of shortest distance between each vertex of first shape with all of the vertices of the other one. Something like the Hausdorff Distance, but I need the minimum instead of the maximum.
Perhaps you should check out (PDF warning! Also note that, for some reason, the order of the pages is reversed) "Optimal Algorithms for Computing the Minimum Distance Between Two Finite Planar Sets" by Toussaint and Bhattacharya:
It is shown in this paper that the
minimum distance between two finite
planar sets if [sic] n points can be
computed in O(n log n) worst-case
running time and that this is optimal
to within a constant factor.
Furthermore, when the sets form a
convex polygon this complexity can be
reduced to O(n).
If the two polygons are crossing convex ones, perhaps you should also check out (PDF warning! Again, the order of the pages is reversed) "An Optimal Algorithm for Computing the Minimum Vertex Distance Between Two Crossing Convex Polygons" by Toussaint:
Let P = {p1,
p2,..., pm} and Q = {q1, q2,...,
qn} be two intersecting polygons whose vertices are specified
by their cartesian coordinates in
order. An optimal O(m + n)
algorithm is presented for computing
the minimum euclidean distance between
a vertex pi in P and a
vertex qj in Q.
There is a simple algorithm that uses Minkowski Addition that allows calculating min-distance of two convex polygonal shapes and runs in O(n + m).
Links:
algoWiki, boost.org, neerc.ifmo.ru (in russian).
If Minkowski subtraction of two convex polygons covers (0, 0), then they intersect

Given a set of coordinates, find the max distance (using steps)

Given a set of coordinates representing a flight path, the exercice is to find the maximum distance (given a n number of points to pass through). To illustrate the problem we have a flight path represented on a 2D grid as the following:
.
Here is what the algorithm should do with a parameter n (integer).
The question is to find an algorithm that can scan through all the points and try by combination all the distances and return the length of the final path.
We already have a method that can get the distance of two points:
/**
* #return the distance between the two coordinates
*/
public double distance(Coordinate destination) {}
/**
* #return the farthest coordinate from start
*/
public Coordinate coordMax() {}
/**
* #return max distance using n points
* I would maybe try to go for a recursive solution
* and already have the 2 corner cases down.
*/
public double statMaxDistance(int n) {
if (n == 0)
return coordTable[0].distance(coordTable[coordTable.length - 1]);
if (n == 1)
return coordTable[0].distance(coordMax());
// TODO recursive step
return statMaxDistance();
}
The question is :
Is there a way to complete this task without iterating over each point of the whole path, one by one, trying all possible combinations, computing all possible distances to eventually end up with the farthest one ?
It would seem rather sensical to follow such an approach where only 1 or 2 points would shift along the whole path but such an algorithm would be quite greedy when computing the maximum distance given 3+ reference points.
This can be solved using a Dynamic Program. Assume that D[i][j] is the maximum distance you can get from the start point to the i-th intermediate point where the last point is j. Your solution will be D[n][endPoint].
So how to solve this? The first column D[0][...] is easy to calculate. This will just be the distances of the according point to the start point. The other columns are a bit trickier. You need to check all entries in the previous column where the last point is strictly before the current point. So, to calculate entry D[i][j], you have to calculate:
D[i][j] = max_{k < j} (D[i - 1][k] + distance(k, j))
This means: Iterate all possible k such that k is smaller than j (i.e. the point k is located before the current point j). Calculate the resulting distance as the sum of the distance up to k (this is the D[i - 1][k] part) and the distance from k to j. Put the maximum of these values into D[i][j]. You may also want to keep track of k if you need to reconstruct the path at the end (i.e. you are not just interested in the maximum distance). Note that there may be cells with no valid solutions (e.g. D[1][0] - you cannot get to point 0 as the second (index 1) intermediate point).
Do this for every intermediate point in every column up to D[n - 1][...]. The final step is to do this process once more for D[n][endPoint], which strictly speaking does not need to be located in the D array (because you are interested in only a single value, not an entire column).
Once you have calculated this value, that is your solution. If you want to find the actual path, you have to backtrack using the stored k values for every cell.

Shortest path with a maximum number of vertices

I want to find the shortest path between two vertices with an additional constraint : max n vertices can be visited. The graph is directed, connected, non negative weights and may contain cycles.
Example:
Shortest path 0->2 with n = 2 is 18
Shortest path 0->3 with n = 3 is 22
Shortest path 0->3 with n = 4 is 9
So far I've implemented Djikstras algorithm to get the simple shortest path, and my idea was to keep a counter of the current vertices visited, if it exceeds n it takes one or more steps back and tries with another path.. but as far as I know Djikstras can't be used for backtracking as explained here.
Another idea is somehow to store every path between every node in a table. But I'm not really sure how Djikstra can discover the path 0->2 with weight 18 since it is not really a shortest path...
Does anyone have any ideas how to tackle this problem?
Divided each vertices into n vertices, that is, for vertices u, we create n vertices expressed as (u, 1) ... (u, n), the second number shows the number of steps to this vertices. For each edge from u to v, we create an edge from (u, i) to (v, i+1) where 1<=i<=n-1 in new graph. Now if you want to calculate the shortest path between u and v with n, just do Dijkstra from (u, 1), then your answer is min(result (v, i) | 1<=i<=n)
The total number of vertices can be n*n, so the complexity is about O(n^2*log(n^2))
Let COST_TO(v,n) be the total weight of the minimum path to vertex v with n edges or less.
When n=0, the answer is easy:
for all v, COST_T(v,0) = 0 if v is the source vertex and infinity otherwise
For n>0, COST_TO(v,n) is the minimum of COST_TO(v,n-1) and all COST_TO(w,n-1)+WEIGHT(w,v), where there is an edge from w to v
so, for n = 0 to N, keep track of all the vertices with COST_(v,n) < infinity along with their costs, and calculate the costs for n from the values for n-1.
At the same time you can keep track of the minimum weight path to each v -- every time you update the cost to v with the edge rule, the new path to v is the path to w plus that edge. A reverse-singly-linked list is handy for this.
Let's assume that you want to find the shortest path from the source vertex S to a destination vertex T consisting of at most K edges. I picked K, because the n in your question is misleading - if you want to find the shortest path visiting at most n vertices, where n is the total number of vertices, you can just run Dijkstra, because any simple path has at most n vertices - I assume that this is not what you want here.
Then, if you want a simple implementation, Bellman-Ford is a good choice here:
After the i-th iteration of the outer loop, the algorithm has computed the shortest path from the source vertex S to any other vertex consisting of at most i edges, so it consists of at at most i + 1 vertices. So in order to solve your problem, run K - 1 outer loops of Bellman-Ford, and check if the distance to the destination vertex T is well defined (is different than infinity), and if it is, you have your result. Otherwise, T is not reachable from S in visiting K or less vertices.
Maybe try a bfs and check the number of vertices against the max. Save the best of the ones that fulfill the constraints.
Heres a video about it
https://youtu.be/TvHV3PB8ANs
Nist.gov has some algos as well.

What would be smart and fast way to find a pair of closest points in two sets?

For example, I have two lists of points:
List<Point2D> a;
List<Point2D> b;
What would be the best way to find such i and j, so that a.get(i).distance(b.get(j)) is minimal?
The obvious solution is brute-force - calculate distance from each point in a to each point in b, keep the pair with shortest distance. But this algorithm is O(n^2), which is not good. Is there some better approach?
For every point of list a you can find the nearest point from list b as described in this answer. Time complexity is O((M+N) log M). N = |A|, M = |B|.
Then you just search the point in a, having the nearest neighbor. Time complexity is O(N).
You can put one of the lists in a quad tree or some other spatial index to make each lookup fast.
As an alternative you could put all your data in a database with spatial index capabilites.

How to decide the H cost in A* Search Algorithm for cities connected with roads

How to decide heuristic cost for the cities connected with roads problem. The graph has non negative weighted unidirectional edges and no edge connects any vertex to itself. In this graph, there is only one edge between any two vertices. My aim is to get the shortest distance between single source and single destination.
If your edges lie in a Euclidian plane, your vertices correspond to roads, and the vertex cost is the length of the road, then the Euclidian distance or L2 norm is a good choice for the heuristic cost.
Here's why. But first, some quick terminology:
Let f(x) be the path cost, the calculated shortest distance from the start node to node x.
Let h(x) be the heuristic cost, an estimate of the distance to the goal from node x.
Because A* is a directed best-first search algorithm. At each step it moves to the node which minimizes h(x) + f(x) (and calculating h(x) requires that we have a goal node in mind).
For this approach to be guaranteed to find the correct shortest patch distance between the start and end nodes, h(x) must be an admissible heuristic. This essentially means that it must not overestimate the distance to the goal node.
Therefore, if your nodes are organized on a Euclidian plane, and your costs correspond to the L2 norm distance between the nodes, then the Euclidian distance or L2 norm between the current node x and the goal node is guaranteed to be an admissible heuristic (it's the shortest possible path between the two nodes, so any actual path along a series of vertices in your graph must be longer).
As a bonus, it's informative to note that Dijkstra's Algorithm is simply a special case of A* with h(x) = 0. For any node, we assume that the path to the goal is 0, which means we simply take the smallest possible step. This is certainly an admissible heuristic because the distance between any two nodes cannot be less than 0 (if we're assuming non-negative edge costs).
If you're trying to optimize for distance travelled, euclidean distance is a good baseline heuristic.
If you're given a weighted graph, use the edge weight as if it's the length of the segment. The shortest path in a weighted graph is the path with the lowest combined edge weight.

Categories

Resources