Finding the shortest path with only passing specific edge less or equal to one time in Graph - algorithm

Given a undirected graph that it has ordinary edges and specific edges, our goal is to find the sum of the shortest path's weight between two vertices(start vertex to end vertex) with only walk through specific edge equal or less than one time. In other words, there are multiple specific edges, and only at most one of them can be used.
This is a problem that I faced in my Data-Structure homework, and I stuck at the first step of the way to storage the weights of the edge in Graph. Because there are two kinds of edge in Graph, I have no idea that how to solve this problem.
I know that I can obtain the shortest path by using Dijkstra’s Algorithm, but during the process, how can I modify the Algorithm to meet the requirement of the restriction?
Thanks a lot for answering my question!

The solution is to duplicate the graph as follows:
Duplicate the vertices, such that for each original vertex A, you have an A and an A'.
If in the original graph there is a normal edge between A and B, then in the new graph, place an edge between A and B and also between A' and B'
If in the original graph there is a specific edge between A and B, then in the new graph place a (directed) edge from A to B' (not the inverse!) and from B to A' (again: not the inverse!). These edges should be directed.
If now the task was to find the shortest path between S and D, then solve in the new graph the problem of finding the shortest path between S and D or S and D', which ever is shortest. You can use a standard implementation of Dijkstra's algorithm for that, starting in S and ending when you find either D or D'.

Given n specific edges run Dijkstra's search n times.
On each run, one of the n nodes (let call it node i) should be set to its real weight and all other n-1 nodes to an infinite value.
At the end of each run store the shortest path and step i
At the end of all runs select from the stored paths the shortest one.
set all n edges weight to infinity
for i=0; i < n ; i++ {
set edge i to it real weight
run run Dijkstra's search
store path
set all n edges weight to infinity
}
select the shortest path from the stored paths.

Related

How to set exactly one edge to zero in directed weighted graph in order to find shortest path?

The following is the question I am working on:
Consider a directed, weighted graph
G
where all edge weights are
positive. The goal of this problem is to find the shortest path
in
G
between two pre-specified vertices
s
and
t
, but with an added twist: you are allowed to change the weight
of
exactly
one edge (of your
choosing) to zero.
In other words, you must pick an edge in
G
to set to zero that minimizes the shortest
path between
s
and
t
.
Give an efficient algorithm to achieve this goal in
O
(
E
lg
V
) time and analyze your algorithm’s running
time. Sub-optimal solutions will receive less credit.
Hint:
You may have to reverse the edges, run a
familiar algorithm a number of times, plus do some extra work
So I have tried running Dijkstra's from s to all other nodes and then I have tried reversing the edges and running it again from s to all other nodes. However, I found out that we have to run Dijskstra's from s to all other nodes and then reverse the edges and then run Dijkstra's from all other nodes to t. I am not exactly sure how this helps us to find the edge to set to zero. By my intuition I thought that we would simply set the maximum weight edge to zero. What is the point of reversing the edges?
We need to run Dijkstra's algorithm twice - once for the original graph with s as the source vertex, and once with the reversed graph and t as the source vertex. We'll denote the distance we get between vertex s and i from the first run as D(i) and the distance we get between vertex t and i second run D_rev(i).
Note that we can go follow the reversed edges backwards (i.e., follow them in the original direction), thus D_rev(i) is actually the shortest distance from vertex i to t. Similarly, D(i) is the shortest distance from vertex s to i following Dijkstra's algorithm.
We can now loop through all the edges, and for each edge e which connects v1 and v2, add up D(v1) and D_rev(v2), which corresponds to the weight of the path s -> v1 -> v2 -> t with e being the zero edge, since we can go from s to v1 with a distance of D(v1), set e to 0, go from v1 to v2, and then go from v2 to t with a distance of D_rev(v2). The minimum over these is the answer.
A rough proof sketch (and also a restatement) : if we set an edge e to 0, but don't use it in the path, we can be better off setting an edge that's in the path to 0. Thus, we need only consider paths that includes the zeroed edge. The shortest path through a zeroed edge e is to first take the shortest path from s to v1, and then take the shortest path from v2 to t, which are exactly what were computed using the Dijkstra algorithm, i.e., D and D_rev.
Hope this answer helps!

most lightweight circle in directed graph that goes through specific vertex

