optimizationdata-structuresgraph-theorymaze

Maze problem with obstacles - How to modify one instruction in given path to reach goal?


I am trying to find out a way to optimize my code which solves the following problem: There is a grid on which i have a target cell to reach. Along the road there are obstacles. I am given a set of instructions (F for forward, B for Back, L for turn left and R for turn right). I start at coordinate x = 0, y = 0 and my initial direction is to the right. I have to find that one instruction to change so that i can reach my target.

For example, let's say that my instructions are FFF and my target is located at (0, 2). If I change the first F into a L, then I can reach my target.

If we have N instructions and K obstacles, actually my code run in about O(N^2 * K). I am trying to find some optimization.

What I did so far is this: if I take the problem without the obstacles I could reach an O(N) time complexity by doing the following: Apply all the instructions as they are given. This brings me to some point on the grid which is my landing point. Then for each instruction, I test the 4 possibilities (actually 3 remaining) corresponding to F, B, L and R. F and B instructions induce a translation on my landing point. L and R instructions induce a rotation on that landing point. At each test I check if this makes me reach the goal's coordinate and if yes then i am done. So i just need to test the landing point and this gives me O(N) execution time

Now the problem is that if I take into consideration the obstacles, well I am stuck because I have no optimal way to check if an obstacle's coordinate intersects my path. This is because i have just computed the coordinates on my landing point and not the points on all the path. Of course I can compute each coordinate for each point for each coorect path but i end up in quadratic time.

My questions are the following:

I am looking for a hint so that i can try to solve it by myself.


Solution

  • You can reduce the number of paths to check with the following observations:

    These are all the cases to look into. They are limited to less than 10 cases, and for each we only need to identify the last index in the path that meets the conditions. And so we have less than 10 mutated paths to verify for obstacles, making this algorithm O(n).

    I hope my messy explanation was clear enough to implement it.