*...*..D
.G..*.....
**...**.
.S....*.
........
...G**..
........
.G..*...
Here is 2d array where
S- Source
D-Destination
G-Point must be visited
." . "Free paths
"*"Block Paths
Can you help me which would be the efficient algorithm to find the length of shortest pathi in java
Only Horizontal and Vertical movements are possiable
To find the shortest distance from
start
point to all other points in the map, you can use a BFS. Sample code:The second path of the problem is actually a traveling salesman problem, so you need to convert from your original graph to a graph which
only contains G,D and S points
, with theweight
of each edge in this graph is theshortest path between them in original path
. From that onward, if the number of G is small (less than 17) you can usedynamic programming and bitmask
to solve the problem.Here there are many algorithms like dijkstra or BFS but if you need to learn an path finding algorithm then i suggest the A* algorithm as it is quicker than dijkstra or BFS and can be easily implemented on a 2D matrix. As in case of must visit node you can try all sequences in which you visit the nodes for example say
S->G1->G2->G3->D
find the minimum for this path asmin(S,G1)+min(S,G2)+min(G3,D)
. try all permutations of theG's
and get the minimum of them all.This is a simple Breadth First search algorithm problem. This is called flood fill technique which is a type of Breadth First search algorithm. Read it from here. You can also learn the basic Breadth first algorithm from here. This could also be solved by other techniques like Dijkstra or Floyd warshal. But Breadth first search is easier to understand.