How to get the shortest cyclic path in a Graph? - java

I am developing a simple program to calculate the shortest path from one city to other, using directed weighted nodes of a graph to represent a train trail map.
So far I tried Bellman-Ford, Dijkstra, Floyd-Warshall and Johnson algorithms and all of them are good to find the shortest path to a different destination which is not the same as the start.
But when I need to calculate the path between city A and back to city A through other cities, I always get 0 value because those methods ignore the path from a city to itself in order to don't get caught in an infinity loop.
I know that it might be simple to resolve that loop problem by creating another parameter which is target to aim the algorithm to stop when it catches this target node, but I don't have the skill to modify one of those libraries.
Can anyone show me the way?
My graph is AB5 - BC4 - CD8 - DC8 - DE6 - AD5 - CE2 - EB3 - AE7 and the distance from B to B should be 9, but in all those algorithms it's returning 0.
Note: it's not a duplicate, since nobody bothered so far on finding routes at ends at the beginning, as I searched on StackOverflow and Google, at least in Java.

A simple approach would be to use the shortest path algorithms/libraries that you already have with a modified graph. You could duplicate each node and the corresponding adjacent outgoing edges, and then find the shortest path from the duplicated node to the original one.
Here is how the transformation would look like for A-A path (without weight for simplicity):

Related

Graph algorithm advise: find all affected paths between two nodes

I'm looking if there is a known solution for the task I have in mind
Given: Undirected graph with V > 100k nodes. Most of the vertices have a degree of 1-2, but some of them might have up to 10-20k edges.
I'm interested in all simple paths between two vertices or all paths ending on the start verticle limited by maxLength. Path can't contain the visited nodes but might end on the start node.
Goal: Occasionally some graph's edges are updated in batch. I'd like to find out what routes between vertices of interest were updated. Ideally in the form of Iterator but List is fine too.
Effectively I'm looking for a reactive way to find out about the affected routes.
The implementation could be in any language but Java/Kotlin specific is more preferred :)
Any references/relevant information would be very appreciated.
I wasn't sure if it's a question for CS StackExchange but it looks more relevant to SO.
To find paths between two nodes that do not share any nodes except the start and end.
Run Dijskta to find shortest simple path between start, end
Add large cost ( = largest integer for example ) to the in-edges of all nodes on shortest path, except start,end
Repeat until no new path found with cost less than largest integer
To find out what routes between vertices of interest were updated. This is trivial
- Multimap of edges, keyed by route index
- Vector of updated edges
- Loop over updated edges
- IF edge in multimap
- print index of affected route

Does A* always provide shortest path?

I am trying to understand how A*, Uniform cost and greedy search algorithms work. I know that the way in which nodes are explored changes in all 3 algorithms (greedy will explore based on heuristic value, A* based on heuristic plus distance, uniform based on distance).
I want to know if for a given source and destination should all 3 algorithms provide the shortest path (with just a different number of cities explored?) or can they provide a different path.
I am mostly confused due to the implementation part of - if you store nodes in queue then when you are about to explore the destination node you will have the shortest path for it but if you have queue of paths (and this queue is now sorted based on heuristic + distance) then you might not always get the shortest path.
Not necessarily, it depends on your heuristic. See this section in Wikipedia that explains it in detail.
To summarize, A* gives an optimal solution if the heuristic is admissable (meaning it never overestimates the cost).
In fact the heuristic should be admissible otherwise A* will find a suboptimal solution. I think the queue should not be ordinated by the distance of the next node but using the heuristic that will put as next node the most promising one.
Think it as: the next node may be the most distant from the current one but at the same time it can be the nearest one to the destination.

Finding shortest path from a list of points

