Helo everyone! I want to do an algorithm in Python that will traverse a map with DFS. And the problem is that it will block after visiting some of the good parts and it will not traverse all the map. I am using pygame, but I will share only my dfs method:
ef moveDSF(self, detectedMap):
if len(self.stack):
current = self.stack.pop()
if current not in self.visited:
self.visited.append(current)
self.x = current[0]
self.y = current[1]
# print(current, self.stack)
for position in v: # v = [[-1, 0], [1, 0], [0, 1], [0, -1]]
new_x = self.x + position[0]
new_y = self.y + position[1]
if 0 < new_x < 19 and 0 < new_y < 19 and detectedMap.surface[new_x][new_y] == 0:
neighbour = (new_x, new_y)
self.stack.append(neighbour)
return True
else:
return False
The map is represented as a 20x20 matrix. At the start, in the stack we will have only the initial value and visited will be an empty list. We go one step at a time in this algorithm because the while loop will be in the pygame part. "detectedMap.surface[new_x][new_y] == 0" checks if that point is a good one, 1 being for walls.