Jamie
Jamie

Reputation: 1094

Finding the shortest path between a point and a row on a grid

I know that there are algorithms to find the shortest path between two points, for example, algorithms answered in How to calculate the shortest path between two points in a grid.

However, now, I have a N * M grid, where rows are from 0 to N - 1 and columns are from 0 to M - 1, where every grid contains obstacle (or you can think it as the distance between two grids). For example, I have a 4 * 4 grid below:

5   7   8   2
2   7   4   3
6   4   3   2
5   7   2   5

And I want to find the shortest distance between the left-top corner and the bottom row, i.e. between (0, 0) and (X, 3), where X can be any number from 0 to 3.

I can find out each shortest path between (0, 0) -> (0, 3) to (0, 0) -> (3, 3), but this may be too slow. Is there a more efficient algorithm / approach to this question?

Upvotes: 2

Views: 882

Answers (1)

templatetypedef
templatetypedef

Reputation: 372664

This comes up more than you might think, and there's a nice way to account for this.

You can imagine that your grid is a graph. Each cell is a node, and there's edges from each cell to each adjacent cell with an appropriate cost.

Consider adding in a new node into the graph and connecting everything in the last row to that new node by an edge of cost zero. Now, think about finding the shortest path from the upper-left corner to the magic new node that you just added. The shortest path there will correspond to a path through the grid that, at the last step, leaves the last row and enters this new node. Since the cost of the edge to the new node is zero, the cost of the cheapest path from the upper-left corner node to this new node is the cost of the best path from the upper-left corner to any cell in the last row.

In other words, if you can solve the shortest path problem between a pair of nodes, you can solve the shortest path problem from any node to any one of many nodes in a graph.

Can you see a way to adapt this technique so that you could also find the shortest path between anything in the first row and anything in the last row?

Upvotes: 2

Related Questions