If I have a list of points returned from a breadth-first-search through a type of 2D array maze in Java, how could I find the shortest path in that list of points?
For example, if my potential target points are [2, 4] and [6, 0] and I have a list of points that goes to each target point, how can I find out which route is shortest?
I'm thinking I might have to use Djikstra's Algorithm or something, but I'm unsure.
Thanks very much
You can use Dijkstra's algorithm here. Given the array maze you mentioned, the first step would be to get all the edges in your maze between 2 adjacent nodes, and the edge costs. For the nodes, you would need to know if each node has been visited, and the current cost of visiting that node.
Now, if you are not concerned with getting the shortest path, you might not need Dijkstra's. Instead, you can use a DP/Recursion approach to get possible paths from a source coordinate to a target coordinate. If you want to see a Dijkstra's implementation, this is something I had written. To get the shortest path, you would obviously need the distance between nodes.
To just find a path between 2 points, I would suggest something like this implementation. It includes both DP and recursion implementations and compares the running times for both (recursion can take very long to run for large datasets).
I feel this much should be enough to get you started. Let me know if you need some other information.
I didn't end up using Dijkstra's, but instead changed my breadth-first-search to add a "level" value or "distance" value from the origin point that would count upward with each visited node. The counts would stay consistent if the path ever branched, and since I already knew the end point, all it would take is to check out what the "count" was in my end points and compare.
Thank you for your help though! You'll get an upvote if the site lets me.
For those facing a similar problem:
I made a simple class called PointC which inherits from Point, but with an added "count" value. The count was updated appropriately with each step of the breadth first search, then the end points were compared at the end to obtain the most optimal path.

When to use DFS and BFS

Here is graph searching problem In Facebook Hacker Cup. Problem Link
Problem Description:
MXN Matrix we have to find the minimum distance from source to target. There are lasers which changes direction and Also Fires laser in every step we take.
Problem:
I have used the same approach is described in the Editorial But i have used DFS instead of BFS and i am getting wrong answer to some of the case.How the DFS is making a Difference Why DFS is not working on this while BFS work.
Code LINK
tHanks
Editorial
It is pretty simple. If you need to find the shortest path in an unweighted graph, you should use BFS. If you need a specific traversal order(like in topological sort), you should use DFS. If the order and the lenght of the path doesn't matter, you can use any of them. In this problem the shortest path is required, so BFS is an obvious choice(DFS doesn't work because it finds some path, not necessarily the shortest one).
The particular reason why BFS is good for finding the shortest path is that BFS traverses nodes in such an order, that all the nodes that have the distance X to the source node are processed before all the nodes that have the distance X+1. This allows for a very simple and efficient way of finding the shortest path in the graph between two nodes: as you add a node to the queue, you know its distance to the source is 1 more that the node you are processing at the moment (it can't be smaller, otherwise it already would have been in the queue). If with the distance for each node you also remember which node you came to it from, you can easily restore the shortest path itself.
DFS traverses nodes in a different order, and hence can't be easily adjusted to find the shortest path.
BFS -
Cases where you can use BFS-
1: To find minimum length path in an unweighted graph.
2: Level order traversal of a tree.
DFS:
Cases where you can use DFS-
1: To find any valid solution to a problem.
2: To check for existence of any path in a graph.
NOTE - Though they can be used in many other places.

How to order graph's nodes such that the distance between two adjacent nodes is minimal

I was wondering if this problem is known in graph theory:
I have an undirected graph with no weights G=(V,A) and I want to place the nodes of this graph in a string so that directed nodes are placed as much close as possible. So for example:
Given this graph:
a,b;a,d;b,e;c,f;c,h;f,h;e,g;e,h.
where arcs are separated by ';'
I need to get to this solution:
a,b,d,e,g,h,c,f=2
where 2 is the maximum distance in the string a,b,d,e,g,h,c,f between two directed nodes.
Formally:
let d(v,u) be the distance between two nodes according to the graph.
Find an order v1,,v2,,vn,, such that max{d(vi,,vi+1,) } is minimal
Well, it seems you are facing a variation of the Hamiltonian Path Problem.
In this problem, given a graph - you are looking for a path that go through all vertices without repeating any node twice.
Note that a hamiltonian path is a perfect solution to your problem, and thus if your problem can be solved efficiently - so does the hamiltonoan path problem.
Unfortunately, there is no known polynomial solution for the hamiltonian path problem, and the problem is NP-Complete (so the general belief is such a (efficient) solution does not exist).
A brute force solution will be O(n!) - check all possible permutations, and choose the optimal one. This can be optimized using branch and bound techniques.

Categories

Resources