I have directed Graph G(V,E) with weight function w. so that weight of each (u,v) is a positive value. I need to find the most lightweight circle in the graph that vertex k' is part of it.
I've also given an algorithm i can use which can find the most lightweight path for a graph with positives weights ( i can use it only once).
I thought about creating a sub graph G' where all vertices and edges that are strongly connected components. find the graph which k' is part of it. then find for the most lightweight adjacent edge from k' to some v of vertices. from that v i can run the algorithm given and find the lightweight path then add the weight of the vertex missing ( (k',v) ).
is that seems correct ? I'm in the beginning of this course and I feel i'm not there yet.
It is a single-source shortest-path problem, where you exclude k->k self-loop as a solution, and find a longer path from k to k. The trick is always expand the shortest path thread.
Given this definition, you can start Googling...
I can't imagine why you called your source vertex k'. Anyway...
Add a new vetrex w that has the same outgoing edges as k'.
Then use Dijkstra's algorithm to find the shortest path from w to k'.
Substitute k' for w in the path, and you have the smallest cycle including k'.
Very interesting problem. I am assuming that there are no negative values in the graph, or otherwise the following solutions requires first normalizing the vertices such that the negative values become at least 0. First method (trivial) is to detect all cycles starting from the target vertex (k). Then compute the weight of all those cycles and take the minimum. The second method is to run Dijkstra algorithm (again watch out negative weights) from the target node (k). Then iterate over all incoming edges of (k), and select the source node that has the minimum Dijkstra value. Now the lightest cycle includes the single path (formed by Dijkstra traversal) from (k) to the chosen node + the bridge to come back to (k). I hope that helps :)

Dijkstra's Single Source Shourtest Path with an extra edge with weight of 'w'

In an recent interview I was asked to implement single source shortest path algorithm(for undirected and positive weighted graph) with slight modification i.e. we're given an extra edge with weight 'w'. And we have to find if we can find a more shorter path, than the one calculated by SSSP algo, by connecting that extra edge, with weight 'w', between two nodes which are not already connected.
Here's an image. As according to SSSP the shortest path between A(source) & D(destination)is A-B-C-D i.e. total of 8.
But given the extra edge. It can be connected between A and D, which are not already connected, to minimize the shortest path yielded through SSSP algo.
Image of graph with extra edge contributing the shortest path
I tried thinking about the solution. But nothing struck so far. I've implemented the Dijkstra algorithm to find the shortest path. But this little modification has baffled me. So can you help a little bit.
There are two options:
We don't need an extra edge. This case is handled by a standard Dijkstra algorithm.
A shortest path with an extra edge looks like this: shortest_path(start, V) + (V, U) + shortest_path(U, target). That is, we go from the start to some vertex V by the shortest path in the original graph, then we go to U (again, an arbitrary vertex) by adding this extra edge (V and U mustn't be connected) and then we go from U to the target node by the shortest path in the original graph.
We can use the structure of the path to get an O(n ^ 2) solution: we can compute shortest paths from the start node to all the others (one run of the Dijkstra's algorithm) and all shortest paths from the target node to all other nodes (one more run). Now we can just iterate over all possible pairs (V, U) and pick the best one.
Bonus: we can solve it in O(m log n) for a sparse graph. The idea is as follows: instead of checking all (U, V) pairs, we can find such U that it has the minimal distance to the target among all vertices that are not connected to V in degree(V) * log V (or even linear) time (this problem is known as finding the smallest element not in the set).
i am not sure I ubderstand your question. You Have a weighted graph ,and can add a edge with w, add to where make shortest path.
I think we can use spfa + dp to solve the problem. Set all other edge to w and create boolean matrix m, m[i,j] =1 mean no edge between i,j, dp[u,0] mean shortest distance when we reach u without using an extra edge, dp[u,1]mean using an extra edge. I don’t write the dp transfer equation. So we can iterate in spfa, and we can also backtrack the best way of dp and get where to set an extra edge.
We do not use Dijkstra algorithm in above solution.
spfa is also a Single Source Shourtest Path algoritm, it can deal negative weighted edge, but not negative cycle.
It’s just my think,i have not try it.but I think it’s a idea to solve it.
If any wrong, tell me please.

minimum connected subgraph containing a given set of nodes

I have an unweighted, connected graph. I want to find a connected subgraph that definitely includes a certain set of nodes, and as few extras as possible. How could this be accomplished?
Just in case, I'll restate the question using more precise language. Let G(V,E) be an unweighted, undirected, connected graph. Let N be some subset of V. What's the best way to find the smallest connected subgraph G'(V',E') of G(V,E) such that N is a subset of V'?
Approximations are fine.
This is exactly the well-known NP-hard Steiner Tree problem. Without more details on what your instances look like, it's hard to give advice on an appropriate algorithm.
I can't think of an efficient algorithm to find the optimal solution, but assuming that your input graph is dense, the following might work well enough:
Convert your input graph G(V, E) to a weighted graph G'(N, D), where N is the subset of vertices you want to cover and D is distances (path lengths) between corresponding vertices in the original graph. This will "collapse" all vertices you don't need into edges.
Compute the minimum spanning tree for G'.
"Expand" the minimum spanning tree by the following procedure: for every edge d in the minimum spanning tree, take the corresponding path in graph G and add all vertices (including endpoints) on the path to the result set V' and all edges in the path to the result set E'.
This algorithm is easy to trip up to give suboptimal solutions. Example case: equilateral triangle where there are vertices at the corners, in midpoints of sides and in the middle of the triangle, and edges along the sides and from the corners to the middle of the triangle. To cover the corners it's enough to pick the single middle point of the triangle, but this algorithm might choose the sides. Nonetheless, if the graph is dense, it should work OK.
The easiest solutions will be the following:
a) based on mst:
- initially, all nodes of V are in V'
- build a minimum spanning tree of the graph G(V,E) - call it T.
- loop: for every leaf v in T that is not in N, delete v from V'.
- repeat loop until all leaves in T are in N.
b) another solution is the following - based on shortest paths tree.
- pick any node in N, call it v, let v be a root of a tree T = {v}.
- remove v from N.
loop:
1) select the shortest path from any node in T and any node in N. the shortest path p: {v, ... , u} where v is in T and u is in N.
2) every node in p is added to V'.
3) every node in p and in N is deleted from N.
--- repeat loop until N is empty.
At the beginning of the algorithm: compute all shortest paths in G using any known efficient algorithm.
Personally, I used this algorithm in one of my papers, but it is more suitable for distributed enviroments.
Let N be the set of nodes that we need to interconnect. We want to build a minimum connected dominating set of the graph G, and we want to give priority for nodes in N.
We give each node u a unique identifier id(u). We let w(u) = 0 if u is in N, otherwise w(1).
We create pair (w(u), id(u)) for each node u.
each node u builds a multiset relay node. That is, a set M(u) of 1-hop neigbhors such that each 2-hop neighbor is a neighbor to at least one node in M(u). [the minimum M(u), the better is the solution].
u is in V' if and only if:
u has the smallest pair (w(u), id(u)) among all its neighbors.
or u is selected in the M(v), where v is a 1-hop neighbor of u with the smallest (w(u),id(u)).
-- the trick when you execute this algorithm in a centralized manner is to be efficient in computing 2-hop neighbors. The best I could get from O(n^3) is to O(n^2.37) by matrix multiplication.
-- I really wish to know what is the approximation ration of this last solution.
I like this reference for heuristics of steiner tree:
The Steiner tree problem, Hwang Frank ; Richards Dana 1955- Winter Pawel 1952
You could try to do the following:
Creating a minimal vertex-cover for the desired nodes N.
Collapse these, possibly unconnected, sub-graphs into "large" nodes. That is, for each sub-graph, remove it from the graph, and replace it with a new node. Call this set of nodes N'.
Do a minimal vertex-cover of the nodes in N'.
"Unpack" the nodes in N'.
Not sure whether or not it gives you an approximation within some specific bound or so. You could perhaps even trick the algorithm to make some really stupid decisions.
As already pointed out, this is the Steiner tree problem in graphs. However, an important detail is that all edges should have weight 1. Because |V'| = |E'| + 1 for any Steiner tree (V',E'), this achieves exactly what you want.
For solving it, I would suggest the following Steiner tree solver (to be transparent: I am one of the developers):
https://scipjack.zib.de/
For graphs with a few thousand edges, you will usually get an optimal solution in less than 0.1 seconds.

