这个还是笔者好久之前写的matlab代码,写的不是很好,还请大家多多在指正
clear;clc
South(1,:) = [1,1,1,1]; %南岸
North(1,:) = [0,0,0,0]; %北岸
A = ['人','狗','鸡','米'];
Safe_condition = [1,1,1,1;1,0,1,1;1,1,0,1;1,1,1,0;1,0,1,0;0,0,0,0;0,1,0,0;0,0,1,0;0,0,0,1;0,1,0,1]; %可行的状态
k = 0; %记录渡河次数
fprintf('渡河方式: \n');
while (~isequal(North(k+1,:),[1,1,1,1]))&&k<=100
k = k+1;
for i = 1:4
flag1 = 0;flag2 = 0;flag3 = 1; %防止死循环,以及出现不可行的状态
if South(k,i) ==1
Cross_river1 = [1,0,0,0];
Cross_river1(i) = 1;
South(k+1,:) = xor(South(k,:),Cross_river1);
North(k+1,:) = [1,1,1,1] - South(k+1,:);
for j = 1:10
if isequal(North(k+1,:),Safe_condition(j,:))
flag1 = 1;
end
end
for j = 1:10
if isequal(South(k+1,:),Safe_condition(j,:))
flag2 = 1;
end
end
for j = 1:k
if isequal(South(k+1,:),South(j,:))
flag3 = 0; %防止出现状态死循环
end
end
if (flag1 ==1)&&(flag2 ==1)&&(flag3 ==1)
if i ==1
fprintf('%s 从南岸到北岸\n',A(1));
break
else
fprintf('%s 和 %s 从南岸到北岸\n',A(1),A(i));
break
end
else
continue
end
end
end
if isequal(North(k+1,:),[1,1,1,1])
break
else
k = k+1;
for m = 1:4
flag1 = 0;flag2 = 0;flag3 = 1;
if North(k,m) ==1
Cross_river2 = [1,0,0,0];
Cross_river2(m) = 1;
North(k+1,:) = xor(North(k,:),Cross_river2);
South(k+1,:) = [1,1,1,1] - North(k+1,:);
for j = 1:10
if isequal(North(k+1,:),Safe_condition(j,:))
flag1 = 1;
end
end
for j = 1:10
if isequal(South(k+1,:),Safe_condition(j,:))
flag2 = 1;
end
end
for j = 1:k
if isequal(South(k+1,:),South(j,:))
flag3 = 0; %防止出现状态死循环
end
end
if (flag1 ==1)&&(flag2 ==1)&&(flag3 ==1)
if m ==1
fprintf('%s 从北岸到南岸\n',A(1));
break
else
fprintf('%s 和 %s 从北岸到南岸\n',A(1),A(m));
break
end
else
continue
end
end
end
end
end