[5]+komments
This commit is contained in:
parent
f4e8b9732e
commit
bd678b4716
|
|
@ -1,136 +1,153 @@
|
|||
import sys
|
||||
sys.setrecursionlimit(30000)
|
||||
|
||||
csv_path = '/stepinim/docs/data/lab1_results.csv'
|
||||
sys.setrecursionlimit(30000) # Увеличиваю лимит рекурсии для BST
|
||||
|
||||
#Связный список
|
||||
# Связный список
|
||||
def ll_insert(head, name, phone):
|
||||
new_node = {'name': name, 'phone': phone, 'next': None}
|
||||
if head is None:
|
||||
return new_node
|
||||
new_node = {'name': name, 'phone': phone, 'next': None} # Создаю новый узел
|
||||
if head is None: # Если список пуст
|
||||
return new_node # Возвращаю узел как голову
|
||||
|
||||
curr = head
|
||||
prev = None
|
||||
while curr is not None:
|
||||
if curr['name'] == name:
|
||||
curr['phone'] = phone
|
||||
curr = head # Указатель для обхода
|
||||
prev = None # Храню предыдущий узел
|
||||
while curr is not None: # Иду по списку
|
||||
if curr['name'] == name: # Если нашел такое же имя
|
||||
curr['phone'] = phone # Обновляю телефон
|
||||
return head
|
||||
prev = curr
|
||||
curr = curr['next']
|
||||
prev['next'] = new_node
|
||||
prev['next'] = new_node # Добавляю в конец
|
||||
return head
|
||||
|
||||
|
||||
def ll_find(head, name):
|
||||
curr = head
|
||||
while curr:
|
||||
if curr['name'] == name:
|
||||
return curr['phone']
|
||||
curr = curr['next']
|
||||
return None
|
||||
curr = head # Начинаю с головы
|
||||
while curr: # Иду по всему списку
|
||||
if curr['name'] == name: # Сравниваю имена
|
||||
return curr['phone'] # Возвращаю телефон
|
||||
curr = curr['next'] # Перехожу к следующему
|
||||
return None # Не нашел
|
||||
|
||||
|
||||
def ll_delete(head, name):
|
||||
if head is None:
|
||||
if head is None: # Пустой список
|
||||
return None
|
||||
if head['name'] == name:
|
||||
return head['next']
|
||||
if head['name'] == name: # Удаляю голову
|
||||
return head['next'] # Возвращаю второй элемент
|
||||
curr = head
|
||||
while curr['next']:
|
||||
if curr['next']['name'] == name:
|
||||
curr['next'] = curr['next']['next']
|
||||
while curr['next']: # Иду пока есть следующий
|
||||
if curr['next']['name'] == name: # Нашел элемент для удаления
|
||||
curr['next'] = curr['next']['next'] # Перепрыгиваю через него
|
||||
return head
|
||||
curr = curr['next']
|
||||
return head
|
||||
|
||||
|
||||
def ll_list_all(head):
|
||||
result = []
|
||||
curr = head
|
||||
while curr:
|
||||
while curr: # Собираю все элементы
|
||||
result.append((curr['name'], curr['phone']))
|
||||
curr = curr['next']
|
||||
result.sort(key=lambda x: x[0])
|
||||
result.sort(key=lambda x: x[0]) # Сортирую по имени
|
||||
return result
|
||||
|
||||
#Хэш-таблица
|
||||
HASH_SIZE = 1009
|
||||
|
||||
# Хэш-таблица
|
||||
HASH_SIZE = 1009 # Размер таблицы - простое число
|
||||
|
||||
|
||||
def _hash_name(name):
|
||||
return hash(name) % HASH_SIZE
|
||||
return hash(name) % HASH_SIZE # Беру остаток от деления - это индекс корзины
|
||||
|
||||
|
||||
def ht_insert(buckets, name, phone):
|
||||
idx = _hash_name(name)
|
||||
buckets[idx] = ll_insert(buckets[idx], name, phone)
|
||||
idx = _hash_name(name) # Вычисляю индекс корзины
|
||||
buckets[idx] = ll_insert(buckets[idx], name, phone) # Метод цепочек - вставляю в список
|
||||
|
||||
|
||||
def ht_find(buckets, name):
|
||||
idx = _hash_name(name)
|
||||
return ll_find(buckets[idx], name)
|
||||
idx = _hash_name(name) # Нахожу корзину
|
||||
return ll_find(buckets[idx], name) # Ищу в цепочке
|
||||
|
||||
|
||||
def ht_delete(buckets, name):
|
||||
idx = _hash_name(name)
|
||||
buckets[idx] = ll_delete(buckets[idx], name)
|
||||
idx = _hash_name(name) # Нахожу корзину
|
||||
buckets[idx] = ll_delete(buckets[idx], name) # Удаляю из цепочки
|
||||
|
||||
|
||||
def ht_list_all(buckets):
|
||||
all_entries = []
|
||||
for bucket in buckets:
|
||||
for bucket in buckets: # Прохожу по всем корзинам
|
||||
if bucket is not None:
|
||||
curr = bucket
|
||||
while curr:
|
||||
while curr: # Собираю всю цепочку
|
||||
all_entries.append((curr['name'], curr['phone']))
|
||||
curr = curr['next']
|
||||
all_entries.sort(key=lambda x: x[0])
|
||||
return all_entries
|
||||
|
||||
#Двоичное дерево поиска
|
||||
|
||||
# Двоичное дерево поиска
|
||||
def bst_insert(root, name, phone):
|
||||
if root is None:
|
||||
if root is None: # Пустое место - создаю узел
|
||||
return {'name': name, 'phone': phone, 'left': None, 'right': None}
|
||||
if name < root['name']:
|
||||
root['left'] = bst_insert(root['left'], name, phone)
|
||||
elif name > root['name']:
|
||||
root['right'] = bst_insert(root['right'], name, phone)
|
||||
else:
|
||||
if name < root['name']: # Меньше - иду влево
|
||||
root['left'] = bst_insert(root['left'], name, phone) # Рекурсивно вставляю в левое поддерево
|
||||
elif name > root['name']: # Больше - иду вправо
|
||||
root['right'] = bst_insert(root['right'], name, phone) # Рекурсивно вставляю в правое поддерево
|
||||
else: # Равно - обновляю
|
||||
root['phone'] = phone
|
||||
return root
|
||||
|
||||
|
||||
def bst_find(root, name):
|
||||
curr = root
|
||||
while curr:
|
||||
if name == curr['name']:
|
||||
while curr: # Итеративный спуск по дереву
|
||||
if name == curr['name']: # Нашел
|
||||
return curr['phone']
|
||||
elif name < curr['name']:
|
||||
elif name < curr['name']: # Искомое меньше - налево
|
||||
curr = curr['left']
|
||||
else:
|
||||
else: # Искомое больше - направо
|
||||
curr = curr['right']
|
||||
return None
|
||||
|
||||
|
||||
def bst_delete(root, name):
|
||||
if root is None:
|
||||
return None
|
||||
if name < root['name']:
|
||||
if name < root['name']: # Ищу в левом поддереве
|
||||
root['left'] = bst_delete(root['left'], name)
|
||||
elif name > root['name']:
|
||||
elif name > root['name']: # Ищу в правом поддереве
|
||||
root['right'] = bst_delete(root['right'], name)
|
||||
else:
|
||||
if root['left'] is None:
|
||||
return root['right']
|
||||
if root['right'] is None:
|
||||
return root['left']
|
||||
else: # Нашел узел для удаления
|
||||
if root['left'] is None: # Нет левого ребенка
|
||||
return root['right'] # Заменяю правым
|
||||
if root['right'] is None: # Нет правого ребенка
|
||||
return root['left'] # Заменяю левым
|
||||
# Есть оба ребенка - ищу минимальный в правом поддереве
|
||||
min_node = root['right']
|
||||
while min_node['left']:
|
||||
while min_node['left']: # Иду до самого левого
|
||||
min_node = min_node['left']
|
||||
root['name'] = min_node['name']
|
||||
root['name'] = min_node['name'] # Копирую данные преемника
|
||||
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
|
||||
|
||||
|
||||
def bst_list_all(root):
|
||||
result = []
|
||||
def inorder(node):
|
||||
|
||||
def inorder(node): # Симметричный обход
|
||||
if node:
|
||||
inorder(node['left'])
|
||||
result.append((node['name'], node['phone']))
|
||||
inorder(node['right'])
|
||||
inorder(node['left']) # Сначала левое
|
||||
result.append((node['name'], node['phone'])) # Потом корень
|
||||
inorder(node['right']) # Потом правое
|
||||
|
||||
inorder(root)
|
||||
return result
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 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 = [
|
||||
(f"User_{i:05d}", f"123-{i:05d}")
|
||||
|
|
@ -166,53 +183,47 @@ base_records = [
|
|||
]
|
||||
|
||||
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 = [
|
||||
name for name, _ in random.sample(base_records, 100)
|
||||
name for name, _ in random.sample(base_records, 100) # 100 существующих имен
|
||||
]
|
||||
|
||||
search_nonexist = [
|
||||
f"None_{i}"
|
||||
for i in range(10)
|
||||
for i in range(10) # 10 несуществующих имен
|
||||
]
|
||||
|
||||
# Удаление
|
||||
# Данные для удаления
|
||||
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):
|
||||
|
||||
if struct_type == "ll":
|
||||
structure = None
|
||||
|
||||
for name, phone in records:
|
||||
structure = ll_insert(structure, name, phone)
|
||||
|
||||
structure = ll_insert(structure, name, phone) # Последовательная вставка
|
||||
return structure
|
||||
|
||||
elif struct_type == "ht":
|
||||
structure = [None] * HASH_SIZE
|
||||
|
||||
for name, phone in records:
|
||||
ht_insert(structure, name, phone)
|
||||
|
||||
ht_insert(structure, name, phone) # Вставка с хэшированием
|
||||
return structure
|
||||
|
||||
elif struct_type == "bst":
|
||||
structure = None
|
||||
|
||||
for name, phone in records:
|
||||
structure = bst_insert(structure, name, phone)
|
||||
|
||||
structure = bst_insert(structure, name, phone) # Вставка с ветвлением
|
||||
return structure
|
||||
|
||||
|
||||
|
|
@ -221,13 +232,9 @@ def build_structure(records, struct_type):
|
|||
# ============================================================
|
||||
|
||||
def measure_insert(records, struct_type):
|
||||
|
||||
start = time.perf_counter()
|
||||
|
||||
build_structure(records, struct_type)
|
||||
|
||||
build_structure(records, struct_type) # Замеряю время построения структуры
|
||||
end = time.perf_counter()
|
||||
|
||||
return end - start
|
||||
|
||||
|
||||
|
|
@ -236,25 +243,20 @@ def measure_insert(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()
|
||||
|
||||
if struct_type == "ll":
|
||||
for name in search_existing + search_nonexist:
|
||||
ll_find(structure, name)
|
||||
|
||||
ll_find(structure, name) # Поиск перебором
|
||||
elif struct_type == "ht":
|
||||
for name in search_existing + search_nonexist:
|
||||
ht_find(structure, name)
|
||||
|
||||
ht_find(structure, name) # Поиск через хэш
|
||||
elif struct_type == "bst":
|
||||
for name in search_existing + search_nonexist:
|
||||
bst_find(structure, name)
|
||||
bst_find(structure, name) # Поиск спуском по дереву
|
||||
|
||||
end = time.perf_counter()
|
||||
|
||||
return end - start
|
||||
|
||||
|
||||
|
|
@ -263,25 +265,20 @@ def measure_search(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()
|
||||
|
||||
if struct_type == "ll":
|
||||
for name in delete_names:
|
||||
structure = ll_delete(structure, name)
|
||||
|
||||
structure = ll_delete(structure, name) # Удаление со сдвигом
|
||||
elif struct_type == "ht":
|
||||
for name in delete_names:
|
||||
ht_delete(structure, name)
|
||||
|
||||
ht_delete(structure, name) # Удаление из цепочки
|
||||
elif struct_type == "bst":
|
||||
for name in delete_names:
|
||||
structure = bst_delete(structure, name)
|
||||
structure = bst_delete(structure, name) # Удаление с ребалансировкой
|
||||
|
||||
end = time.perf_counter()
|
||||
|
||||
return end - start
|
||||
|
||||
|
||||
|
|
@ -298,62 +295,28 @@ experiments = [
|
|||
]
|
||||
|
||||
modes = [
|
||||
("shuffled", records_shuffled),
|
||||
("sorted", records_sorted)
|
||||
("shuffled", records_shuffled), # Тест на случайных данных
|
||||
("sorted", records_sorted) # Тест на отсортированных данных
|
||||
]
|
||||
|
||||
for struct_name, struct_type in experiments:
|
||||
|
||||
for mode_name, records in modes:
|
||||
|
||||
for rep in range(1, 4):
|
||||
|
||||
for rep in range(1, 4): # 3 повтора для усреднения
|
||||
insert_time = measure_insert(records, struct_type)
|
||||
|
||||
search_time = measure_search(records, struct_type)
|
||||
|
||||
delete_time = measure_delete(records, struct_type)
|
||||
|
||||
all_data.append([
|
||||
struct_name,
|
||||
mode_name,
|
||||
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
|
||||
])
|
||||
all_data.append([struct_name, mode_name, 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
|
||||
# ============================================================
|
||||
|
||||
with open(csv_path, "w", newline="", encoding="utf-8") as f:
|
||||
|
||||
writer = csv.writer(f)
|
||||
|
||||
writer.writerow([
|
||||
"Структура",
|
||||
"Режим",
|
||||
"Повтор",
|
||||
"Операция",
|
||||
"Время (сек)"
|
||||
])
|
||||
|
||||
writer.writerow(["Структура", "Режим", "Повтор", "Операция", "Время (сек)"])
|
||||
writer.writerows(all_data)
|
||||
|
||||
print(f"CSV сохранён: {csv_path}")
|
||||
|
|
@ -365,9 +328,7 @@ print(f"CSV сохранён: {csv_path}")
|
|||
df = pd.read_csv(csv_path)
|
||||
|
||||
df_avg = (
|
||||
df.groupby(
|
||||
["Структура", "Режим", "Операция"]
|
||||
)["Время (сек)"]
|
||||
df.groupby(["Структура", "Режим", "Операция"])["Время (сек)"]
|
||||
.mean()
|
||||
.reset_index()
|
||||
)
|
||||
|
|
@ -375,9 +336,7 @@ df_avg = (
|
|||
fig, ax = plt.subplots(figsize=(12, 6))
|
||||
|
||||
ops = ["insert", "search", "delete"]
|
||||
|
||||
x = range(len(ops))
|
||||
|
||||
width = 0.12
|
||||
|
||||
configs = [
|
||||
|
|
@ -390,20 +349,14 @@ configs = [
|
|||
]
|
||||
|
||||
for i, (struct, mode) in enumerate(configs):
|
||||
|
||||
subset = df_avg[
|
||||
(df_avg["Структура"] == struct)
|
||||
&
|
||||
(df_avg["Структура"] == struct) &
|
||||
(df_avg["Режим"] == mode)
|
||||
]
|
||||
|
||||
]
|
||||
times = [
|
||||
subset[
|
||||
subset["Операция"] == op
|
||||
]["Время (сек)"].values[0]
|
||||
subset[subset["Операция"] == op]["Время (сек)"].values[0]
|
||||
for op in ops
|
||||
]
|
||||
|
||||
ax.bar(
|
||||
[p + i * width for p in x],
|
||||
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_xticklabels(ops)
|
||||
|
||||
ax.set_ylabel("Среднее время (сек)")
|
||||
|
||||
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.savefig(graph_path)
|
||||
|
||||
print(f"График сохранён: {graph_path}")
|
||||
|
||||
plt.show()
|
||||
|
|
@ -18,17 +18,20 @@ class Cell:
|
|||
self.is_wall = is_wall
|
||||
self.is_start = is_start
|
||||
self.is_exit = is_exit
|
||||
self.weight = 1
|
||||
self.weight = 1 # Вес клетки (нужен для Дейкстры)
|
||||
|
||||
# Можно ли пройти через клетку
|
||||
def isPassable(self):
|
||||
return not self.is_wall
|
||||
|
||||
def __repr__(self):
|
||||
return f"Cell({self.x},{self.y})"
|
||||
|
||||
# Хеш по координатам — чтобы класть клетки в set и dict
|
||||
def __hash__(self):
|
||||
return hash((self.x, self.y))
|
||||
|
||||
# Сравнение двух клеток (нужно для set и dict)
|
||||
def __eq__(self, other):
|
||||
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):
|
||||
self.width = width
|
||||
self.height = height
|
||||
self.cells = []
|
||||
self.cells = [] # Двумерный список: cells[y][x]
|
||||
self.start = None
|
||||
self.exit = None
|
||||
|
||||
# Получить клетку по координатам, если она в границах лабиринта
|
||||
def getCell(self, x, y):
|
||||
if 0 <= x < self.width and 0 <= y < self.height:
|
||||
return self.cells[y][x]
|
||||
return None
|
||||
|
||||
# Получить всех соседей клетки (вверх, вниз, влево, вправо), кроме стен
|
||||
def getNeighbors(self, cell):
|
||||
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
|
||||
ny = cell.y + dy
|
||||
|
||||
neighbor = self.getCell(nx, ny)
|
||||
|
||||
if neighbor and neighbor.isPassable():
|
||||
neighbors.append(neighbor)
|
||||
|
||||
return neighbors
|
||||
|
||||
# То же самое, но возвращает пары (сосед, вес) — для Дейкстры
|
||||
def getWeightedNeighbors(self, cell):
|
||||
return [(n, n.weight) for n in self.getNeighbors(cell)]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ЭТАП 2. BUILDER
|
||||
# ЭТАП 2. ЗАГРУЗКА ЛАБИРИНТА ИЗ ФАЙЛА
|
||||
# ============================================================
|
||||
|
||||
class MazeBuilder:
|
||||
|
|
@ -74,75 +76,62 @@ class MazeBuilder:
|
|||
|
||||
|
||||
class TextFileMazeBuilder(MazeBuilder):
|
||||
|
||||
def buildFromFile(self, filename):
|
||||
|
||||
# Читаем файл, убираем переносы строк
|
||||
with open(filename, 'r', encoding='utf-8') as f:
|
||||
lines = [line.rstrip('\n') for line in f]
|
||||
|
||||
height = len(lines)
|
||||
width = max(len(line) for line in lines)
|
||||
|
||||
width = max(len(line) for line in lines) # Берём самую длинную строку
|
||||
maze = Maze(width, height)
|
||||
|
||||
# Разбираем каждый символ в клетку
|
||||
for y, line in enumerate(lines):
|
||||
|
||||
row = []
|
||||
|
||||
for x, char in enumerate(line):
|
||||
|
||||
if char == '#':
|
||||
cell = Cell(x, y, is_wall=True)
|
||||
|
||||
cell = Cell(x, y, is_wall=True) # Стена
|
||||
elif char == 'S':
|
||||
cell = Cell(x, y, is_start=True)
|
||||
maze.start = cell
|
||||
|
||||
maze.start = cell # Запомнили старт
|
||||
elif char == 'E':
|
||||
cell = Cell(x, y, is_exit=True)
|
||||
maze.exit = cell
|
||||
|
||||
maze.exit = cell # Запомнили выход
|
||||
else:
|
||||
cell = Cell(x, y)
|
||||
|
||||
cell = Cell(x, y) # Пустая клетка
|
||||
row.append(cell)
|
||||
|
||||
# Если строка короче ширины — добиваем стенами
|
||||
while len(row) < width:
|
||||
row.append(Cell(len(row), y, is_wall=True))
|
||||
|
||||
maze.cells.append(row)
|
||||
|
||||
# Проверяем, что старт и выход есть
|
||||
if maze.start is None or maze.exit is None:
|
||||
raise ValueError("В лабиринте нет S или E")
|
||||
|
||||
return maze
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ВОССТАНОВЛЕНИЕ ПУТИ
|
||||
# ВОССТАНОВЛЕНИЕ ПУТИ ПО СЛОВАРЮ РОДИТЕЛЕЙ
|
||||
# ============================================================
|
||||
|
||||
def reconstruct_path(parents, end_cell):
|
||||
|
||||
path = []
|
||||
|
||||
current = end_cell
|
||||
|
||||
# Идём от выхода к старту по цепочке parents
|
||||
while current is not None:
|
||||
path.append(current)
|
||||
current = parents[current]
|
||||
|
||||
path.reverse()
|
||||
|
||||
path.reverse() # Разворачиваем — получаем путь от старта к выходу
|
||||
return path
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ЭТАП 3. STRATEGY
|
||||
# ЭТАП 3. АЛГОРИТМЫ ПОИСКА ПУТИ
|
||||
# ============================================================
|
||||
|
||||
class PathFindingStrategy:
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return "Unknown"
|
||||
|
|
@ -152,137 +141,89 @@ class PathFindingStrategy:
|
|||
|
||||
|
||||
# ============================================================
|
||||
# BFS
|
||||
# BFS — обход в ширину (очередь)
|
||||
# ============================================================
|
||||
|
||||
class BFSStrategy(PathFindingStrategy):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return "BFS"
|
||||
|
||||
def findPath(self, maze, start, exit):
|
||||
|
||||
queue = deque([start])
|
||||
|
||||
queue = deque([start]) # Очередь: кто первый зашёл — первый вышел
|
||||
visited = {start}
|
||||
|
||||
parents = {
|
||||
start: None
|
||||
}
|
||||
|
||||
parents = {start: None} # Откуда пришли в клетку
|
||||
visited_count = 1
|
||||
|
||||
while queue:
|
||||
|
||||
current = queue.popleft()
|
||||
|
||||
current = queue.popleft() # Берём из начала очереди
|
||||
if current == exit:
|
||||
path = reconstruct_path(parents, exit)
|
||||
return path, visited_count
|
||||
|
||||
for neighbor in maze.getNeighbors(current):
|
||||
|
||||
if neighbor not in visited:
|
||||
|
||||
visited.add(neighbor)
|
||||
|
||||
parents[neighbor] = current
|
||||
|
||||
visited_count += 1
|
||||
|
||||
queue.append(neighbor)
|
||||
|
||||
queue.append(neighbor) # Кладём в конец очереди
|
||||
return [], visited_count
|
||||
|
||||
|
||||
# ============================================================
|
||||
# DFS
|
||||
# DFS — обход в глубину (стек)
|
||||
# ============================================================
|
||||
|
||||
class DFSStrategy(PathFindingStrategy):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return "DFS"
|
||||
|
||||
def findPath(self, maze, start, exit):
|
||||
|
||||
stack = [start]
|
||||
|
||||
stack = [start] # Стек: кто последний зашёл — первый вышел
|
||||
visited = {start}
|
||||
|
||||
parents = {
|
||||
start: None
|
||||
}
|
||||
|
||||
parents = {start: None}
|
||||
visited_count = 1
|
||||
|
||||
while stack:
|
||||
|
||||
current = stack.pop()
|
||||
|
||||
current = stack.pop() # Берём с вершины стека
|
||||
if current == exit:
|
||||
path = reconstruct_path(parents, exit)
|
||||
return path, visited_count
|
||||
|
||||
for neighbor in maze.getNeighbors(current):
|
||||
|
||||
if neighbor not in visited:
|
||||
|
||||
visited.add(neighbor)
|
||||
|
||||
parents[neighbor] = current
|
||||
|
||||
visited_count += 1
|
||||
|
||||
stack.append(neighbor)
|
||||
|
||||
stack.append(neighbor) # Кладём на вершину стека
|
||||
return [], visited_count
|
||||
|
||||
|
||||
# ============================================================
|
||||
# A*
|
||||
# A* — поиск с подсказкой (эвристикой)
|
||||
# ============================================================
|
||||
|
||||
class AStarStrategy(PathFindingStrategy):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return "A*"
|
||||
|
||||
# Подсказка: примерное расстояние до выхода (по прямой)
|
||||
def heuristic(self, a, b):
|
||||
return abs(a.x - b.x) + abs(a.y - b.y)
|
||||
|
||||
def findPath(self, maze, start, exit):
|
||||
|
||||
counter = 0
|
||||
|
||||
open_set = []
|
||||
|
||||
counter = 0 # Чтобы различать клетки с одинаковым приоритетом
|
||||
open_set = [] # Куча: всегда берём самую перспективную клетку
|
||||
heapq.heappush(open_set, (0, counter, start))
|
||||
|
||||
parents = {
|
||||
start: None
|
||||
}
|
||||
|
||||
g_score = {
|
||||
start: 0
|
||||
}
|
||||
|
||||
parents = {start: None}
|
||||
g_score = {start: 0} # Пройденное расстояние от старта
|
||||
visited = set()
|
||||
|
||||
visited_count = 0
|
||||
|
||||
while open_set:
|
||||
|
||||
_, _, current = heapq.heappop(open_set)
|
||||
|
||||
_, _, current = heapq.heappop(open_set) # Достаём клетку с лучшей оценкой
|
||||
if current in visited:
|
||||
continue
|
||||
|
||||
visited.add(current)
|
||||
|
||||
visited_count += 1
|
||||
|
||||
if current == exit:
|
||||
|
|
@ -290,137 +231,86 @@ class AStarStrategy(PathFindingStrategy):
|
|||
return path, visited_count
|
||||
|
||||
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]:
|
||||
|
||||
g_score[neighbor] = tentative_g
|
||||
|
||||
parents[neighbor] = current
|
||||
|
||||
# Оценка клетки = пройденный путь + подсказка до выхода
|
||||
f_score = tentative_g + self.heuristic(neighbor, exit)
|
||||
|
||||
counter += 1
|
||||
|
||||
heapq.heappush(
|
||||
open_set,
|
||||
(f_score, counter, neighbor)
|
||||
)
|
||||
|
||||
heapq.heappush(open_set, (f_score, counter, neighbor))
|
||||
return [], visited_count
|
||||
|
||||
|
||||
# ============================================================
|
||||
# DIJKSTRA
|
||||
# ДЕЙКСТРА — поиск с учётом весов клеток
|
||||
# ============================================================
|
||||
|
||||
class DijkstraStrategy(PathFindingStrategy):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return "Dijkstra"
|
||||
|
||||
def findPath(self, maze, start, exit):
|
||||
|
||||
counter = 0
|
||||
|
||||
queue = []
|
||||
|
||||
queue = [] # Куча: всегда берём клетку с кратчайшим путём от старта
|
||||
heapq.heappush(queue, (0, counter, start))
|
||||
|
||||
distances = {
|
||||
start: 0
|
||||
}
|
||||
|
||||
parents = {
|
||||
start: None
|
||||
}
|
||||
|
||||
distances = {start: 0} # Кратчайшее известное расстояние до каждой клетки
|
||||
parents = {start: None}
|
||||
visited = set()
|
||||
|
||||
visited_count = 0
|
||||
|
||||
while queue:
|
||||
|
||||
dist, _, current = heapq.heappop(queue)
|
||||
|
||||
dist, _, current = heapq.heappop(queue) # Достаём ближайшую клетку
|
||||
if current in visited:
|
||||
continue
|
||||
|
||||
visited.add(current)
|
||||
|
||||
visited_count += 1
|
||||
|
||||
if current == exit:
|
||||
path = reconstruct_path(parents, exit)
|
||||
return path, visited_count
|
||||
|
||||
# Здесь используем вес клеток, а не просто +1
|
||||
for neighbor, weight in maze.getWeightedNeighbors(current):
|
||||
|
||||
new_dist = dist + weight
|
||||
|
||||
if neighbor not in distances or new_dist < distances[neighbor]:
|
||||
|
||||
distances[neighbor] = new_dist
|
||||
|
||||
parents[neighbor] = current
|
||||
|
||||
counter += 1
|
||||
|
||||
heapq.heappush(
|
||||
queue,
|
||||
(new_dist, counter, neighbor)
|
||||
)
|
||||
|
||||
heapq.heappush(queue, (new_dist, counter, neighbor))
|
||||
return [], visited_count
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ЭТАП 4. STATS + SOLVER
|
||||
# ЭТАП 4. РЕШАТЕЛЬ И СТАТИСТИКА
|
||||
# ============================================================
|
||||
|
||||
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.time_ms = time_ms
|
||||
self.visited_cells = visited_cells
|
||||
self.path_length = path_length
|
||||
self.path_found = path_found
|
||||
self.time_ms = time_ms # Время в миллисекундах
|
||||
self.visited_cells = visited_cells # Сколько клеток посетили
|
||||
self.path_length = path_length # Длина найденного пути
|
||||
self.path_found = path_found # Нашли путь или нет
|
||||
|
||||
|
||||
class MazeSolver:
|
||||
|
||||
def __init__(self, maze, strategy=None):
|
||||
self.maze = maze
|
||||
self.strategy = strategy
|
||||
|
||||
# Сменить алгоритм поиска
|
||||
def setStrategy(self, strategy):
|
||||
self.strategy = strategy
|
||||
|
||||
def solve(self):
|
||||
|
||||
if self.strategy is None:
|
||||
raise ValueError("Стратегия не выбрана")
|
||||
|
||||
# Засекаем время и запускаем алгоритм
|
||||
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()
|
||||
|
||||
elapsed_ms = (end_time - start_time) * 1000
|
||||
|
||||
return SearchStats(
|
||||
|
|
@ -433,171 +323,126 @@ class MazeSolver:
|
|||
|
||||
|
||||
# ============================================================
|
||||
# ВИЗУАЛИЗАЦИЯ
|
||||
# ВЫВОД ЛАБИРИНТА В КОНСОЛЬ
|
||||
# ============================================================
|
||||
|
||||
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):
|
||||
|
||||
line = ""
|
||||
|
||||
for x in range(maze.width):
|
||||
|
||||
cell = maze.getCell(x, y)
|
||||
|
||||
if cell == maze.start:
|
||||
line += "S"
|
||||
|
||||
elif cell == maze.exit:
|
||||
line += "E"
|
||||
|
||||
elif cell in path_set:
|
||||
line += "."
|
||||
|
||||
line += "." # Точка — клетка пути
|
||||
elif cell.is_wall:
|
||||
line += "#"
|
||||
|
||||
else:
|
||||
line += " "
|
||||
|
||||
print(line)
|
||||
|
||||
print()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ФАЙЛЫ И ПУТИ
|
||||
# ПУТИ ДЛЯ СОХРАНЕНИЯ ФАЙЛОВ
|
||||
# ============================================================
|
||||
|
||||
OUTPUT_DIR = os.path.join("docs", "data")
|
||||
|
||||
PREFIX = "_2lab"
|
||||
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True) # Создаём папку, если её нет
|
||||
|
||||
|
||||
def get_path(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):
|
||||
|
||||
with open(filename, 'w', encoding='utf-8') as f:
|
||||
|
||||
for line in lines:
|
||||
f.write(line + '\n')
|
||||
|
||||
return filename
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ГЕНЕРАЦИЯ
|
||||
# ГЕНЕРАЦИЯ ЛАБИРИНТОВ
|
||||
# ============================================================
|
||||
|
||||
# Случайный лабиринт с гарантированным путём
|
||||
def generate_maze(width, height, wall_density=0.3):
|
||||
|
||||
grid = [[' ' for _ in range(width)] for _ in range(height)]
|
||||
|
||||
# Ставим стены по краям
|
||||
for x in range(width):
|
||||
grid[0][x] = '#'
|
||||
grid[height - 1][x] = '#'
|
||||
|
||||
for y in range(height):
|
||||
grid[y][0] = '#'
|
||||
grid[y][width - 1] = '#'
|
||||
|
||||
# Прокладываем гарантированную дорожку от (1,1) до (width-2, height-2)
|
||||
x, y = 1, 1
|
||||
|
||||
path_cells = {(x, y)}
|
||||
|
||||
while x < width - 2 or y < height - 2:
|
||||
|
||||
if x < width - 2 and random.random() > 0.3:
|
||||
x += 1
|
||||
|
||||
elif y < height - 2:
|
||||
y += 1
|
||||
|
||||
else:
|
||||
x += 1
|
||||
|
||||
path_cells.add((x, y))
|
||||
|
||||
# Случайно расставляем стены, но не на дорожке
|
||||
for yy in range(1, height - 1):
|
||||
|
||||
for xx in range(1, width - 1):
|
||||
|
||||
if (xx, yy) not in path_cells:
|
||||
|
||||
if random.random() < wall_density:
|
||||
grid[yy][xx] = '#'
|
||||
|
||||
# Ставим старт и выход по углам
|
||||
grid[1][1] = 'S'
|
||||
grid[height - 2][width - 2] = 'E'
|
||||
|
||||
return [''.join(row) for row in grid]
|
||||
|
||||
|
||||
# Пустой лабиринт без стен
|
||||
def generate_empty_maze(size):
|
||||
|
||||
lines = [" " * size for _ in range(size)]
|
||||
|
||||
lines[0] = "S" + " " * (size - 1)
|
||||
|
||||
lines[size - 1] = " " * (size - 1) + "E"
|
||||
|
||||
return lines
|
||||
|
||||
|
||||
# Лабиринт, где выход замурован со всех сторон
|
||||
def generate_no_exit_maze(size):
|
||||
|
||||
lines = generate_maze(size, size, wall_density=0.2)
|
||||
|
||||
for y, line in enumerate(lines):
|
||||
|
||||
if 'E' in line:
|
||||
|
||||
x = line.index('E')
|
||||
|
||||
# Окружаем выход стенами
|
||||
for dy, dx in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
||||
|
||||
ny = y + dy
|
||||
nx = x + dx
|
||||
|
||||
ny, nx = y + dy, x + dx
|
||||
if 0 <= ny < size and 0 <= nx < size:
|
||||
|
||||
if lines[ny][nx] == ' ':
|
||||
|
||||
lines[ny] = (
|
||||
lines[ny][:nx]
|
||||
+ '#'
|
||||
+ lines[ny][nx + 1:]
|
||||
)
|
||||
|
||||
lines[ny] = lines[ny][:nx] + '#' + lines[ny][nx + 1:]
|
||||
return lines
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ЭКСПЕРИМЕНТЫ
|
||||
# ЗАПУСК ЭКСПЕРИМЕНТОВ
|
||||
# ============================================================
|
||||
|
||||
def run_experiments():
|
||||
|
||||
# Набор лабиринтов для тестов
|
||||
mazes = {
|
||||
|
||||
"small": [
|
||||
"##########",
|
||||
"#S #",
|
||||
|
|
@ -610,16 +455,13 @@ def run_experiments():
|
|||
"# E#",
|
||||
"##########"
|
||||
],
|
||||
|
||||
"medium": generate_maze(50, 50, 0.35),
|
||||
|
||||
"large": generate_maze(100, 100, 0.4),
|
||||
|
||||
"empty": generate_empty_maze(20),
|
||||
|
||||
"no_exit": generate_no_exit_maze(15)
|
||||
}
|
||||
|
||||
# Список алгоритмов
|
||||
strategies = [
|
||||
BFSStrategy(),
|
||||
DFSStrategy(),
|
||||
|
|
@ -634,39 +476,28 @@ def run_experiments():
|
|||
print("=" * 60)
|
||||
|
||||
for maze_name, lines in mazes.items():
|
||||
|
||||
filename = get_path(f"{maze_name}.txt")
|
||||
|
||||
create_test_maze(filename, lines)
|
||||
|
||||
maze = TextFileMazeBuilder().buildFromFile(filename)
|
||||
|
||||
print(f"\nЛабиринт: {maze_name}")
|
||||
print("-" * 60)
|
||||
|
||||
for strategy in strategies:
|
||||
|
||||
times = []
|
||||
visited_values = []
|
||||
|
||||
final_path_len = 0
|
||||
|
||||
# Запускаем 5 раз и считаем среднее время
|
||||
for _ in range(5):
|
||||
|
||||
solver = MazeSolver(maze)
|
||||
|
||||
solver.setStrategy(strategy)
|
||||
|
||||
stats, path = solver.solve()
|
||||
|
||||
times.append(stats.time_ms)
|
||||
|
||||
visited_values.append(stats.visited_cells)
|
||||
|
||||
final_path_len = stats.path_length
|
||||
|
||||
avg_time = sum(times) / len(times)
|
||||
|
||||
avg_visited = sum(visited_values) / len(visited_values)
|
||||
|
||||
results.append({
|
||||
|
|
@ -678,110 +509,61 @@ def run_experiments():
|
|||
})
|
||||
|
||||
status = "найден" if final_path_len > 0 else "не найден"
|
||||
print(f"{strategy.name:<10} | {avg_time:>8.4f} мс | {int(avg_visited):>5} клеток | путь {status}")
|
||||
|
||||
print(
|
||||
f"{strategy.name:<10} | "
|
||||
f"{avg_time:>8.4f} мс | "
|
||||
f"{int(avg_visited):>5} клеток | "
|
||||
f"путь {status}"
|
||||
)
|
||||
|
||||
# Сохраняем всё в CSV
|
||||
csv_path = get_path("results.csv")
|
||||
|
||||
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.writerows(results)
|
||||
|
||||
print(f"\nCSV сохранён: {csv_path}")
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ГРАФИК
|
||||
# ПОСТРОЕНИЕ ГРАФИКА
|
||||
# ============================================================
|
||||
|
||||
def build_charts(results):
|
||||
|
||||
mazes = list(dict.fromkeys(r["maze"] for r in results))
|
||||
|
||||
strategies = list(dict.fromkeys(r["strategy"] for r in results))
|
||||
mazes = list(dict.fromkeys(r["maze"] for r in results)) # Список лабиринтов без повторов
|
||||
strategies = list(dict.fromkeys(r["strategy"] for r in results)) # Список стратегий без повторов
|
||||
|
||||
fig, ax = plt.subplots(figsize=(12, 6))
|
||||
|
||||
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):
|
||||
|
||||
times = [
|
||||
r["time_ms"]
|
||||
for r in results
|
||||
if r["strategy"] == strategy
|
||||
]
|
||||
|
||||
ax.bar(
|
||||
[j + i * width for j in x],
|
||||
times,
|
||||
width,
|
||||
label=strategy,
|
||||
color=colors.get(strategy, 'gray')
|
||||
)
|
||||
# Берём время этой стратегии для всех лабиринтов
|
||||
times = [r["time_ms"] for r in results 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_ylabel("Время (мс)")
|
||||
|
||||
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.legend()
|
||||
|
||||
ax.grid(axis='y', alpha=0.3)
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
chart_path = get_path("chart_time.png")
|
||||
|
||||
plt.savefig(chart_path, dpi=150, bbox_inches='tight')
|
||||
|
||||
print(f"График сохранён: {chart_path}")
|
||||
|
||||
plt.show()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# MAIN
|
||||
# ГЛАВНАЯ ФУНКЦИЯ
|
||||
# ============================================================
|
||||
|
||||
def main():
|
||||
|
||||
results = run_experiments()
|
||||
|
||||
build_charts(results)
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user