Реализация алгоритма Дейкстры

This commit is contained in:
GordStep 2026-05-22 21:57:45 +03:00
parent d8fb7ab226
commit 1224a5afee
6 changed files with 208 additions and 41 deletions

View File

@ -0,0 +1,11 @@
#####################################
#S #
# #
# #
# #
# #
# #
# #
# #
# E#
#####################################

View File

@ -0,0 +1,20 @@
####################
S # # # #
### # ### # ### # ##
# # # # # # # # ##
# ### # ### # ### ##
# # # # # ##
# ### ### ### # # ##
# # # # # # # # ##
# # # # ### # # # ##
# # # # # # # # ##
# # # ### # # # # ##
# # # # # # # ##
# # ### # ### # # ##
# # # # # # ##
# ### # ### # ### ##
# # # # # # # # ##
# # # # # # # # # ##
# # # # # # # # # ##
# # # # E#
####################

View File

@ -58,7 +58,7 @@ class ConsoleView(Observer):
elif c.toStr() in ["S", "E"]:
print(c.toStr(), end='')
elif c.getXY() in path_xy:
print('*', end='')
print('.', end='')
else:
print(c.toStr(), end='')

View File

@ -1,10 +1,56 @@
from source.strategy import PathFindingStrategy
from heapq import *
from source.strategy import PathFindingStrategy, reconstruct_path
from source.classes import Maze, Cell
class Dijkstra(PathFindingStrategy):
def findPath(self, maze: Maze, start: Cell, exit: Cell):
pass
@property
def name(self) -> str:
"""Возвращает название метода"""
return "Dijkstra"
def findPath(self, maze: Maze):
start_cell = maze.start
exit_cell = maze.exit
queue = []
counter = 0 # счётчик для уникальности, чтобы не сравнивать клетки
heappush(queue, (0, counter, start_cell))
counter += 1
cost_visited = {start_cell.getXY(): 0}
came_from = {start_cell.getXY(): None}
visited_count = 1
while queue:
current_cost, _, current_cell = heappop(queue)
if current_cell.getXY() == exit_cell.getXY():
return reconstruct_path(
came_from=came_from,
start=start_cell,
end=current_cell
), visited_count
next_cells = maze.getNeighbors(current_cell)
for next_cell in next_cells:
neighbor_cost = next_cell.value
neighbor_cell_xy = next_cell.getXY()
new_cost = current_cost + neighbor_cost
if neighbor_cell_xy not in cost_visited or new_cost < cost_visited[neighbor_cell_xy]:
heappush(queue, (new_cost, counter, next_cell))
counter += 1
cost_visited[neighbor_cell_xy] = new_cost
came_from[neighbor_cell_xy] = current_cell
visited_count += 1
return [], visited_count
def __dijkstra__(self, maze: Maze, start: Cell, exit: Cell):
pass

View File

