function [solutionpath,visiting_path]=bredth_first_sg(instate, goalstate)
% From S to G
% we use five number to represent the five destinations:
% S A B C G [1 1] [2 2] [3 3] [4 4] [5 5]
% instate=[1 1];
% goalstate=[5 5];
% This function is to solve the city block problem by bredth-first search
% The usage of this code is:
% [solutionpath,visiting_path]=bredth_first_sg([1 1], [5 5])
%show the initial state and goal state
state{1}='S';
state{2}='A';
state{3}='B';
state{4}='C';
state{5}='G';
display(['The initial state is ' state{instate(1)}])
display(['The goal state is ' state{goalstate(1)}])
open=instate; % initialize the open set
closed=[]; % initialize the closed set
iternnum=0; % record the interation number
%% get closed and open set
while ~isempty(open)
iternnum=iternnum+1;
X=open(1,:); %got the leftmost state from open
open(1,:)=[]; %remove leftmost state from open
eva=sum(abs(X-goalstate)); %if x is goal then return success
if eva==0
display('Find the goalstate successfully')
break;
end
children=getchilidrenSG(X); % get the clidren of X
k = ismember(children,[open;closed],'rows'); % remove the repeated state
children(k,:)=[];
closed=[X;closed]; % put the leftmoset to the closed
open=[open;children]; % put the children on right end of open
end
%% get the visiting path and solution path
if isempty(open) && eva~=0
display('Fail to find the goalstate successfully')
else
%show the visiting path
visitingpath=[];
for i=1:size(closed,1)
visitingpath=[state(closed(i,1)) visitingpath];
end
visiting_path=[visitingpath state(goalstate(1))];
display('The visiting path is ')
display(visiting_path)
visitingpath=[goalstate;closed];
%prune the visiting path to get solution path
k=1;
while k<size(visitingpath,1)
% find the father mode of the visiting path
father_mode=getchilidrenSG(visitingpath(k,:));
same_mode=ismember(visitingpath(k+1:end,:),father_mode,'rows');
% find the father node(s) of the visiting node, delete
% the nodes between the current node and fathest father. (e.g., G-C-B-A-S,
% G is the child of B and C, then delete C and keep B
index= find(same_mode==1)+k;
visitingpath=visitingpath([1:k,index(end):end],:);
k=k+1;
end
solutionpath=state(flipud(visitingpath(:,1)));
display('The solution path is ')
display(solutionpath)
end
bredth_first_sg.zip_Breadth-First_city_sg
版权申诉
9 浏览量
2022-07-14
14:47:24
上传
评论
收藏 1KB ZIP 举报
Kinonoyomeo
- 粉丝: 76
- 资源: 1万+
最新资源
- chromedriver-linux64.zip 是一个用于在 Linux 系统上运行 Chrome 浏览器的驱动程序
- 基于Python和PyTorch框架完成的一个手写数字识别实验源码(带MINIST手写数字数据集)+详细注释(高分项目)
- 基于Matlab在MNIST数据集上利用CNN完成手写体数字识别任务,并实现单层CNN反向传播算法+源代码+文档说明(高分项目)
- NVIDIA驱动、CUDA和Pytorch及其依赖
- html动态爱心代码一(附源码)
- c40539bc-071a-486c-9d52-9d0c18d62dac 4.html
- 基于物理的非视域成像(NLOS)算法,利用了nerf+python源码+文档说明
- yuluer知更鸟.7z(1).001
- python课程设计-基于tensorflow实现的图文生成程序,数据集flickr30k-images+源代码+文档说明+截图
- python作业-基于Flickr30k数据集实现图像文本跨模态搜索python源码+数据集+测试界面+项目说明(高分课程设计)
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