5

I am developing a system using Dijkstra's algorithm to display the shortest path in a squared grid using Java. When the path goes to a diagonal, vertical or horizontal cell near by, the path cost increases by 1. But the path's priority should be given to go through diagonal cells. Only when there is no possible diagonal cell near by, the path can go through a vertical or a horizontal cell. What is the most convenient method to do that?

Sami Udakara
  • 145
  • 1
  • 1
  • 8
  • 3
    It would be better if you remove `java` tag and add `algorithm` tag instead. – Shridhar R Kulkarni Apr 29 '17 at 08:36
  • Is it okay if any other solution is given or you are sure to use Dijkstra's? – Shridhar R Kulkarni Apr 29 '17 at 08:43
  • I am sure to use Dijkstra's algorithm. Need a solution only for that method. Because I have already implemented two different methods – Sami Udakara Apr 29 '17 at 08:57
  • You can pick the order in which to process neighbours in Dijkstra's, so just pick the diagonal neighbours first. Or make diagonal moves cost like 0.9999999 or something. – Bernhard Barker Apr 29 '17 at 09:04
  • We can't change the cost for the diagonal cells. Checking the diagonal neighbors first gives a wrong path when I try to find the shortest path between between two nodes like starting node(9,9) and end node (0,0) – Sami Udakara Apr 29 '17 at 09:15

1 Answers1

0

In Dijkstra's algorithm we keep selecting vertices which have not yet been selected and which have minimum distance from source. Here every next vertex or next square is equally far with a distance of one. Among the squares with minimum distance,if the diagonal square has not yet been included then include it, otherwise select either horizontal sidewise or vertical sidewise square. From implementation point of view it is just using if.. else construct. You can maintain some field for priority of node. Keep priority one for diagonal square and zero otherwise.

Moreover Dijkstra's algorithm is not a well suit for this problem as Dijkstra's algorithm is used to find the shortest path from a single source vertex to all other vertices in the given graph. Though you have not mentioned in the question it looks like you intend to find shortest path from specific source square to specific destination square.

Also, all the reachable squares are equidistant so there is no fun in using Dijkstra'a algorithm here. Alternatively, You can use DFS or BFS treating the grid as a graph. For yet another alternative you might also have a look at Dynamic Programming style on this problem for which you can find some examples here.

Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57