过河问题matlab建模,matlab三对夫妻过河问题

function easy

%***********************初始化参数,堆栈**************************

table=[-1 -1 -1;-2 0 -1;0 -2 -1;0 -1 -1;-1 0 -1;-1 -1 -1;-2 0 -1;0 -2 -1;0 -1 -1;-1 0 -1];

op=[1 1 1 1 1 -1 -1 -1 -1 -1];

boat=[6:10;1:5];

vis=zeros(1,64);

path=zeros(1,64);

STACK_DEPTH=10000;

MAX_STEP=100;

init=[3,3,1];

space=zeros(STACK_DEPTH,3);

cnt=1;

push(init);

%***********************搜索节点,找到终点**************************

for step=1:MAX_STEP

father=pop();

if all(father(1:2)==0)

disp('找打解!!!')

break;

else visited(father)

end

sub=boat(father(3)+1,:);

for i=sub

son=father+op(i)*table(i,:);

if  islegal(son)&&~havevisited(son)

push(son);

insertpath(son,father);

end

end

end

%***********************处理结果,找出路径**************************

p=path(1);

state(1:3)=expand(1);

for i=1:64

[a,b,c]=expand(p);

if all([a b c]==[3 3 1])

state=[state;[a b c]];

break;

else

state=[state;[a b c]];

p=path(p);

end

end

state=flipud(state);

change=[0 0 0;diff(state)];

gostr={'->','

for i=1:size(state,1)

go=gostr{mod(i,2)+1};

businessman=abs(change(i,1));

serv=abs(change(i,2));

disp(['第',num2str(i-1,'%-.2d'),'步:',num2str(businessman),'商人',num2str(serv),'仆人',go,' :左边(',num2str(state(i,1)),',',num2str(state(i,2)),')右边(',num2str(3-state(i,1)),',',num2str(3-state(i,2)),')'])

end

%***********************堆栈进栈、出栈操作**************************

function push(element)

space(cnt,:)=element;

cnt=cnt+1;

if cnt>STACK_DEPTH

error('栈溢出')

end

end

function element=pop()

if cnt<2

error('栈为空')

end

cnt=cnt-1;

element=space(cnt,:);

end

%***********************访问状态表**************************

function visited(node)

index=node(1)*16+node(2)*4+node(3)+1;

vis(index)=1;

end

function bool=havevisited(node)

index=node(1)*16+node(2)*4+node(3)+1;

bool=(vis(index)==1);

end

%**********************添加关系路径**************************

function insertpath(son,father)

index_father=father(1)*16+father(2)*4+father(3)+1;

index_son=son(1)*16+son(2)*4+son(3)+1;

path(index_son)=index_father;

end

end

%**********************判断节点是否合法**************************

function bool=islegal(states)

l=states(1:2);

r=[3,3]-states(1:2);

% if  (l(2)>l(1)&&l(1)>0)||(r(2)>r(1)&&r(1)>0)||any(l<0)||any(r<0)

if  all(diff([0,l])>0)||all(diff([0,r])>0)||any(l<0)||any(r<0)

bool=false;

else

bool=true;

end

end

%**********************展开得到状态**************************

function [a,b,c]=expand(p)

a=fix(p/16);

c=mod(p,4)-1;

b=(p-16*a-c-1)/4;

end


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部