基于A星和dijkstra算法的障碍物规避matlab仿真,可以设置行列数,随机产生障碍物
1.算法概述
Dijkstra(迪杰斯特拉)算法是典型的最短路径路由算法,用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止(BFS、prime算法都有类似思想)。Dijkstra算法能得出最短路径的最优解,但由于它遍历计算的节点很多,所以效率低。
算法描述
(1)S为已经找到的从v出发的最短路径的终点集合,它的初始状态为空集,将源点加入S中。 其余顶点构成集合U。
(2)构建源点到其余顶点的距离列表,与源点不相连的顶点距离记为∞。
(3)广度遍历与源点相连的顶点,找到距离最近的顶点,则到这个顶点的最短路径就确定了,最短距离就是当前距离,将这个顶点从U中拿出,放入S中。
(4)用当前的顶点作为中间点,对其进行广度遍历,对遍历到的顶点距离进行更新。
(5)在U中搜索最短距离的顶点,将其放入S。
(6)以这个节点作为中间点广度搜索,更新距离。
(7)重复这个过程,直至U为空。
2.仿真效果预览
matlab2022a仿真结果如下:
3.MATLAB程序
cmap = [1 1 1; ...% 1 -白色-无障碍 0 0 0; ...% 2 -黑色-有障碍 0 0.8 0; ...% 3 -绿色-已搜索 0 0.4 0; ...% 4 -粉色-正在搜索 0 1 1; ...% 5 -浅蓝色-起始点 1 1 0; ...% 6 -黄色-目标点 0 0 1]; % 7 -蓝色-最终路径 colormap(cmap); %生成随机地图 map = zeros(n_r,n_c); randmap = rand(n_r,n_c); for i = 2:(sub2ind(size(randmap),n_r,n_c)-1) if (randmap(i) >= 0.75) map(i) = 2; end end map(1, 1) = 5; % start_coords 起点坐标 map(n_r, n_c) = 6; % dest_coords 终点坐标 image(1.5,1.5,map); grid on; axis image; set(handles.text5,'string','随机地图生成完毕'); % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) % hObject handle to pushbutton2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %搜索最佳路径 global n_r; global n_c; global cmap; global map; global state; nrows = n_r; ncols = n_c; start_node = sub2ind(size(map), 1, 1); %sub2ind()函数将矩阵中的某个元素的线性序号计算出来 %线性索引号例子:2*2矩阵[1 3;中,1是第一个,5是第二个 % 5 7] ,3是第三个,7是第四个 %(matlab是列优先,不是我们通常习惯的行优先) dest_node = sub2ind(size(map), n_r, n_c); % Initialize distance array 初始化距离数组 distanceFromStart = Inf(nrows,ncols); distanceFromStart(start_node) = 0 ; % For each grid cell this array holds the index of its parent 对于每个网格单元,该数组都保存其父单元的索引 parent = zeros(nrows,ncols); % Main Loop while true % Draw current map map(start_node) = 5; map(dest_node) = 6; image(1.5, 1.5, map); grid on; %网格 axis image; %显示坐标 drawnow; %刷新屏幕 % Find the node with the minimum distance 找到距离最短的节点 [min_dist, current] = min(distanceFromStart(:)); if ((current == dest_node) || isinf(min_dist)) %TF = isinf(A) 返回一个和A尺寸一样的数组, 如果A中某个元素是inf (无穷), 则对应TF中元素是1, 否则TF中对应元素是0。 break; end; %搜索中心的索引坐标:current, %搜索中心与起始点的路程:min_dist % 这两个值后面会用。 map(current) = 3; distanceFromStart(current) = Inf; [i, j] = ind2sub(size(distanceFromStart), current); %索引号变为坐标 neighbor = [i-1,j; i+1,j; i,j+1; i,j-1]; outRangetest = (neighbor(:,1)<1) + (neighbor(:,1)>nrows)+(neighbor(:,2)<1) + (neighbor(:,2)>ncols); locate = find(outRangetest>0); %返回outRangetest中大于0的元素的相对应的线性索引值。 neighbor(locate,:)=[]; neighborIndex = sub2ind(size(map),neighbor(:,1),neighbor(:,2)); for i=1:length(neighborIndex) if (map(neighborIndex(i))~=2) && (map(neighborIndex(i))~=3 && map(neighborIndex(i))~= 5) map(neighborIndex(i)) = 4; if (distanceFromStart(neighborIndex(i))>= min_dist + 1 ) distanceFromStart(neighborIndex(i)) = min_dist+1; parent(neighborIndex(i)) = current; % pause(0.02); end end end end A_001