Java solution to the bridge problem

Source: Internet
Author: User

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;
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.