Ex No - 2 (B) Memory-Bounded A Algorithm
Ex No - 2 (B) Memory-Bounded A Algorithm
Ex No - 2 (B) Memory-Bounded A Algorithm
#!/usr/bin/env python
import random
from typing import Tuple, List, Generator, Union, Optional
class Cell:
"""Cell class represents a cell in the maze.
Attributes:
value: The character stored in the cell.
position: Vertical and horizontal position of the cell in the maze.
parent: Cell which has been visited before this cell.
g: Cost from start to this cell.
h: Estimated cost from this cell to the goal.
f: Sum of the cost of this cell and the estimated cost to the goal.
"""
class Maze:
"""The place that represents a 2D grid of cells.
Attributes:
grid: A list of cells with their specific position.
horizontal_limit: The horizontal limit of the maze (x-axis).
vertical_limit: The vertical limit that we can go (y-axis).
start: The starting position of the maze.
goals: The goals positions that we want to reach.
"""
def __init__(self, maze: str) -> None:
lines = maze.splitlines()
rows, cols = len(lines), max(map(len, lines))
grid = [[Cell(' ', (i, j)) for j in range(cols)] for i in range(rows)]
# Generate a matrix based on the max length of rows
start = None
goals = []
self.grid = grid
self.horizontal_limit = rows
self.vertical_limit = cols
self.start = start
self.goals = goals
if save_to_file:
with open('genmaze.txt', 'w') as f:
f.write(grid)
return Maze(grid)
while opened:
# print('---------------------------------------------------')
lowest_f = min(opened, key=lambda cell: cell.f)
current = opened.pop(opened.index(lowest_f))
# print(f'Current position is {current.position}')
closed.append(current)
if current.position in maze.goals:
# print(f'Goal found after {len(closed)} steps!')
# print(f'The maximum required bound in this case is {int(bound)
if bound is not None else "not specified"}')
# print('---------------------------------------------------')
return _reconstruct_path(current) # Return the path at the first
goal found
return None
if __name__ == '__main__':
import sys
import argparse
if args.generate:
maze = _generate_maze(min_size=(5, 5), max_size=(100, 100),
save_to_file=True)
print('Maze generated successfully!\n')
elif args.maze is not None:
with open(args.maze, 'r') as f:
maze = Maze(f.read())
print('Maze loaded from file...\n')
else:
print('No maze specified! Please read the help for more information.')
sys.exit(1)