Problem: In the dark of the night, four travelers came to a narrow bridge with no guardrail. Without the help of a flashlight, we would not have dared to cross the bridge anyway. Unfortunately, four people took only one flashlight, and the bridge was narrow enough for two people to cross. If they cross the bridge alone, the four people will need 1, 2, 5, 10 minutes respectively, and if the two people cross the bridge at the same time, it takes the slower the person to take the time to act alone. The question is how to design a plan to get the four people across the bridge as quickly as possible.
The Java implementation features are as follows: (JDK1.3,JBUILD7 test passed)
public class MKS {
Public mks () {
int[] i={1,2,5,10};
boolean[] j={true,true,true,true};
int go=1 ;
int time=0;
for (; true;)
{
if (j[0]| | j[1]| | j[2]| | J[3])
{
if (go==1)
{
go=0;
if (j[0]==true&&j[1]==true)
{
System.out.print (i[0]+ "crossing the Bridge \" r\n ");
System.out.print (i[1]+ "bridge \ r \ n");
Time+=i[1];
System.out.print ("time=" +time+ "\ r \ n");
J[0]=false;
J[1]=false;
}
Else
{
System.out.print (i[2]+ "bridge \ r \ n");
System.out.print (i[3]+ "bridge \ r \ n");
Time+=i[3];
System.out.print ("time=" +time+ "\ r \ n");
J[2]=false;
J[3]=false;
}
{
Else
{
go=1;
if (j[0]==false)
{
J[0]=true;
System.out.print (i[0]+ "back \ \ r \ n");
Time+=i[0];
System.out.print ("time=" +time+ "\ r \ n");
}
Else
{
J[1]=true;
System.out.print (i[1]+ "back \ \ r \ n");
Time+=i[1];
System.out.print ("time=" +time+ "\ r \ n");
}
}
}
Else
{
break;
}
}
}
}