Single shortest path of an acyclic undirected disconnected graph

Is there a graph algorithm that given a start(v) and an end(u) will find a shortest path through the given set of edges, but if u is a disconnected vertex, it will also determine the shortest path to add missing edges until u is no longer disconnected?
I have a pixel matrix where lines are made of 255's(black) and 0's(white). lines(255) can have breaks or spurs and I must get rid of both. I could have a pixel matrix forest with say 7 or so trees of black pixels. I need to find the true end points of each tree, find the single shortest path of each tree, then union all skew trees together to form 1 single line(ie, a single shortest path from the furthest 2 end points in the original matrix). all edge weights could be considered 1.
Thanks
How about running Dijkstra's algorithm and if disconnected, connect v and u? What's your criteria for "best place to add a missing edge?" Do edges have weights (like distance)?
Edit:
For one idea of "the best place," you could try the path that has minimal sum of shortest paths between all connected pairs. Floyd–Warshall algorithm can be used to find shortest paths between all pairs. So, run Floyd-Warshall for each node in v's tree and u.
Your problem isn't well defined for disconnected graphs. I can always add and edge between v and u.
If you meant that given an acyclic undirected disconnected graph, actually known as a forest, and given a subset of edges as a subgraph, can you find the shortest path between vertices, than this problem is trivial since if there is a path in the full graph, there is one path only.
If this is a general graph G, and you are talking about a forest subgraph G', than we need more info. Is this weighted? Is it only positive weights? If it is unweighted, do some variant of Dijksta. Define the diameter of a tree to be the length of the longest path between two leaves (this is well defined in a tree, since ther is only one such path). Let S be the sum of the diameters of all the trees in G', then set the weight all edges out of G' to 2S, then Dijkstra's algorithm will automatically prefer to step through G', stepping outside G' only when there is no choice, since walking through G' would always be cheaper.
Here you have following scenarios:
case:1. (all edges>0)
Negate all edges
find the longest path in graph using this:
https://www.geeksforgeeks.org/longest-path-undirected-tree/
negate the final result
case2: edges might be or might not be negative
Read Floyd–Warshall algorithm for this

Resources