Question: Below is PS 4 import java.util. * ; public class WaterJug { static class State { int [ ] jugs; List path; State ( int

Below is PS4
"import java.util.*;
public class WaterJug {
static class State {
int[] jugs;
List path;
State(int[] jugs, List path){
this.jugs = jugs;
this.path = path;
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int c1= scanner.nextInt();
int c2= scanner.nextInt();
int c3= scanner.nextInt();
int d = scanner.nextInt();
int[] capacities ={c1, c2, c3};
int[] initialState ={c1,0,0};
List result = bfs(initialState, capacities, d);
if (result != null){
for (int[] state : result){
System.out.println(state[0]+""+ state[1]+""+ state[2]);
}
}else{
System.out.println("Not Possible");
}
}
private static List bfs(int[] initialState, int[] capacities, int target){
Queue queue = new LinkedList<>();
Set visited = new HashSet<>();
List initialPath = new ArrayList<>();
initialPath.add(initialState);
queue.add(new State(initialState, initialPath));
visited.add(Arrays.toString(initialState));
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 =0; i <3; i++){
for (int j =0; j <3; j++){
if (i != j){
int[] newState = pour(jugs, i, j, capacities);
String newStateString = Arrays.toString(newState);
if (!visited.contains(newStateString)){
visited.add(newStateString);
List newPath = new ArrayList<>(path);
newPath.add(newState);
queue.add(new State(newState, newPath));
}
}
}
}
}
return null;
}
private static int[] pour(int[] state, int from, int to, int[] capacities){
int[] newState = Arrays.copyOf(state,3);
int amountToPour = Math.min(newState[from], capacities[to]- newState[to]);
newState[from]-= amountToPour;
newState[to]+= amountToPour;
return newState;
}
}
"
Answer please
"It would be possible to model the water transfer problem (PS4) using a graph and solve it using depth-first search.
true
false"

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!