Question: Below is PS 4 import java.util. * ; public class WaterJug { static class State { int [ ] jugs; List path; State ( int
Below is PS
"import java.util.;
public class WaterJug
static class State
int jugs;
List path;
Stateint jugs, List path
this.jugs jugs;
this.path path;
public static void mainString args
Scanner scanner new ScannerSystemin;
int c scanner.nextInt;
int c scanner.nextInt;
int c scanner.nextInt;
int d scanner.nextInt;
int capacities c c c;
int initialState c;
List result bfsinitialState capacities, d;
if result null
for int state : result
System.out.printlnstate state state;
else
System.out.printlnNot Possible";
private static List bfsint initialState, int capacities, int target
Queue queue new LinkedList;
Set visited new HashSet;
List initialPath new ArrayList;
initialPath.addinitialState;
queue.addnew StateinitialState initialPath;
visited.addArraystoStringinitialState;
while queue.isEmpty
State currentState queue.poll;
int jugs currentState.jugs;
List path currentState.path;
Check if any jug has the target amount
for int amount : jugs
if amount target
return path;
Try all possible pours between the jugs
for int i ; i ; i
for int j ; j ; j
if i j
int newState pourjugs i j capacities;
String newStateString Arrays.toStringnewState;
if visited.containsnewStateString
visited.addnewStateString;
List newPath new ArrayListpath;
newPath.addnewState;
queue.addnew StatenewState newPath;
return null;
private static int pourint state, int from, int to int capacities
int newState Arrays.copyOfstate;
int amountToPour Math.minnewStatefrom capacitiesto newStateto;
newStatefrom amountToPour;
newStateto amountToPour;
return newState;
Answer please
It would be possible to model the water transfer problem PS using a graph and solve it using depthfirst search.
true
false"
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
