Skip to content
Advertisement

Determine minimum number of moves to reach top left corner of 2-D array

I’m working through some leetcode problems and came across this one:

I’m given a 2-D array, for example:

JavaScript

Each cell in the array represents the number of moves I must make from that cell. I can move only up or only left each time I stop on a cell. I want to find the minimum number of moves necessary to go from the bottom right of the array to the top left cell.

For example, in the given array, I should return 2, going from given[2][2] to given[0][2] to given[0][0] as this is the shortest possible path. If there is no possible way to get to the top left, I should return -1.

I’m not sure where to even begin. Can anyone offer any pointers? I was thinking I could represent this as a graph and apply Djikstra’s Algorithm, but I don’t know if this is a viable solution.

Advertisement

Answer

I assume all the elements are positive numbers.

JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement