Package bridge problem;
Import Java.util.Vector;
public class Bridgepass {
Private Vector v_source = null;
Private Vector v_destination = null;
private static int time_total = 0;
Public Bridgepass ()
{
V_source = new Vector ();
V_destination = new Vector ();
}
public void SetSource (int[] array, int num) {
for (int i=0; i<num; i++) {
V_source.addelement (Array[i]);
}
}
Public Vector GetSource () {
return v_source;
}
Public Vector getdestination () {
return v_destination;
}
/**
* The recursive algorithm.
* @param src:the set of persons in A-side
* @param des:the set of persons in B-side
* @param size:the number of persons in A-side
* @param totaltime:the TotalTime has used
*/
public void Passmethod (vector src, vector des, int size, int totaltime)
{
If only 2 persons in A-side, just pass bridge together in one time.
if (size = = 2) {
System.out.println ("A->b:" +src.elementat (0) + "and" + src.elementat (1));
System.out.println ("*****total Time:" + (TotalTime + math.max ((integer) src.elementat (0), (integer) Src.elementat (1))) +"****");
} else if (size >= 3) {
If more than 2 persons in A-side, use the recursive algorithm.
for (int i=0; i<size; i++) {
for (int j=i+1; j<size; J + +) {
Pass, A->b.
Vector _src = null;
Vector _des = null;
_SRC = (Vector) src.clone ();
_des = (Vector) des.clone ();
int time1 = 0;
int time2 = 0;
time1 = (Integer) _src.elementat (i);
_des.addelement (TIME1);
Time2 = (Integer) _src.elementat (j);
_des.addelement (time2);
System.out.print ("a->b:" + time1);
System.out.println ("and" + time2);
_src.removeelement (TIME1);
_src.removeelement (time2);
Back, B->a.
int minValue = (Integer) _des.elementat (0);
for (int k=0; k<_des.size (); k++) {
if ((Integer) _des.elementat (k)). Intvalue () < MinValue) {
MinValue = (Integer) _des.elementat (k);
}
}
_src.addelement (MinValue);
_des.removeelement (MinValue);
System.out.println ("B->a:" +minvalue);
Passmethod (_SRC, _des, _src.size (), TotalTime + Math.max (time1, time2) + MinValue);
}
}
}
}
public static void Main (string[] cmd)
{
Bridgepass test = new Bridgepass ();
The persons want to pass bridge:
int source[] = {1,2,5,8,10};
Test.setsource (source, source.length);
Test.passmethod (Test.getsource (), Test.getdestination (), source.length, 0);
}
}
Overview: As a collection on both sides of the bridge, the recursive representation of the past two comes back one.
Java implementation of bridge problem