Finding shortest path in 2d array

David :

I need to find the shortest path from top left to bottom right.

The Rules are it has to go from A to B to A to B etc.

See picture as example:

enter image description here

The expected output for the above picture is then 13.

I'm trying to implement this in java with a dijkstra algorithm for this but then got stuck. Is this the right way to go?

Ankari :

If the goal is to find the shortest path from the top left corner to the bottom right corner (or between any arbitrary 2 points), dijsktra is one possible way to go, however you must correctly construct a graph from the input.

In this case I would go for a simple flood-fill algorithm. You can find several online resources explaining it including this video or this article, so I won't go in more details in this answer.

You can find the shortest route using only 2 matrices (one for your original array of letter and one for the distances) if you implement your rules correctly (A to B and B to A only).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151049&siteId=1