Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the shortest path to visit all non-blocked squares on a grid

Let's say you have a grid like this (made randomly):

grid

Now let's say you have a car starting randomly from one of the while boxes, what would be the shortest path to go through each one of the white boxes? You can visit each white box as many times as you want and can't jump over the black boxes. The black boxes are like walls. In simple words you can move from white box to white box only.

You can move in any direction, even diagonally.

Two subquestions:

  1. Assume you know the position of all black boxes before moving.
  2. Assume you only know the position of a black box when you are in a white box adjacent to it.
like image 509
Laz Avatar asked May 20 '10 16:05

Laz


People also ask

How do you find the shortest path on A grid?

The shortest “path” is the lowest sum of the cell values that make up a consecutive path from one vertices (say top left) to the other end on the far side (bottom right).

How do you visit all nodes in A graph the shortest path?

graph length will be N, and j is not same as i is in the list graph[i] exactly once, if and only if nodes i and j are connected. We have to find the length of the shortest path that visits every node. We can start and stop at any node, we can revisit nodes multiple times, and we can reuse edges.

Which algorithm is best for finding shortest path?

Dijkstra's Algorithm stands out from the rest due to its ability to find the shortest path from one node to every other node within the same graph data structure.

Does A * find the shortest path?

A* is the most popular choice for pathfinding, because it's fairly flexible and can be used in a wide range of contexts. A* is like Dijkstra's Algorithm in that it can be used to find a shortest path.


1 Answers

You should model the problem as a complete graph where the distance between two nodes (white boxes) is the length of the shortest path between those nodes. Those path lengths can be calculated by the Floyd-Warshall algorithm. Then, you can treat it as "Traveling salesman", like glowcoder wrote.

EDIT: to make it more clear: you can describe each "interesting" path through the maze by a sequence of different white boxes. Because if you have an arbitrary path visiting each white box, you can split it up into sub-paths each one ending at a new white box not visited so far. Each of this sub-paths from white box A to B can be replaced by a shortest sub-path from A to B, that's why you need the shortest-paths-between-all-pairs-of-nodes matrix.

like image 166
Doc Brown Avatar answered Oct 16 '22 10:10

Doc Brown