[5]+komments

This commit is contained in:
xalva 2026-05-21 13:40:02 +03:00
parent f4e8b9732e
commit bd678b4716
2 changed files with 209 additions and 484 deletions

View File

@ -1,136 +1,153 @@
import sys import sys
sys.setrecursionlimit(30000)
csv_path = '/stepinim/docs/data/lab1_results.csv' sys.setrecursionlimit(30000) # Увеличиваю лимит рекурсии для BST
#Связный список # Связный список
def ll_insert(head, name, phone): def ll_insert(head, name, phone):
new_node = {'name': name, 'phone': phone, 'next': None} new_node = {'name': name, 'phone': phone, 'next': None} # Создаю новый узел
if head is None: if head is None: # Если список пуст
return new_node return new_node # Возвращаю узел как голову
curr = head curr = head # Указатель для обхода
prev = None prev = None # Храню предыдущий узел
while curr is not None: while curr is not None: # Иду по списку
if curr['name'] == name: if curr['name'] == name: # Если нашел такое же имя
curr['phone'] = phone curr['phone'] = phone # Обновляю телефон
return head return head
prev = curr prev = curr
curr = curr['next'] curr = curr['next']
prev['next'] = new_node prev['next'] = new_node # Добавляю в конец
return head return head
def ll_find(head, name): def ll_find(head, name):
curr = head curr = head # Начинаю с головы
while curr: while curr: # Иду по всему списку
if curr['name'] == name: if curr['name'] == name: # Сравниваю имена
return curr['phone'] return curr['phone'] # Возвращаю телефон
curr = curr['next'] curr = curr['next'] # Перехожу к следующему
return None return None # Не нашел
def ll_delete(head, name): def ll_delete(head, name):
if head is None: if head is None: # Пустой список
return None return None
if head['name'] == name: if head['name'] == name: # Удаляю голову
return head['next'] return head['next'] # Возвращаю второй элемент
curr = head curr = head
while curr['next']: while curr['next']: # Иду пока есть следующий
if curr['next']['name'] == name: if curr['next']['name'] == name: # Нашел элемент для удаления
curr['next'] = curr['next']['next'] curr['next'] = curr['next']['next'] # Перепрыгиваю через него
return head return head
curr = curr['next'] curr = curr['next']
return head return head
def ll_list_all(head): def ll_list_all(head):
result = [] result = []
curr = head curr = head
while curr: while curr: # Собираю все элементы
result.append((curr['name'], curr['phone'])) result.append((curr['name'], curr['phone']))
curr = curr['next'] curr = curr['next']
result.sort(key=lambda x: x[0]) result.sort(key=lambda x: x[0]) # Сортирую по имени
return result return result
#Хэш-таблица
HASH_SIZE = 1009 # Хэш-таблица
HASH_SIZE = 1009 # Размер таблицы - простое число
def _hash_name(name): def _hash_name(name):
return hash(name) % HASH_SIZE return hash(name) % HASH_SIZE # Беру остаток от деления - это индекс корзины
def ht_insert(buckets, name, phone): def ht_insert(buckets, name, phone):
idx = _hash_name(name) idx = _hash_name(name) # Вычисляю индекс корзины
buckets[idx] = ll_insert(buckets[idx], name, phone) buckets[idx] = ll_insert(buckets[idx], name, phone) # Метод цепочек - вставляю в список
def ht_find(buckets, name): def ht_find(buckets, name):
idx = _hash_name(name) idx = _hash_name(name) # Нахожу корзину
return ll_find(buckets[idx], name) return ll_find(buckets[idx], name) # Ищу в цепочке
def ht_delete(buckets, name): def ht_delete(buckets, name):
idx = _hash_name(name) idx = _hash_name(name) # Нахожу корзину
buckets[idx] = ll_delete(buckets[idx], name) buckets[idx] = ll_delete(buckets[idx], name) # Удаляю из цепочки
def ht_list_all(buckets): def ht_list_all(buckets):
all_entries = [] all_entries = []
for bucket in buckets: for bucket in buckets: # Прохожу по всем корзинам
if bucket is not None: if bucket is not None:
curr = bucket curr = bucket
while curr: while curr: # Собираю всю цепочку
all_entries.append((curr['name'], curr['phone'])) all_entries.append((curr['name'], curr['phone']))
curr = curr['next'] curr = curr['next']
all_entries.sort(key=lambda x: x[0]) all_entries.sort(key=lambda x: x[0])
return all_entries return all_entries
#Двоичное дерево поиска
# Двоичное дерево поиска
def bst_insert(root, name, phone): def bst_insert(root, name, phone):
if root is None: if root is None: # Пустое место - создаю узел
return {'name': name, 'phone': phone, 'left': None, 'right': None} return {'name': name, 'phone': phone, 'left': None, 'right': None}
if name < root['name']: if name < root['name']: # Меньше - иду влево
root['left'] = bst_insert(root['left'], name, phone) root['left'] = bst_insert(root['left'], name, phone) # Рекурсивно вставляю в левое поддерево
elif name > root['name']: elif name > root['name']: # Больше - иду вправо
root['right'] = bst_insert(root['right'], name, phone) root['right'] = bst_insert(root['right'], name, phone) # Рекурсивно вставляю в правое поддерево
else: else: # Равно - обновляю
root['phone'] = phone root['phone'] = phone
return root return root
def bst_find(root, name): def bst_find(root, name):
curr = root curr = root
while curr: while curr: # Итеративный спуск по дереву
if name == curr['name']: if name == curr['name']: # Нашел
return curr['phone'] return curr['phone']
elif name < curr['name']: elif name < curr['name']: # Искомое меньше - налево
curr = curr['left'] curr = curr['left']
else: else: # Искомое больше - направо
curr = curr['right'] curr = curr['right']
return None return None
def bst_delete(root, name): def bst_delete(root, name):
if root is None: if root is None:
return None return None
if name < root['name']: if name < root['name']: # Ищу в левом поддереве
root['left'] = bst_delete(root['left'], name) root['left'] = bst_delete(root['left'], name)
elif name > root['name']: elif name > root['name']: # Ищу в правом поддереве
root['right'] = bst_delete(root['right'], name) root['right'] = bst_delete(root['right'], name)
else: else: # Нашел узел для удаления
if root['left'] is None: if root['left'] is None: # Нет левого ребенка
return root['right'] return root['right'] # Заменяю правым
if root['right'] is None: if root['right'] is None: # Нет правого ребенка
return root['left'] return root['left'] # Заменяю левым
# Есть оба ребенка - ищу минимальный в правом поддереве
min_node = root['right'] min_node = root['right']
while min_node['left']: while min_node['left']: # Иду до самого левого
min_node = min_node['left'] min_node = min_node['left']
root['name'] = min_node['name'] root['name'] = min_node['name'] # Копирую данные преемника
root['phone'] = min_node['phone'] root['phone'] = min_node['phone']
root['right'] = bst_delete(root['right'], min_node['name']) root['right'] = bst_delete(root['right'], min_node['name']) # Удаляю преемника
return root return root
def bst_list_all(root): def bst_list_all(root):
result = [] result = []
def inorder(node):
def inorder(node): # Симметричный обход
if node: if node:
inorder(node['left']) inorder(node['left']) # Сначала левое
result.append((node['name'], node['phone'])) result.append((node['name'], node['phone'])) # Потом корень
inorder(node['right']) inorder(node['right']) # Потом правое
inorder(root) inorder(root)
return result return result
# ============================================================ # ============================================================
# TECT # TECT
# ============================================================ # ============================================================
@ -156,9 +173,9 @@ graph_path = os.path.join(DATA_DIR, "lab1_graph.png")
# ТЕСТОВЫЕ ДАННЫЕ # ТЕСТОВЫЕ ДАННЫЕ
# ============================================================ # ============================================================
random.seed(42) random.seed(42) # Фиксирую seed для повторяемости
N = 3000 N = 3000 # 3000 записей
base_records = [ base_records = [
(f"User_{i:05d}", f"123-{i:05d}") (f"User_{i:05d}", f"123-{i:05d}")
@ -166,53 +183,47 @@ base_records = [
] ]
records_shuffled = base_records.copy() records_shuffled = base_records.copy()
random.shuffle(records_shuffled) random.shuffle(records_shuffled) # Перемешанный порядок
records_sorted = sorted(base_records, key=lambda x: x[0]) records_sorted = sorted(base_records, key=lambda x: x[0]) # Отсортированный порядок
# Поиск # Данные для поиска
search_existing = [ search_existing = [
name for name, _ in random.sample(base_records, 100) name for name, _ in random.sample(base_records, 100) # 100 существующих имен
] ]
search_nonexist = [ search_nonexist = [
f"None_{i}" f"None_{i}"
for i in range(10) for i in range(10) # 10 несуществующих имен
] ]
# Удаление # Данные для удаления
delete_names = [ delete_names = [
name for name, _ in random.sample(base_records, 50) name for name, _ in random.sample(base_records, 50) # 50 имен для удаления
] ]
# ============================================================ # ============================================================
# СОЗДАНИЕ СТРУКТУР # СОЗДАНИЕ СТРУКТУР
# ============================================================ # ============================================================
def build_structure(records, struct_type): def build_structure(records, struct_type):
if struct_type == "ll": if struct_type == "ll":
structure = None structure = None
for name, phone in records: for name, phone in records:
structure = ll_insert(structure, name, phone) structure = ll_insert(structure, name, phone) # Последовательная вставка
return structure return structure
elif struct_type == "ht": elif struct_type == "ht":
structure = [None] * HASH_SIZE structure = [None] * HASH_SIZE
for name, phone in records: for name, phone in records:
ht_insert(structure, name, phone) ht_insert(structure, name, phone) # Вставка с хэшированием
return structure return structure
elif struct_type == "bst": elif struct_type == "bst":
structure = None structure = None
for name, phone in records: for name, phone in records:
structure = bst_insert(structure, name, phone) structure = bst_insert(structure, name, phone) # Вставка с ветвлением
return structure return structure
@ -221,13 +232,9 @@ def build_structure(records, struct_type):
# ============================================================ # ============================================================
def measure_insert(records, struct_type): def measure_insert(records, struct_type):
start = time.perf_counter() start = time.perf_counter()
build_structure(records, struct_type) # Замеряю время построения структуры
build_structure(records, struct_type)
end = time.perf_counter() end = time.perf_counter()
return end - start return end - start
@ -236,25 +243,20 @@ def measure_insert(records, struct_type):
# ============================================================ # ============================================================
def measure_search(records, struct_type): def measure_search(records, struct_type):
structure = build_structure(records, struct_type) # Строю структуру
structure = build_structure(records, struct_type)
start = time.perf_counter() start = time.perf_counter()
if struct_type == "ll": if struct_type == "ll":
for name in search_existing + search_nonexist: for name in search_existing + search_nonexist:
ll_find(structure, name) ll_find(structure, name) # Поиск перебором
elif struct_type == "ht": elif struct_type == "ht":
for name in search_existing + search_nonexist: for name in search_existing + search_nonexist:
ht_find(structure, name) ht_find(structure, name) # Поиск через хэш
elif struct_type == "bst": elif struct_type == "bst":
for name in search_existing + search_nonexist: for name in search_existing + search_nonexist:
bst_find(structure, name) bst_find(structure, name) # Поиск спуском по дереву
end = time.perf_counter() end = time.perf_counter()
return end - start return end - start
@ -263,25 +265,20 @@ def measure_search(records, struct_type):
# ============================================================ # ============================================================
def measure_delete(records, struct_type): def measure_delete(records, struct_type):
structure = build_structure(records, struct_type) # Строю структуру
structure = build_structure(records, struct_type)
start = time.perf_counter() start = time.perf_counter()
if struct_type == "ll": if struct_type == "ll":
for name in delete_names: for name in delete_names:
structure = ll_delete(structure, name) structure = ll_delete(structure, name) # Удаление со сдвигом
elif struct_type == "ht": elif struct_type == "ht":
for name in delete_names: for name in delete_names:
ht_delete(structure, name) ht_delete(structure, name) # Удаление из цепочки
elif struct_type == "bst": elif struct_type == "bst":
for name in delete_names: for name in delete_names:
structure = bst_delete(structure, name) structure = bst_delete(structure, name) # Удаление с ребалансировкой
end = time.perf_counter() end = time.perf_counter()
return end - start return end - start
@ -298,62 +295,28 @@ experiments = [
] ]
modes = [ modes = [
("shuffled", records_shuffled), ("shuffled", records_shuffled), # Тест на случайных данных
("sorted", records_sorted) ("sorted", records_sorted) # Тест на отсортированных данных
] ]
for struct_name, struct_type in experiments: for struct_name, struct_type in experiments:
for mode_name, records in modes: for mode_name, records in modes:
for rep in range(1, 4): # 3 повтора для усреднения
for rep in range(1, 4):
insert_time = measure_insert(records, struct_type) insert_time = measure_insert(records, struct_type)
search_time = measure_search(records, struct_type) search_time = measure_search(records, struct_type)
delete_time = measure_delete(records, struct_type) delete_time = measure_delete(records, struct_type)
all_data.append([ all_data.append([struct_name, mode_name, rep, "insert", insert_time])
struct_name, all_data.append([struct_name, mode_name, rep, "search", search_time])
mode_name, all_data.append([struct_name, mode_name, rep, "delete", delete_time])
rep,
"insert",
insert_time
])
all_data.append([
struct_name,
mode_name,
rep,
"search",
search_time
])
all_data.append([
struct_name,
mode_name,
rep,
"delete",
delete_time
])
# ============================================================ # ============================================================
# CSV # CSV
# ============================================================ # ============================================================
with open(csv_path, "w", newline="", encoding="utf-8") as f: with open(csv_path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f) writer = csv.writer(f)
writer.writerow(["Структура", "Режим", "Повтор", "Операция", "Время (сек)"])
writer.writerow([
"Структура",
"Режим",
"Повтор",
"Операция",
"Время (сек)"
])
writer.writerows(all_data) writer.writerows(all_data)
print(f"CSV сохранён: {csv_path}") print(f"CSV сохранён: {csv_path}")
@ -365,9 +328,7 @@ print(f"CSV сохранён: {csv_path}")
df = pd.read_csv(csv_path) df = pd.read_csv(csv_path)
df_avg = ( df_avg = (
df.groupby( df.groupby(["Структура", "Режим", "Операция"])["Время (сек)"]
["Структура", "Режим", "Операция"]
)["Время (сек)"]
.mean() .mean()
.reset_index() .reset_index()
) )
@ -375,9 +336,7 @@ df_avg = (
fig, ax = plt.subplots(figsize=(12, 6)) fig, ax = plt.subplots(figsize=(12, 6))
ops = ["insert", "search", "delete"] ops = ["insert", "search", "delete"]
x = range(len(ops)) x = range(len(ops))
width = 0.12 width = 0.12
configs = [ configs = [
@ -390,20 +349,14 @@ configs = [
] ]
for i, (struct, mode) in enumerate(configs): for i, (struct, mode) in enumerate(configs):
subset = df_avg[ subset = df_avg[
(df_avg["Структура"] == struct) (df_avg["Структура"] == struct) &
&
(df_avg["Режим"] == mode) (df_avg["Режим"] == mode)
] ]
times = [ times = [
subset[ subset[subset["Операция"] == op]["Время (сек)"].values[0]
subset["Операция"] == op
]["Время (сек)"].values[0]
for op in ops for op in ops
] ]
ax.bar( ax.bar(
[p + i * width for p in x], [p + i * width for p in x],
times, times,
@ -412,22 +365,12 @@ for i, (struct, mode) in enumerate(configs):
) )
ax.set_xticks([p + 2.5 * width for p in x]) ax.set_xticks([p + 2.5 * width for p in x])
ax.set_xticklabels(ops) ax.set_xticklabels(ops)
ax.set_ylabel("Среднее время (сек)") ax.set_ylabel("Среднее время (сек)")
ax.set_title("Сравнение структур данных") ax.set_title("Сравнение структур данных")
ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
ax.legend(
bbox_to_anchor=(1.05, 1),
loc="upper left"
)
plt.tight_layout() plt.tight_layout()
plt.savefig(graph_path) plt.savefig(graph_path)
print(f"График сохранён: {graph_path}") print(f"График сохранён: {graph_path}")
plt.show() plt.show()

View File

@ -18,17 +18,20 @@ class Cell:
self.is_wall = is_wall self.is_wall = is_wall
self.is_start = is_start self.is_start = is_start
self.is_exit = is_exit self.is_exit = is_exit
self.weight = 1 self.weight = 1 # Вес клетки (нужен для Дейкстры)
# Можно ли пройти через клетку
def isPassable(self): def isPassable(self):
return not self.is_wall return not self.is_wall
def __repr__(self): def __repr__(self):
return f"Cell({self.x},{self.y})" return f"Cell({self.x},{self.y})"
# Хеш по координатам — чтобы класть клетки в set и dict
def __hash__(self): def __hash__(self):
return hash((self.x, self.y)) return hash((self.x, self.y))
# Сравнение двух клеток (нужно для set и dict)
def __eq__(self, other): def __eq__(self, other):
return isinstance(other, Cell) and self.x == other.x and self.y == other.y return isinstance(other, Cell) and self.x == other.x and self.y == other.y
@ -37,35 +40,34 @@ class Maze:
def __init__(self, width, height): def __init__(self, width, height):
self.width = width self.width = width
self.height = height self.height = height
self.cells = [] self.cells = [] # Двумерный список: cells[y][x]
self.start = None self.start = None
self.exit = None self.exit = None
# Получить клетку по координатам, если она в границах лабиринта
def getCell(self, x, y): def getCell(self, x, y):
if 0 <= x < self.width and 0 <= y < self.height: if 0 <= x < self.width and 0 <= y < self.height:
return self.cells[y][x] return self.cells[y][x]
return None return None
# Получить всех соседей клетки (вверх, вниз, влево, вправо), кроме стен
def getNeighbors(self, cell): def getNeighbors(self, cell):
neighbors = [] neighbors = []
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]: # Четыре направления
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
nx = cell.x + dx nx = cell.x + dx
ny = cell.y + dy ny = cell.y + dy
neighbor = self.getCell(nx, ny) neighbor = self.getCell(nx, ny)
if neighbor and neighbor.isPassable(): if neighbor and neighbor.isPassable():
neighbors.append(neighbor) neighbors.append(neighbor)
return neighbors return neighbors
# То же самое, но возвращает пары (сосед, вес) — для Дейкстры
def getWeightedNeighbors(self, cell): def getWeightedNeighbors(self, cell):
return [(n, n.weight) for n in self.getNeighbors(cell)] return [(n, n.weight) for n in self.getNeighbors(cell)]
# ============================================================ # ============================================================
# ЭТАП 2. BUILDER # ЭТАП 2. ЗАГРУЗКА ЛАБИРИНТА ИЗ ФАЙЛА
# ============================================================ # ============================================================
class MazeBuilder: class MazeBuilder:
@ -74,75 +76,62 @@ class MazeBuilder:
class TextFileMazeBuilder(MazeBuilder): class TextFileMazeBuilder(MazeBuilder):
def buildFromFile(self, filename): def buildFromFile(self, filename):
# Читаем файл, убираем переносы строк
with open(filename, 'r', encoding='utf-8') as f: with open(filename, 'r', encoding='utf-8') as f:
lines = [line.rstrip('\n') for line in f] lines = [line.rstrip('\n') for line in f]
height = len(lines) height = len(lines)
width = max(len(line) for line in lines) width = max(len(line) for line in lines) # Берём самую длинную строку
maze = Maze(width, height) maze = Maze(width, height)
# Разбираем каждый символ в клетку
for y, line in enumerate(lines): for y, line in enumerate(lines):
row = [] row = []
for x, char in enumerate(line): for x, char in enumerate(line):
if char == '#': if char == '#':
cell = Cell(x, y, is_wall=True) cell = Cell(x, y, is_wall=True) # Стена
elif char == 'S': elif char == 'S':
cell = Cell(x, y, is_start=True) cell = Cell(x, y, is_start=True)
maze.start = cell maze.start = cell # Запомнили старт
elif char == 'E': elif char == 'E':
cell = Cell(x, y, is_exit=True) cell = Cell(x, y, is_exit=True)
maze.exit = cell maze.exit = cell # Запомнили выход
else: else:
cell = Cell(x, y) cell = Cell(x, y) # Пустая клетка
row.append(cell) row.append(cell)
# Если строка короче ширины — добиваем стенами
while len(row) < width: while len(row) < width:
row.append(Cell(len(row), y, is_wall=True)) row.append(Cell(len(row), y, is_wall=True))
maze.cells.append(row) maze.cells.append(row)
# Проверяем, что старт и выход есть
if maze.start is None or maze.exit is None: if maze.start is None or maze.exit is None:
raise ValueError("В лабиринте нет S или E") raise ValueError("В лабиринте нет S или E")
return maze return maze
# ============================================================ # ============================================================
# ВОССТАНОВЛЕНИЕ ПУТИ # ВОССТАНОВЛЕНИЕ ПУТИ ПО СЛОВАРЮ РОДИТЕЛЕЙ
# ============================================================ # ============================================================
def reconstruct_path(parents, end_cell): def reconstruct_path(parents, end_cell):
path = [] path = []
current = end_cell current = end_cell
# Идём от выхода к старту по цепочке parents
while current is not None: while current is not None:
path.append(current) path.append(current)
current = parents[current] current = parents[current]
path.reverse() # Разворачиваем — получаем путь от старта к выходу
path.reverse()
return path return path
# ============================================================ # ============================================================
# ЭТАП 3. STRATEGY # ЭТАП 3. АЛГОРИТМЫ ПОИСКА ПУТИ
# ============================================================ # ============================================================
class PathFindingStrategy: class PathFindingStrategy:
@property @property
def name(self): def name(self):
return "Unknown" return "Unknown"
@ -152,137 +141,89 @@ class PathFindingStrategy:
# ============================================================ # ============================================================
# BFS # BFS — обход в ширину (очередь)
# ============================================================ # ============================================================
class BFSStrategy(PathFindingStrategy): class BFSStrategy(PathFindingStrategy):
@property @property
def name(self): def name(self):
return "BFS" return "BFS"
def findPath(self, maze, start, exit): def findPath(self, maze, start, exit):
queue = deque([start]) # Очередь: кто первый зашёл — первый вышел
queue = deque([start])
visited = {start} visited = {start}
parents = {start: None} # Откуда пришли в клетку
parents = {
start: None
}
visited_count = 1 visited_count = 1
while queue: while queue:
current = queue.popleft() # Берём из начала очереди
current = queue.popleft()
if current == exit: if current == exit:
path = reconstruct_path(parents, exit) path = reconstruct_path(parents, exit)
return path, visited_count return path, visited_count
for neighbor in maze.getNeighbors(current): for neighbor in maze.getNeighbors(current):
if neighbor not in visited: if neighbor not in visited:
visited.add(neighbor) visited.add(neighbor)
parents[neighbor] = current parents[neighbor] = current
visited_count += 1 visited_count += 1
queue.append(neighbor) # Кладём в конец очереди
queue.append(neighbor)
return [], visited_count return [], visited_count
# ============================================================ # ============================================================
# DFS # DFS — обход в глубину (стек)
# ============================================================ # ============================================================
class DFSStrategy(PathFindingStrategy): class DFSStrategy(PathFindingStrategy):
@property @property
def name(self): def name(self):
return "DFS" return "DFS"
def findPath(self, maze, start, exit): def findPath(self, maze, start, exit):
stack = [start] # Стек: кто последний зашёл — первый вышел
stack = [start]
visited = {start} visited = {start}
parents = {start: None}
parents = {
start: None
}
visited_count = 1 visited_count = 1
while stack: while stack:
current = stack.pop() # Берём с вершины стека
current = stack.pop()
if current == exit: if current == exit:
path = reconstruct_path(parents, exit) path = reconstruct_path(parents, exit)
return path, visited_count return path, visited_count
for neighbor in maze.getNeighbors(current): for neighbor in maze.getNeighbors(current):
if neighbor not in visited: if neighbor not in visited:
visited.add(neighbor) visited.add(neighbor)
parents[neighbor] = current parents[neighbor] = current
visited_count += 1 visited_count += 1
stack.append(neighbor) # Кладём на вершину стека
stack.append(neighbor)
return [], visited_count return [], visited_count
# ============================================================ # ============================================================
# A* # A* — поиск с подсказкой (эвристикой)
# ============================================================ # ============================================================
class AStarStrategy(PathFindingStrategy): class AStarStrategy(PathFindingStrategy):
@property @property
def name(self): def name(self):
return "A*" return "A*"
# Подсказка: примерное расстояние до выхода (по прямой)
def heuristic(self, a, b): def heuristic(self, a, b):
return abs(a.x - b.x) + abs(a.y - b.y) return abs(a.x - b.x) + abs(a.y - b.y)
def findPath(self, maze, start, exit): def findPath(self, maze, start, exit):
counter = 0 # Чтобы различать клетки с одинаковым приоритетом
counter = 0 open_set = [] # Куча: всегда берём самую перспективную клетку
open_set = []
heapq.heappush(open_set, (0, counter, start)) heapq.heappush(open_set, (0, counter, start))
parents = {start: None}
parents = { g_score = {start: 0} # Пройденное расстояние от старта
start: None
}
g_score = {
start: 0
}
visited = set() visited = set()
visited_count = 0 visited_count = 0
while open_set: while open_set:
_, _, current = heapq.heappop(open_set) # Достаём клетку с лучшей оценкой
_, _, current = heapq.heappop(open_set)
if current in visited: if current in visited:
continue continue
visited.add(current) visited.add(current)
visited_count += 1 visited_count += 1
if current == exit: if current == exit:
@ -290,137 +231,86 @@ class AStarStrategy(PathFindingStrategy):
return path, visited_count return path, visited_count
for neighbor in maze.getNeighbors(current): for neighbor in maze.getNeighbors(current):
tentative_g = g_score[current] + 1 # Расстояние до соседа через текущую
tentative_g = g_score[current] + 1
if neighbor not in g_score or tentative_g < g_score[neighbor]: if neighbor not in g_score or tentative_g < g_score[neighbor]:
g_score[neighbor] = tentative_g g_score[neighbor] = tentative_g
parents[neighbor] = current parents[neighbor] = current
# Оценка клетки = пройденный путь + подсказка до выхода
f_score = tentative_g + self.heuristic(neighbor, exit) f_score = tentative_g + self.heuristic(neighbor, exit)
counter += 1 counter += 1
heapq.heappush(open_set, (f_score, counter, neighbor))
heapq.heappush(
open_set,
(f_score, counter, neighbor)
)
return [], visited_count return [], visited_count
# ============================================================ # ============================================================
# DIJKSTRA # ДЕЙКСТРА — поиск с учётом весов клеток
# ============================================================ # ============================================================
class DijkstraStrategy(PathFindingStrategy): class DijkstraStrategy(PathFindingStrategy):
@property @property
def name(self): def name(self):
return "Dijkstra" return "Dijkstra"
def findPath(self, maze, start, exit): def findPath(self, maze, start, exit):
counter = 0 counter = 0
queue = [] # Куча: всегда берём клетку с кратчайшим путём от старта
queue = []
heapq.heappush(queue, (0, counter, start)) heapq.heappush(queue, (0, counter, start))
distances = {start: 0} # Кратчайшее известное расстояние до каждой клетки
distances = { parents = {start: None}
start: 0
}
parents = {
start: None
}
visited = set() visited = set()
visited_count = 0 visited_count = 0
while queue: while queue:
dist, _, current = heapq.heappop(queue) # Достаём ближайшую клетку
dist, _, current = heapq.heappop(queue)
if current in visited: if current in visited:
continue continue
visited.add(current) visited.add(current)
visited_count += 1 visited_count += 1
if current == exit: if current == exit:
path = reconstruct_path(parents, exit) path = reconstruct_path(parents, exit)
return path, visited_count return path, visited_count
# Здесь используем вес клеток, а не просто +1
for neighbor, weight in maze.getWeightedNeighbors(current): for neighbor, weight in maze.getWeightedNeighbors(current):
new_dist = dist + weight new_dist = dist + weight
if neighbor not in distances or new_dist < distances[neighbor]: if neighbor not in distances or new_dist < distances[neighbor]:
distances[neighbor] = new_dist distances[neighbor] = new_dist
parents[neighbor] = current parents[neighbor] = current
counter += 1 counter += 1
heapq.heappush(queue, (new_dist, counter, neighbor))
heapq.heappush(
queue,
(new_dist, counter, neighbor)
)
return [], visited_count return [], visited_count
# ============================================================ # ============================================================
# ЭТАП 4. STATS + SOLVER # ЭТАП 4. РЕШАТЕЛЬ И СТАТИСТИКА
# ============================================================ # ============================================================
class SearchStats: class SearchStats:
def __init__(self, strategy_name, time_ms, visited_cells, path_length, path_found):
def __init__(
self,
strategy_name,
time_ms,
visited_cells,
path_length,
path_found
):
self.strategy_name = strategy_name self.strategy_name = strategy_name
self.time_ms = time_ms self.time_ms = time_ms # Время в миллисекундах
self.visited_cells = visited_cells self.visited_cells = visited_cells # Сколько клеток посетили
self.path_length = path_length self.path_length = path_length # Длина найденного пути
self.path_found = path_found self.path_found = path_found # Нашли путь или нет
class MazeSolver: class MazeSolver:
def __init__(self, maze, strategy=None): def __init__(self, maze, strategy=None):
self.maze = maze self.maze = maze
self.strategy = strategy self.strategy = strategy
# Сменить алгоритм поиска
def setStrategy(self, strategy): def setStrategy(self, strategy):
self.strategy = strategy self.strategy = strategy
def solve(self): def solve(self):
if self.strategy is None: if self.strategy is None:
raise ValueError("Стратегия не выбрана") raise ValueError("Стратегия не выбрана")
# Засекаем время и запускаем алгоритм
start_time = time.perf_counter() start_time = time.perf_counter()
path, visited = self.strategy.findPath(self.maze, self.maze.start, self.maze.exit)
path, visited = self.strategy.findPath(
self.maze,
self.maze.start,
self.maze.exit
)
end_time = time.perf_counter() end_time = time.perf_counter()
elapsed_ms = (end_time - start_time) * 1000 elapsed_ms = (end_time - start_time) * 1000
return SearchStats( return SearchStats(
@ -433,171 +323,126 @@ class MazeSolver:
# ============================================================ # ============================================================
# ВИЗУАЛИЗАЦИЯ # ВЫВОД ЛАБИРИНТА В КОНСОЛЬ
# ============================================================ # ============================================================
def render(maze, path=None): def render(maze, path=None):
path_set = set(path) if path else set() # Для быстрой проверки "клетка на пути?"
path_set = set(path) if path else set()
for y in range(maze.height): for y in range(maze.height):
line = "" line = ""
for x in range(maze.width): for x in range(maze.width):
cell = maze.getCell(x, y) cell = maze.getCell(x, y)
if cell == maze.start: if cell == maze.start:
line += "S" line += "S"
elif cell == maze.exit: elif cell == maze.exit:
line += "E" line += "E"
elif cell in path_set: elif cell in path_set:
line += "." line += "." # Точка — клетка пути
elif cell.is_wall: elif cell.is_wall:
line += "#" line += "#"
else: else:
line += " " line += " "
print(line) print(line)
print() print()
# ============================================================ # ============================================================
# ФАЙЛЫ И ПУТИ # ПУТИ ДЛЯ СОХРАНЕНИЯ ФАЙЛОВ
# ============================================================ # ============================================================
OUTPUT_DIR = os.path.join("docs", "data") OUTPUT_DIR = os.path.join("docs", "data")
PREFIX = "_2lab" PREFIX = "_2lab"
os.makedirs(OUTPUT_DIR, exist_ok=True) # Создаём папку, если её нет
os.makedirs(OUTPUT_DIR, exist_ok=True)
def get_path(filename): def get_path(filename):
name, ext = os.path.splitext(filename) name, ext = os.path.splitext(filename)
return os.path.join(OUTPUT_DIR, f"{name}{PREFIX}{ext}")
return os.path.join(
OUTPUT_DIR,
f"{name}{PREFIX}{ext}"
)
# ============================================================ # ============================================================
# СОЗДАНИЕ ЛАБИРИНТА # СОЗДАНИЕ ЛАБИРИНТА ИЗ СПИСКА СТРОК
# ============================================================ # ============================================================
def create_test_maze(filename, lines): def create_test_maze(filename, lines):
with open(filename, 'w', encoding='utf-8') as f: with open(filename, 'w', encoding='utf-8') as f:
for line in lines: for line in lines:
f.write(line + '\n') f.write(line + '\n')
return filename return filename
# ============================================================ # ============================================================
# ГЕНЕРАЦИЯ # ГЕНЕРАЦИЯ ЛАБИРИНТОВ
# ============================================================ # ============================================================
# Случайный лабиринт с гарантированным путём
def generate_maze(width, height, wall_density=0.3): def generate_maze(width, height, wall_density=0.3):
grid = [[' ' for _ in range(width)] for _ in range(height)] grid = [[' ' for _ in range(width)] for _ in range(height)]
# Ставим стены по краям
for x in range(width): for x in range(width):
grid[0][x] = '#' grid[0][x] = '#'
grid[height - 1][x] = '#' grid[height - 1][x] = '#'
for y in range(height): for y in range(height):
grid[y][0] = '#' grid[y][0] = '#'
grid[y][width - 1] = '#' grid[y][width - 1] = '#'
# Прокладываем гарантированную дорожку от (1,1) до (width-2, height-2)
x, y = 1, 1 x, y = 1, 1
path_cells = {(x, y)} path_cells = {(x, y)}
while x < width - 2 or y < height - 2: while x < width - 2 or y < height - 2:
if x < width - 2 and random.random() > 0.3: if x < width - 2 and random.random() > 0.3:
x += 1 x += 1
elif y < height - 2: elif y < height - 2:
y += 1 y += 1
else: else:
x += 1 x += 1
path_cells.add((x, y)) path_cells.add((x, y))
# Случайно расставляем стены, но не на дорожке
for yy in range(1, height - 1): for yy in range(1, height - 1):
for xx in range(1, width - 1): for xx in range(1, width - 1):
if (xx, yy) not in path_cells: if (xx, yy) not in path_cells:
if random.random() < wall_density: if random.random() < wall_density:
grid[yy][xx] = '#' grid[yy][xx] = '#'
# Ставим старт и выход по углам
grid[1][1] = 'S' grid[1][1] = 'S'
grid[height - 2][width - 2] = 'E' grid[height - 2][width - 2] = 'E'
return [''.join(row) for row in grid] return [''.join(row) for row in grid]
# Пустой лабиринт без стен
def generate_empty_maze(size): def generate_empty_maze(size):
lines = [" " * size for _ in range(size)] lines = [" " * size for _ in range(size)]
lines[0] = "S" + " " * (size - 1) lines[0] = "S" + " " * (size - 1)
lines[size - 1] = " " * (size - 1) + "E" lines[size - 1] = " " * (size - 1) + "E"
return lines return lines
# Лабиринт, где выход замурован со всех сторон
def generate_no_exit_maze(size): def generate_no_exit_maze(size):
lines = generate_maze(size, size, wall_density=0.2) lines = generate_maze(size, size, wall_density=0.2)
for y, line in enumerate(lines): for y, line in enumerate(lines):
if 'E' in line: if 'E' in line:
x = line.index('E') x = line.index('E')
# Окружаем выход стенами
for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]: for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ny, nx = y + dy, x + dx
ny = y + dy
nx = x + dx
if 0 <= ny < size and 0 <= nx < size: if 0 <= ny < size and 0 <= nx < size:
if lines[ny][nx] == ' ': if lines[ny][nx] == ' ':
lines[ny] = lines[ny][:nx] + '#' + lines[ny][nx + 1:]
lines[ny] = (
lines[ny][:nx]
+ '#'
+ lines[ny][nx + 1:]
)
return lines return lines
# ============================================================ # ============================================================
# ЭКСПЕРИМЕНТЫ # ЗАПУСК ЭКСПЕРИМЕНТОВ
# ============================================================ # ============================================================
def run_experiments(): def run_experiments():
# Набор лабиринтов для тестов
mazes = { mazes = {
"small": [ "small": [
"##########", "##########",
"#S #", "#S #",
@ -610,16 +455,13 @@ def run_experiments():
"# E#", "# E#",
"##########" "##########"
], ],
"medium": generate_maze(50, 50, 0.35), "medium": generate_maze(50, 50, 0.35),
"large": generate_maze(100, 100, 0.4), "large": generate_maze(100, 100, 0.4),
"empty": generate_empty_maze(20), "empty": generate_empty_maze(20),
"no_exit": generate_no_exit_maze(15) "no_exit": generate_no_exit_maze(15)
} }
# Список алгоритмов
strategies = [ strategies = [
BFSStrategy(), BFSStrategy(),
DFSStrategy(), DFSStrategy(),
@ -634,39 +476,28 @@ def run_experiments():
print("=" * 60) print("=" * 60)
for maze_name, lines in mazes.items(): for maze_name, lines in mazes.items():
filename = get_path(f"{maze_name}.txt") filename = get_path(f"{maze_name}.txt")
create_test_maze(filename, lines) create_test_maze(filename, lines)
maze = TextFileMazeBuilder().buildFromFile(filename) maze = TextFileMazeBuilder().buildFromFile(filename)
print(f"\nЛабиринт: {maze_name}") print(f"\nЛабиринт: {maze_name}")
print("-" * 60) print("-" * 60)
for strategy in strategies: for strategy in strategies:
times = [] times = []
visited_values = [] visited_values = []
final_path_len = 0 final_path_len = 0
# Запускаем 5 раз и считаем среднее время
for _ in range(5): for _ in range(5):
solver = MazeSolver(maze) solver = MazeSolver(maze)
solver.setStrategy(strategy) solver.setStrategy(strategy)
stats, path = solver.solve() stats, path = solver.solve()
times.append(stats.time_ms) times.append(stats.time_ms)
visited_values.append(stats.visited_cells) visited_values.append(stats.visited_cells)
final_path_len = stats.path_length final_path_len = stats.path_length
avg_time = sum(times) / len(times) avg_time = sum(times) / len(times)
avg_visited = sum(visited_values) / len(visited_values) avg_visited = sum(visited_values) / len(visited_values)
results.append({ results.append({
@ -678,110 +509,61 @@ def run_experiments():
}) })
status = "найден" if final_path_len > 0 else "не найден" status = "найден" if final_path_len > 0 else "не найден"
print(f"{strategy.name:<10} | {avg_time:>8.4f} мс | {int(avg_visited):>5} клеток | путь {status}")
print( # Сохраняем всё в CSV
f"{strategy.name:<10} | "
f"{avg_time:>8.4f} мс | "
f"{int(avg_visited):>5} клеток | "
f"путь {status}"
)
csv_path = get_path("results.csv") csv_path = get_path("results.csv")
with open(csv_path, "w", newline="", encoding='utf-8') as f: with open(csv_path, "w", newline="", encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=["maze", "strategy", "time_ms", "visited", "path_length"])
writer = csv.DictWriter(
f,
fieldnames=[
"maze",
"strategy",
"time_ms",
"visited",
"path_length"
]
)
writer.writeheader() writer.writeheader()
writer.writerows(results) writer.writerows(results)
print(f"\nCSV сохранён: {csv_path}") print(f"\nCSV сохранён: {csv_path}")
return results return results
# ============================================================ # ============================================================
# ГРАФИК # ПОСТРОЕНИЕ ГРАФИКА
# ============================================================ # ============================================================
def build_charts(results): def build_charts(results):
mazes = list(dict.fromkeys(r["maze"] for r in results)) # Список лабиринтов без повторов
mazes = list(dict.fromkeys(r["maze"] for r in results)) strategies = list(dict.fromkeys(r["strategy"] for r in results)) # Список стратегий без повторов
strategies = list(dict.fromkeys(r["strategy"] for r in results))
fig, ax = plt.subplots(figsize=(12, 6)) fig, ax = plt.subplots(figsize=(12, 6))
x = range(len(mazes)) x = range(len(mazes))
width = 0.2 # Ширина одного столбика
width = 0.2 # Цвета для каждого алгоритма
colors = {'BFS': '#3498db', 'DFS': '#e74c3c', 'A*': '#2ecc71', 'Dijkstra': '#f39c12'}
colors = {
'BFS': '#3498db',
'DFS': '#e74c3c',
'A*': '#2ecc71',
'Dijkstra': '#f39c12'
}
for i, strategy in enumerate(strategies): for i, strategy in enumerate(strategies):
# Берём время этой стратегии для всех лабиринтов
times = [ times = [r["time_ms"] for r in results if r["strategy"] == strategy]
r["time_ms"] # Рисуем столбики рядом друг с другом
for r in results ax.bar([j + i * width for j in x], times, width, label=strategy, color=colors.get(strategy, 'gray'))
if r["strategy"] == strategy
]
ax.bar(
[j + i * width for j in x],
times,
width,
label=strategy,
color=colors.get(strategy, 'gray')
)
ax.set_xlabel("Лабиринт") ax.set_xlabel("Лабиринт")
ax.set_ylabel("Время (мс)") ax.set_ylabel("Время (мс)")
ax.set_title("Сравнение алгоритмов") ax.set_title("Сравнение алгоритмов")
ax.set_xticks([j + width * 1.5 for j in x]) # Подписи по центру группы
ax.set_xticks([j + width * 1.5 for j in x])
ax.set_xticklabels(mazes) ax.set_xticklabels(mazes)
ax.legend() ax.legend()
ax.grid(axis='y', alpha=0.3) ax.grid(axis='y', alpha=0.3)
plt.tight_layout() plt.tight_layout()
chart_path = get_path("chart_time.png") chart_path = get_path("chart_time.png")
plt.savefig(chart_path, dpi=150, bbox_inches='tight') plt.savefig(chart_path, dpi=150, bbox_inches='tight')
print(f"График сохранён: {chart_path}") print(f"График сохранён: {chart_path}")
plt.show() plt.show()
# ============================================================ # ============================================================
# MAIN # ГЛАВНАЯ ФУНКЦИЯ
# ============================================================ # ============================================================
def main(): def main():
results = run_experiments() results = run_experiments()
build_charts(results) build_charts(results)