I have an undirected graph and i want to list all possible paths from a starting node.
Each connection between 2 nodes is unique in a listed path is unique, for example give this graph representation:
{A: [B, C, D],
B: [A, C, D],
C: [A, B, D],
D: [A, B, C]}
some listed path starting from A
A, B, C, D, A, C in this path we have a connection between
A and B but we can't have a connection between B and A
I can't accomplish it using the existing algorithm that i know like DFS .
Any help will be very appreciated .
The simplest way would be to recursively try each neighbor and combine all the results.
This assumes there are no loops - if you allow loops (as in your example) there will be infinitely-many paths. In this case, you can make a path-generator by limiting the path-length to check for, then looping over all possible path-lengths.
A probably most intuitive way would be to, as previously suggested, iterate over all neighbours of each potential starting point until all paths are exhausted.
However, the risk with this method is that it tends to loop forever if the graph has cycles. This can be mitigated by using a list of visited vertices (or, probably preferable in your case, visited edges)
In pseudocode, that might give something like this:
paths = []
for node in graph
visited = []
path = [node]
add node and path to stack-or-queue
while node on stack-or-queue
pop node and path
for edges of node
if edge is not visited
add edge to visited
add neighbour to path
add neighbour and path to stack-or-queue
add path to paths
It produces an algorithm of relatively high complexity, so be sure to test it well to avoid crap.
Writing it recursively might be easier, although it removes the possibility of easily changing between DFS and BFS.
Related
I'm trying to figure out the most optimal way to get the shortest paths from all the source nodes to any one of the target nodes that leads to the minimum weight in a weighted graph. All nodes are either a source node or a target node. So figure we have a graph consisting of A, B, C as source nodes and D, E, F as target nodes. A, B, C has to find the shortest path to any one of the target nodes that happens to have the shortest path.
The naive solution is to use the Dijkstra's algorithm or something similar to first find the shortest path from A to D and then from A to E etc. and then comparing the final weight of each of those shortest paths to see which is actually the shortest. I want to know if there is a more efficient solution to this.
Add a new node that leads to all the sources (make these new edges 0-weight), and run Dijkstra's from the new node.
I try to get this code developed for a potential project at work and I think Dijkstra can help but no idea how to get started.[![enter image description here][1]][1]
I have a list of Line objects called myList and each line has EndPoint1 and EndPoint2 as Point2Dcordinates (x,y) and Name as string. So the list has L1, L2, L3, L4, L5, L6, L7, and L8 as shown in the example image. Points A, B, C, D, and E are points of these lines and they are always not connected points between two lines.
I would like to write a method that gives me a list of the lines (or names of the lines) that connected two points for example:
List<string> FindPath(Point2D P1, Point2D P2): (A, E): L1, L3, L6, L7, L8
List<string> FindPath(Point2D P1, Point2D P2): (B, D): L2, L3, L5
Edit:
I would like to find all possible paths, although 99.9% of the time there is only 1 path possible.
You are talking about a data structure called a graph, a collection of nodes (points), connected by edges (line segments).
Graphs comes in several flavours. They can be directed or undirected, and they can by cyclic, or acyclic.
Directed graphs have one-way edges: the edge a→b can only be used to travel from a to b, it can't be used to get from b to a. Undirected graphs, on the other hand, have 2-way edges: as long as two nodes are connected, you can get from either one to the other.
Cyclic graphs allow cycles, where traversing the graph can return you to a node you have already visited (a → b → c → a is a cycle); acyclic graphs do not allow such cycles. If your graph is cyclic, when you traverse it, you'll need to track what nodes you've visited, so you can detect and deal with cycles. If you don't you'll wind up in an endless loop.
In addition, both nodes and edges may carry additional information, such as "cost", making them a weighted graph. Google's and Apple's maps are modeled as such weighted graphs. Each intersection is a node, and each street segment between intersections is an edge. The additional information (weigths) carried by edges are information such as average speed, starting/ending addresses, etc.
If you need to find the shortest path between two nodes in your graph, you may need a weighted graph (where the edges carry a distance. Or not: perhaps "shortest path" is defined as the least number of intermediate nodes between A and B.
So, you need the correct model:
a set of nodes, and
a set of edges, defined by the 2 nodes it connects.
One can (and it is sometimes useful to dispense with the set of nodes completely, and define the graph solely in terms of its edges:
Once you have that, finding a path from any two points in the graph is actually pretty easy. The algorithm is this:
You can get from node A to node B if an edge AB exists. Otherwise...
You can get from node A to node B if
an edge AX exists, and
you have not yet visited node X, and
you can [recursively] get from node X to node B.
That's about all there is to it.
I am assuming you need to find the shortest path from one point to another. Hence you need to do a BFS *).
First convert the points into a graph. The graph could be of the format
// The key is the point and the it contains the list of all
// the neighbours
Map<Point2D, List<Point2D>> graph = new HashMap<>();
Then use a Queue and a visited matrix to keep track of the visited points. When looping through the Points make sure you add them to an answer list.
For more details on BFS look here: https://www.geeksforgeeks.org/print-paths-given-source-destination-using-bfs/
*) Breadth First Search Algorithm
You can solve this by treating it as a graph. Each x is a vertex, and your lines are the edges. Then to find the path between P1 and P2, run BFS from P1.
I want to find a simple method to generate sets of disjoint parts in a Graph. In other words, in the following Graph, I want to get two sets of {A, B, C, D} and {E, F}.
You can use any graph traversal algorithm (BFS and DFS are the most common).
Whenever the algorithm is "stuck" (there is no more nodes to traverse), you have finished finding one component, mark it, and choose a random vertex that was not traversed yet to find the next component.
I am trying self-study Graph Theory, and now trying to understand how to find SCC in a graph. I have read several different questions/answers on SO (e.g., 1,2,3,4,5,6,7,8), but I cant find one with a complete step-by-step example I could follow.
According to CORMEN (Introduction to Algorithms), one method is:
Call DFS(G) to compute finishing times f[u] for each vertex u
Compute Transpose(G)
Call DFS(Transpose(G)), but in the main loop of DFS, consider the vertices in order of decreasing f[u] (as computed in step 1)
Output the vertices of each tree in the depth-first forest of step 3 as a separate strong connected component
Observe the following graph (question is 3.4 from here. I have found several solutions here and here, but I am trying to break this down and understand it myself.)
Step 1: Call DFS(G) to compute finishing times f[u] for each vertex u
Running DFS starting on vertex A:
Please notice RED text formatted as [Pre-Vist, Post-Visit]
Step 2: Compute Transpose(G)
Step 3. Call DFS(Transpose(G)), but in the main loop of DFS, consider the vertices in order of decreasing f[u] (as computed in step 1)
Okay, so vertices in order of decreasing post-visit(finishing times) values:
{E, B, A, H, G, I , C, D, F ,J}
So at this step, we run DFS on G^T but start with each vertex from above list:
DFS(E): {E}
DFS(B): {B}
DFS(A): {A}
DFS(H): {H, I, G}
DFS(G): remove from list since it is already visited
DFS(I): remove from list since it is already visited
DFS(C): {C, J, F, D}
DFS(J): remove from list since it is already visited
DFS(F): remove from list since it is already visited
DFS(D): remove from list since it is already visited
Step 4: Output the vertices of each tree in the depth-first forest of step 3 as a separate strong connected component.
So we have five strongly connected components: {E}, {B}, {A}, {H, I, G}, {C, J, F, D}
This is what I believe is correct. However, solutions I found here and here say SCCs are {C,J,F,H,I,G,D}, and {A,E,B}. Where are my mistakes?
Your steps are correct and your answer is also correct, by examining the other answers you provided you can see that they used a different algorithm: First you run DFS on G transposed and then you run an undirected components algorithm on G processing the vertices in decreasing order of their post numbers from the previous step.
The problem is they ran this last step on G transposed instead of in G and thus got an incorrent answer. If you read Dasgupta from page 98 onwards you will see a detailed explanation of the algorithm they (tried) to use.
Your answers is correct. As per CLRS, "A strongly connected component of a directed graph G = (V,E) is a maximal set of vertices C, such that for every pair of vertices u and v, we have both u ~> v and v ~> u, i.e. vertices v and u are reachable from each other."
In case you assume {C, J, F, H, I, G, D} as correct, there is no way to reach from D to G (amongst many other fallacies), and same with other set, there is no way to reach from A to E.
I have been given a question on an assignment that has got me stumped. I may just be thinking too hard about it... The question follows.
Give a linear time algorithm to determine the longest unweighed path in an acyclic undirected graph (that is, a tree).
My first intention is to go with a DFS. But it seems like a DFS would only give me the longest path from the node I start at to another vertex; however, the problem asks for the longest path in the tree... not the longest path from the node I start at. Could someone set me straight?
Thanks.
One such method is to pick any node, A, and in linear time compute distances to all other nodes. Suppose B is most distant from A. In step 2, find the node most distant from B.
Let d(P,Q) denote distance from P to Q. Note that if E is the lowest common ancestor of A, B, C, then d(A,B) = d(A,E)+d(E,B) and also note that d(E,B) ≥ d(E,C).
Edit 1: The algorithm or method – find B most distant from any A; find C most distant from B; claim that d(B,C) is maximal over all vertex pairs in the graph – seems to be sound, but the above does not prove it.
On one hand, it need not be that d(E,B) ≥ d(E,C), and on another, that alone would not be quite enough to establish d(B,C) ≥ d(F,G) where F, G are any nodes in the tree. ...