添加Dijkstra算法

This commit is contained in:
张梦南 2025-05-27 21:44:25 +08:00
parent 44d13cd7ba
commit 16609a6699
5 changed files with 93 additions and 10 deletions

78
Dijkstra/Dijkstras.m Normal file
View File

@ -0,0 +1,78 @@
function path = Dijkstras(map, start, goal)
[rows, cols] = size(map);
dist = inf(rows, cols); %
visited = false(rows, cols); % 访
prev = cell(rows, cols); %
dist(start(1), start(2)) = 0; % 0
openList = start; %
% []
directions = [0 1; 1 0; 0 -1; -1 0];
while ~isempty(openList)
% openList
minDist = inf;
minIdx = 1;
for i = 1:size(openList, 1)
r = openList(i,1); c = openList(i,2);
if dist(r, c) < minDist
minDist = dist(r, c);
minIdx = i;
end
end
current = openList(minIdx, :);
openList(minIdx, :) = []; %
r = current(1); c = current(2);
if visited(r, c), continue; end
visited(r, c) = true;
%
if isequal(current, goal)
break;
end
%
for d = 1:size(directions, 1)
nr = r + directions(d, 1);
nc = c + directions(d, 2);
%
if nr >= 1 && nr <= rows && nc >= 1 && nc <= cols
if map(nr, nc) == 0 && ~visited(nr, nc)
alt = dist(r, c) + 1; % 1
if alt < dist(nr, nc)
dist(nr, nc) = alt;
prev{nr, nc} = [r, c];
openList = [openList; nr, nc]; %
end
end
end
end
end
%
path = [];
cur = goal;
while ~isempty(prev{cur(1), cur(2)})
path = [cur; path];
cur = prev{cur(1), cur(2)};
end
if isequal(cur, start)
path = [start; path];
else
path = [];
end
%
if ~isempty(path)
disp('');
for i = 1:size(path, 1)
fprintf('(%d, %d)\n', path(i, 2), path(i, 1));
end
else
disp('');
end
end

View File

@ -1,3 +1,4 @@
% AstarDijkstra
%
% 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
map = [0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; % 1
@ -26,11 +27,13 @@ start = [2, 2];
goal = [19, 19];
% A*
path = Astar(map, start, goal);
path_Astar = Astar(map, start, goal);
% Dijkstra
path_Dijkstra = Dijkstras(map, start, goal);
visualize_path(map, start, goal, path);
visualize_path(map, start, goal, path_Astar, path_Dijkstra);
function visualize_path(map, start, goal, path)
function visualize_path(map, start, goal, path_Astar, path_Dijkstra)
% 01
imagesc(map);
colormap(flipud(gray)); % 0 1
@ -43,19 +46,21 @@ function visualize_path(map, start, goal, path)
%
plot(goal(2), goal(1), 'ro', 'MarkerSize', 10, 'LineWidth', 2);
if ~isempty(path)
if ~isempty(path_Astar)
%
if ~isequal(path(1,:), start)
path = [start; path];
if ~isequal(path_Astar(1,:), start)
path_Astar = [start; path_Astar];
end
%
if ~isequal(path(end,:), goal)
path = [path; goal];
if ~isequal(path_Astar(end,:), goal)
path_Astar = [path_Astar; goal];
end
% 线
plot(path(:,2), path(:,1), 'g-', 'LineWidth', 2); % 绿线
plot(path(:,2), path(:,1), 'go', 'MarkerSize', 4, 'MarkerFaceColor', 'g'); %
plot(path_Astar(:,2), path_Astar(:,1), 'r-', 'LineWidth', 2); % 绿线
plot(path_Astar(:,2), path_Astar(:,1), 'ro', 'MarkerSize', 4, 'MarkerFaceColor', 'r'); %
plot(path_Dijkstra(:,2), path_Dijkstra(:,1), 'g-', 'LineWidth', 2); % 绿线
plot(path_Dijkstra(:,2), path_Dijkstra(:,1), 'go', 'MarkerSize', 4, 'MarkerFaceColor', 'g'); %
end
% 线