I need an algorithm for a robot to explore an n*n grid with obstacles (a maze if you wish). The goal is to explore all the squares without obstacles in them an avoid the squares with obstacles. The trick is that an obstacle forces the robot to change its path causing it to miss the possible free squares behind the obstacle. I can lazily increment/decrement the robot’s x/y coordinates to have the robot move in any of the four directions in case there are no obstacles and the robot can traverse a pre-seen path (if needed) in order to reach other free squares. The algorithm should terminate when ALL the free squares were met at least once.
Any simple lazy/efficient way to do this? a pseudo-code will be greatly appreciated
I believe the problem is reduceable from Traveling Salesman Problem, and thus is NP – Hard, so you are unlikely to find a polynomial solution that solves the problem optimally and efficiently.
However, You might want to adopt some of the heuristics and approximations for TSP, I believe they can be adjusted to this problem as well, since the problem seems very closed to TSP in the first place
EDIT:
If finding the shortest path is not a requirement, and you want any path, a simple DFS with maintaining a visited set can do. In the step in DFS you come back from the recursion – you move to the previous squares, this way the robot is ensured to explore all squares, if there is a path to all of them.
pseudo code for DFS:
invoke with
search([source],{},source)Note that optimization heuristics can be used before the
for eachstep – the heuristic will just be to reorder the iteration order of the nodes.