When to use DFS and BFS - java

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.

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

how to find shortest path between multiple clusters

Dijkstra theorem talks about finding shortest path between two vertices.. But what if we have a matrix/graph which has clusters.. and now we need to find shortest path between these clusters ! distance between these clusters is in same way like it happens with between nodes having different weights.
As Matt recommended we can assume distance between nodes of cluster as zero.. which makes so much sense.. But, what if we want to find single shortest path so that ALL clusters are connected to each other..
Dijkstra's algorithm works basically the same way between two clusters as it does between two vertices. Start with all the vertices in the source cluster at distance 0, and proceed building incrementally longer paths until you find one of the vertices in the target cluster.
If it helps, you can think of it this way: Connect all the vertices in both clusters together with 0-cost edges, and then find the shortest path from any specific source vertex to any specific target vertex. It won't matter which ones you choose, because the 0-cost edges ensure the everything in a cluster is at the same distance from everything else.

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.

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.

How to get the shortest cyclic path in a Graph?

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):

Categories

Resources