But I don't know how it's stuck in an infinite loop. I added the explored variable. If the node is examined it shouldn't get added to the frontier. But still, it's stuck in an infinite loop. The same node is going back and forth and not exploring the new direction. I don't know what's the problem.
Here's the code:
class Agent():
def __init__(self, node, parent):
self.node = node
self.parent = parent
class Queue():
def __init__(self):
self.frontier = []
self.explored = []
def contains_state(self, state):
return any(node.node == state for node in self.frontier)
def add(self, child):
self.frontier.append(child)
def remove(self):
node = self.frontier[-1]
self.frontier = self.frontier[::-1]
return node
class Stack():
pass
class Maze():
def __init__(self):
self.filename = 'maze1'
with open(self.filename) as f:
self.maze = f.read().splitlines()
self.height = len(self.maze)
self.width = len(max([x for x in self.maze]))
self.walls = []
for i in range(self.height):
for j in range(self.width):
if self.maze[i][j] == '0':
self.walls.append((i, j))
if self.maze[i][j] == 'A':
self.start = (i, j)
if self.maze[i][j] == 'B':
self.goal = (i, j)
def action(self, position):
print(position)
action_dict = {'up': (position[0]-1, position[1]),
'down': (position[0]+1, position[1]),
'left': (position[0], position[1]-1),
'right': (position[0], position[1]+1)}
possible_actions = []
for actions in action_dict:
r = action_dict[actions][0]
c = action_dict[actions][1]
if r >= 0 and r < self.height and c >= 0 and c < self.width:
if self.maze[r][c] != '0':
possible_actions.append((r, c))
return possible_actions
def solve(self):
solver = Queue()
agent = Agent(node=self.start, parent=())
new_observation = agent
solver.add(new_observation)
self.explored = set()
while (True):
child = solver.remove()
if child.node == self.goal:
path = []
while child.parent is not None:
path.append(child.node)
child = child.parent
for i in path:
self.maze[i[0]] = self.maze[i[0]][:i[1]] + '*' + self.maze[i[0]][i[1] + 1:]
n_names = ["{}\n".format(i) for i in self.maze]
with open(self.filename + '_solution', 'w') as fp:
fp.writelines(n_names)
break
neighbours = self.action(child.node)
for i in neighbours:
child = Agent(node=i, parent=new_observation.node)
if not solver.contains_state(i) and i not in self.explored:
solver.add(child)
self.explored.add(i)
if len(solver.frontier) == 0:
print("No solution")
break
algo = Maze()
algo.solve()
Here's the Maze I am trying to solve:
000B00
00 00
00 000
00 00
A 000