88 lines
2.5 KiB
Python
88 lines
2.5 KiB
Python
import os
|
|
import time
|
|
import csv
|
|
from collections import deque
|
|
import heapq
|
|
from abc import ABC, abstractmethod
|
|
from dataclasses import dataclass
|
|
from typing import List, Tuple, Optional, Dict, Any
|
|
import random
|
|
|
|
@dataclass
|
|
class Cell:
|
|
"""Клетка лабиринта"""
|
|
x: int
|
|
y: int
|
|
is_wall: bool = False
|
|
is_start: bool = False
|
|
is_exit: bool = False
|
|
weight: int = 1
|
|
|
|
def is_passable(self) -> bool:
|
|
return not self.is_wall
|
|
|
|
def __hash__(self):
|
|
return hash((self.x, self.y))
|
|
|
|
def __eq__(self, other):
|
|
return self.x == other.x and self.y == other.y if other else False
|
|
|
|
|
|
class Maze:
|
|
"""Лабиринт"""
|
|
|
|
def __init__(self, width: int, height: int):
|
|
self.width = width
|
|
self.height = height
|
|
self._cells: List[List[Optional[Cell]]] = [[None for _ in range(width)] for _ in range(height)]
|
|
self.start: Optional[Cell] = None
|
|
self.exit: Optional[Cell] = None
|
|
|
|
def set_cell(self, x: int, y: int, cell: Cell) -> None:
|
|
if 0 <= x < self.width and 0 <= y < self.height:
|
|
self._cells[y][x] = cell
|
|
|
|
def get_cell(self, x: int, y: int) -> Optional[Cell]:
|
|
if 0 <= x < self.width and 0 <= y < self.height:
|
|
return self._cells[y][x]
|
|
return None
|
|
|
|
def get_neighbors(self, cell: Cell) -> List[Cell]:
|
|
neighbors = []
|
|
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
|
|
|
|
for dx, dy in directions:
|
|
nx, ny = cell.x + dx, cell.y + dy
|
|
neighbor = self.get_cell(nx, ny)
|
|
if neighbor and neighbor.is_passable():
|
|
neighbors.append(neighbor)
|
|
|
|
return neighbors
|
|
|
|
def get_all_cells(self) -> List[Cell]:
|
|
cells = []
|
|
for y in range(self.height):
|
|
for x in range(self.width):
|
|
cell = self.get_cell(x, y)
|
|
if cell:
|
|
cells.append(cell)
|
|
return cells
|
|
|
|
def __str__(self) -> str:
|
|
result = ""
|
|
for y in range(self.height):
|
|
for x in range(self.width):
|
|
cell = self.get_cell(x, y)
|
|
if cell is None:
|
|
result += "?"
|
|
elif cell.is_wall:
|
|
result += "#"
|
|
elif cell.is_start:
|
|
result += "S"
|
|
elif cell.is_exit:
|
|
result += "E"
|
|
else:
|
|
result += " "
|
|
result += "\n"
|
|
return result
|