本文使用MATLAB实现了商人过河为题,以下为部分代码:
boat_p函数:
function boat=boat_p(pm,tybe)
boat=[];
switch tybe
case 1
for i=pm:-1:2
for j=0:i-1
boat_pass=[j,i-j-1];
boat=[boat;boat_pass];
end
end
case 2
for i=2:pm
for j=0:i-1
boat_pass=[j,i-j-1];
boat=[boat;boat_pass];
end
end
end
end
history函数:
function qa_h=history(qa,tybe)
n=length(qa);
switch tybe
case 0
qa_h=[];
i=3;
while i<=n
qa_h=[qa_h;qa(i,:)];
i=i+2;
end
case 1
qa_h=[];
i=2;
while i<=n
qa_h=[qa_h;qa(i,:)];
i=i+2;
end
end
member函数:
function y=member(a,b)
h=size(a);
count=0;
for i=1:h(1)
if isequal(b,a(i,:))
count=count+1;
end
end
if count==0
y=0;
else
y=1;
end
end
safe_situation函数:
function safe=safe_situation(pm)
safe=[];
for i=0:pm
safe_pass=[0,i;pm,i;i,i];
safe=[safe;safe_pass];
end
end
pass_river函数:
clear;
pm=4; %商人和仆人对数,假设一个商人带一个仆人
%由于绘图限制,请不要超过11
qa=[pm,pm];
n=1;
safe=safe_situation(pm);
boat1=boat_p(pm,1);
boat2=boat_p(pm,2);
n1=length(boat1);n2=length(boat2);
draw(pm,qa,n);pause(3);
qa_pass=qa(n,:);
qa_pass=qa_pass-boat1(1,:);
qa(n+1,:)=qa_pass;
n=n+1;
qa_h=history(qa,mod(n,2));
draw(pm,qa,n);pause(3);
while sum(qa(n,:))~=0
if mod(n,2)==1
for i=1:n1
qa_pass=qa(n,:);
qa_pass=qa_pass-boat1(i,:);
if member(safe,qa_pass)==1&&member(qa_h,qa_pass)==0
qa(n+1,:)=qa_pass;
break;
end
end
end
if mod(n,2)==0
for i=1:n2
qa_pass=qa(n,:);
qa_pass=qa_pass+boat2(i,:);
if member(safe,qa_pass)==1&&member(qa_h,qa_pass)==0
qa(n+1,:)=qa_pass;
break;
end
end
end
n=n+1;
qa_h=history(qa,mod(n,2));
draw(pm,qa,n);
pause(3);
end
代码运行效果演示:
标签:end,商人,safe,qa,MATLAB,pass,过河,boat,pm From: https://blog.csdn.net/Li8384/article/details/144885968