@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 12,
"id": "4dbe48b6",
"metadata": {},
"outputs": [],
@ -17,7 +17,19 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 13,
"id": "007bf97a",
"metadata": {},
"outputs": [],
"source": [
"test_lab = './mazes/tests/test_lab.txt'\n",
"test_lab2 = './mazes/tests/test_lab2.txt'\n",
"test_lab3 = './mazes/tests/test_lab20x20.txt'"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "4489fc7e",
"metadata": {},
"outputs": [
@ -35,7 +47,7 @@
}
],
"source": [
"with open('test_lab.txt') as f:\n",
"with open(test_lab) as f:\n",
" data = f.readlines()\n",
" for el in data:\n",
" print(el.rstrip())"
@ -43,7 +55,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 15,
"id": "fde1eddb",
"metadata": {},
"outputs": [
@ -64,14 +76,14 @@
"\n",
"\n",
"builder = TextFileMazeBuilder()\n",
"maze = builder.buildFromFile(filename='test_lab.txt')\n",
"maze = builder.buildFromFile(filename=test_lab)\n",
"\n",
"maze.printer()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 16,
"id": "22325f68",
"metadata": {},
"outputs": [
@ -80,7 +92,7 @@
"output_type": "stream",
"text": [
"Загружен лабиринт:\n",
"S*P# ###\n",
"S.P# ###\n",
"## # # E\n",
"# # #\n",
"### ## #\n",
@ -104,7 +116,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 17,
"id": "19840429",
"metadata": {},
"outputs": [
@ -113,11 +125,11 @@
"output_type": "stream",
"text": [
"Путь найден:\n",
"S**# ###\n",
"##*# #*E\n",
"# ** #*#\n",
"###*##*#\n",
"# ****#\n",
"S..# ###\n",
"##.# #.E\n",
"# .. #.#\n",
"###.##.#\n",
"# ....#\n",
"########\n"
]
},
@ -142,15 +154,12 @@
" (7, 1)])"
]
},
"execution_count": 5,
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\n",
"\n",
"\n",
"solver = MazeSolver(maze, DFS(), ConsoleView())\n",
"stats = solver.solve()\n",
"\n",
@ -159,7 +168,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 18,
"id": "73ba37a8",
"metadata": {},
"outputs": [
@ -168,11 +177,11 @@
"output_type": "stream",
"text": [
"Путь найден:\n",
"S**# ###\n",
"##*# #*E\n",
"# ** #*#\n",
"###*##*#\n",
"# ****#\n",
"S..# ###\n",
"##.# #.E\n",
"# .. #.#\n",
"###.##.#\n",
"# ....#\n",
"########\n"
]
},
@ -197,15 +206,12 @@
" (7, 1)])"
]
},
"execution_count": 6,
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\n",
"\n",
"\n",
"solver = MazeSolver(maze, BFS(), ConsoleView())\n",
"stats = solver.solve()\n",
"\n",
@ -214,7 +220,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 19,
"id": "857c5c04",
"metadata": {},
"outputs": [
@ -223,10 +229,12 @@
"output_type": "stream",
"text": [
"0\n",
"2\n",
"1\n",
"4\n",
"2\n",
"3\n",
"4\n"
"3\n",
"2\n"
]
},
{
@ -235,7 +243,7 @@
"{'0', '1', '2', '3', '4'}"
]
},
"execution_count": 7,
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
@ -264,7 +272,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 20,
"id": "9a5ea5cb",
"metadata": {},
"outputs": [
@ -350,7 +358,7 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 21,
"id": "32edf4d1",
"metadata": {},
"outputs": [
@ -364,7 +372,7 @@
}
],
"source": [
"with open('test_lab.txt') as f:\n",
"with open(test_lab) as f:\n",
" data = f.read().splitlines()\n",
" x, y = 0, 0\n",
" width = len(data[0])\n",
@ -375,9 +383,91 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 22,
"id": "48d20564",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Путь найден:\n",
"# # # # # # # # # # # # # # # # # # # #\n",
"S. # # # #\n",
"#.# # # # # # # # # # # # #\n",
"#..... # # # # # # # # #\n",
"# #.# # # # # # # # # # # #\n",
"# #............. # # # # #\n",
"# # # # # # #. # # # # # # #\n",
"# # # # #..... # # # # #\n",
"# # # # # # #. # # # # #\n",
"# # # # #. # # # # #\n",
"# # # # # # #. # # # # #\n",
"# # # # #..... # # # #\n",
"# # # # # # # # #. # # # #\n",
"# # # # #. # # #\n",
"# # # # # # # # #. # # # # #\n",
"# # # # # # #. # # # #\n",
"# # # # # # #. # # # #\n",
"# # # # # # #. # # # #\n",
"# # # #...........E #\n",
"# # # # # # # # # # # # # # # # # # # #\n"
]
}
],
"source": [
"maze2 = builder.buildFromFile(test_lab3)\n",
"\n",
"solver = MazeSolver(maze2, BFS(), ConsoleView())\n",
"stats = solver.solve()"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "bf13d5ba",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Путь найден:\n",
"# # # # # # # # # # # # # # # # # # # #\n",
"S.......# # # #\n",
"# # # .# # # # # # # # # # #\n",
"#.......# # # # # # # # #\n",
"#. # # # # # # # # # # # # #\n",
"#...# ...........# # # # #\n",
"# .# # #. # # # .# # # # # # #\n",
"#...# #...# # .....# # # # #\n",
"#. # # .# # # # .# # # # #\n",
"#...# #...# #...# # # # #\n",
"# .# #. # # # #. # # # # #\n",
"#...# #..... # #.......# # # #\n",
"#. # # # #...# # # # .# # # #\n",
"#...#.......# .# #...# # #\n",
"# .#.# # .#...# # # #. # # # # #\n",
"#...#. #...#. # # #...# # # #\n",
"#. #...#. #...# # # .# # # #\n",
"#...# .#...# .# # # .# # # #\n",
"# .....# .....# # .........E #\n",
"# # # # # # # # # # # # # # # # # # # #\n"
]
}
],
"source": [
"maze2 = builder.buildFromFile(test_lab3)\n",
"\n",
"solver = MazeSolver(maze2, DFS(), ConsoleView())\n",
"stats = solver.solve()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9383cb75",
"metadata": {},
"outputs": [],
"source": []
}