I've written a DFS algorithm which finds a path between to vertices in a graph but want to optimize it to return the path containing the minimum number of edges.
I wanted to just switch to a BFS algorithm, but I'm unsure of how I would need to modify it given the properties of my graph and the criteria the resulting path must meet.
The Graph:
Undirected, weighted and contains edges with positive weights, negative weights, and weights of 0.
The Path:
Cannot visit any vertex more than once. Total weight of the path must always be positive including the path up to any vertex before the vertex of the end of the path.
The weights can be thought of as the cost to use each path and the total weight as the amount available to use. Positive weights increase the amount available to use and negative weights cost their weight to use.
Any help would be appreciated, thanks!
BFS is applicable to unweighted graphs (or graphs where all edges have the same weight).
For weighted graphs one can use algorithms such as Dijkstra's (which is a "modified BFS"), or A* (which is a "modified Dijkstra's") .
However both Dijkstra's or A* do not work correctly with negative weights.
For graph with negative weights consider
Bellman–Ford algorithm.
Edit: If you only want to use the smallest number of edges whilst maintaining
Total weight of the path must always be positive including the path up
to any vertex before the vertex of the end of the path.
you can use BFS and use the weight just as selection criteria, meaning check before adding an edge to the queue. If adding it would make the total weight negative, do not add it.
Related
I'm wondering if A* search is suitable for the following situation:
There exist adjacency matrix for graph G (m x n)
Blocked cell is marked by 0
Non-blocked cell is marked by some value (let's call this prize!)
The goal is to find a Path from start to end but given multiple options to move vertical/horizontal, always choose cell with the largest prize.
Would this mean that the f(n) = g(n) + h(n) check would differ than the regular A* algorithms? Or perhaps given multiple f(n)'s (neighbors) with the same minimum value, choose the neighbor with the highest cell-value?
Would that skew the A* algorithms accuracy?
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
I was given a graph, including a start vertex, other vertices, and edges represent the costs going from one vertex to another. I need to find the set of destination vertices that I can travel to from the start vertex. The budget is a certain amount of dollars and the travel total cost should be within the budget. How can i implement the Dijkstra's algorithm to this problem? I think we usually use Dijkstra to find the shortest path between two fixed vertices before. But I am not sure how to implement Dijkstra on this budget problem. If someone can give some ideas, that really helps!
To my undersatanding, Dijkstra's algorithm solves the single-source shortest path problem. This means that the resulting data structure is a tree rooted at the starting node. Typically, an implementation would store the minimum cost to reach each node from the starting node. In total, the set of vertices that can be reached within the budget are the ones to which the cost of the shortest path does not exceed the budget. The algorithm itself does not need to be modified; in an additional step, the nodes which can be reached within budged has to be returned as the output.
If you use Dijkstra algorithm, you may end up with the below scenarios:
Assuming budget of 50 and the graph of 4 nodes (start, node 1, node 2, node 3)
Start Node -> node 1 (15) -> node 2 (10): so total cost is 25
Start Node -> node 3 (15): total cost is 15
So now what is your expected result? You should go to node 1 then node 2 and ignore node 3 (since you cannot return back to start then go to node 3, the return will cost 30 too). Or you should go to node 1, back to start, then go to node 3 (total cost of 45, the largest cost you can utilise)
What you need is not the shortest path covering all destinations which is Floyd-Warshall algorithm https://en.wikipedia.org/wiki/Floyd–Warshall_algorithm
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.
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.