79 lines
2.2 KiB
Mathematica
Raw Permalink Normal View History

2025-05-27 21:44:25 +08:00
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