问题
So, suppose i have a maze, which has a start point and an end point, marked with Orange and red respectively and my goal is to find the minimum distance between them. The blocked path is represented by black colour and the open path is represented by white colour . However there are two modification done in this.
- There are some cells which are must visit, marked in grey colour.
- Any cell can be visited any number of times(even the start, finish and must visit points)
for ex- B=Black, W=white, G=grey, R=Red, O=orange
BBBBBB BBBBB
BBGBBB BWGGB
MAZE1 => BOWGRB MAZE2 => BOBBB
BBGBBB BWWRB
BBBBBB BBBBB
Here in this case ans will be
MAZE1 => M[2][1] => [2][2] => [1][2] => [2][2] => [3][2] => [2][2] => [2][3] => [2][4] = 7
MAZE2 => M[1][1] => [1][2] => [2][2] => [3][2] => [3][3] => [3][2] => [2][2] = 6
As you can see, the nodes appear multiple times
First i thought of using recursion technique (backtracking) but couldn't come to an algorithm. and
So i thought of using this way.
- I will keep track of all the coordinates of must visit points, start and end points
- Find the distance between each node(like in selection sort we compare each and every term, just like that, we get the minimum distance between each node (using BFS))
- Then apply some minimum distance algorithm. I thought of TSP but it says nodes must be visited exactly once.Here it can be multiple times. I found chinese postman problem, but don't know if it can be applied here. Floyd warshall algorithm is there but it doesn't include every point
How should i proceed, any idea?
回答1:
Ok, so maybe I will try to solve this another time. Last time, I didn't notice about the fact that you can visit one point as many times as you can, so that appoarch maybe wrong.
First, assume that the total of Start, End and Gray node is N, and Start is 0, End is N - 1 and Gray node is from 1 to N - 2.
We can see that we can represent the state
at any one time by (mask, index)
, with index represent the current node we are in, and mask represent all the nodes we already visited (0 < mask < 2^N).
At first, the state is (1,0) or (00000 ... 1,0), which means only city 0 is visited, our goal is to reach the state (2^N - 1, N - 1) which means all the nodes are visited, and we end the journey at node N - 1.
So, at this point, we can easily see that, we have convert the orignal problem into a graph of state, and our goal is to find the shortest path from State 0 (1,0) to State end (2^N - 1, N - 1), so, applying Dijkstra shortest path algorithm for this new graph, and we have the answer.
Note: the answer is made based on one assumption that N <= 17
Another note: for robotics, the shortest path may not necessary the best path, as the speed for the robot is different when it turns and when it runs in straight line.
来源:https://stackoverflow.com/questions/25441051/minimum-distance-between-start-and-end-by-going-through-must-visit-points-in-a-m