2025-12-01 14:23:49 -06:00

92 lines
2.0 KiB
Python

class Coord:
x: int
y: int
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __str__(self) -> str:
return f'({self.x}, {self.y})'
def __eq__(self, other) -> bool:
return other.x == self.x and other.y == self.y
def __add__(self, other):
return Coord(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Coord(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Coord(self.x * other, self.y * other)
def __rmul__(self, other):
return Coord(self.x * other, self.y * other)
def copy(self):
return Coord(self.x, self.y)
UP = Coord(1, 0)
DOWN = Coord(-1, 0)
EAST = Coord(0, 1)
WEST = Coord(0, -1)
class Maze:
map: list[str]
start: Coord
end: Coord
def __init__(self, file_path: str):
with open(file_path, 'r') as file:
self.map = file.readlines()
for y, row in enumerate(self.map):
for x, char in enumerate(row):
if char == 'E':
self.end = Coord(x, y)
elif char == 'S':
self.start = Coord(x, y)
def get_pos(self, pos: Coord) -> str:
return self.map[pos.y][pos.x]
def is_wall(self, pos: Coord) -> bool:
return self.get_pos(pos) == '#'
def is_end(self, pos: Coord) -> bool:
return self.end == pos
def lowest_score(self, pos: Coord, score: int | None = 0, dir: Coord | None = None, facing: Coord | None = EAST) -> int:
print(pos)
if self.is_end(pos):
return score
if self.is_wall(pos):
return float('inf')
if dir:
if dir != facing:
score += 1000
facing = dir
score += 1
pos += facing
return min([self.lowest_score(pos, score, dir, facing) for dir in [UP, DOWN, EAST, WEST]])
def main():
maze = Maze('test.text')
print(maze.lowest_score(maze.start))
if __name__ == '__main__':
main()