matlab求解走迷宫格最短路径,迷宫用0和1的矩阵表示,1代表墙,0代表可以走的道路,自定义起点终点,然后可视化输出,输出最短路径和距离。
时间: 2023-12-03 10:03:45 浏览: 111
好的,以下是一个使用MATLAB实现的求解走迷宫格最短路径的示例代码:
```matlab
% 自定义迷宫
maze = [0 0 0 1 0 1 0;
1 1 0 1 0 1 0;
0 0 0 0 0 0 0;
0 1 1 1 1 1 0;
0 1 0 0 0 0 0;
0 0 0 1 1 0 0;
1 1 0 0 0 0 0];
% 起点和终点
start_pos = [1, 1];
end_pos = [7, 7];
% 迷宫可视化
figure;
imagesc(maze);
colormap(gray);
hold on;
% 标记起点和终点
plot(start_pos(2), start_pos(1), 'go', 'MarkerSize', 10, 'LineWidth', 2);
plot(end_pos(2), end_pos(1), 'ro', 'MarkerSize', 10, 'LineWidth', 2);
% 使用bfs算法求解最短路径
queue = start_pos;
visited = zeros(size(maze));
visited(start_pos(1), start_pos(2)) = 1;
predecessor = zeros(size(maze));
while ~isempty(queue)
curr_pos = queue(1, :);
queue(1, :) = [];
neighbors = getNeighbors(curr_pos, maze);
for i=1:size(neighbors, 1)
neighbor_pos = neighbors(i, :);
if visited(neighbor_pos(1), neighbor_pos(2)) == 0
visited(neighbor_pos(1), neighbor_pos(2)) = 1;
queue = [queue; neighbor_pos];
predecessor(neighbor_pos(1), neighbor_pos(2)) = sub2ind(size(maze), curr_pos(1), curr_pos(2));
end
if neighbor_pos(1) == end_pos(1) && neighbor_pos(2) == end_pos(2)
break;
end
end
end
% 标记最短路径
shortest_path = [end_pos(1), end_pos(2)];
curr_pos = end_pos;
while ~(curr_pos(1) == start_pos(1) && curr_pos(2) == start_pos(2))
prev_pos = predecessor(curr_pos(1), curr_pos(2));
[prev_row, prev_col] = ind2sub(size(maze), prev_pos);
shortest_path = [prev_row, prev_col; shortest_path];
curr_pos = [prev_row, prev_col];
end
plot(shortest_path(:, 2), shortest_path(:, 1), 'm', 'LineWidth', 2);
% 输出最短路径和距离
distance = size(shortest_path, 1) - 1;
fprintf('最短路径为:%s\n', mat2str(shortest_path));
fprintf('最短路径长度为:%d\n', distance);
% 获取邻居节点
function neighbors = getNeighbors(pos, maze)
[m, n] = size(maze);
row = pos(1);
col = pos(2);
neighbors = [];
if row > 1 && maze(row-1, col) == 0
neighbors = [neighbors; row-1, col];
end
if row < m && maze(row+1, col) == 0
neighbors = [neighbors; row+1, col];
end
if col > 1 && maze(row, col-1) == 0
neighbors = [neighbors; row, col-1];
end
if col < n && maze(row, col+1) == 0
neighbors = [neighbors; row, col+1];
end
end
```
运行上述代码后,会在MATLAB中输出最短路径和距离,并可视化地展示迷宫、起点、终点和最短路径。
阅读全文