class Solution {
int maxX = -1;
int maxY = -1;
public boolean canMeasureWater(int x, int y, int target) {
maxX = x;
maxY = y;
boolean[][] isVisited = new boolean[x + 1][y + 1];
isVisited[0][0] = true;
return backtrack(0, 0, target, isVisited);
}
public boolean backtrack(int x, int y, int target, boolean[][] isVisited) {
System.out.println(x + " " + y);
if (x == target || y == target || x + y == target) {
return true;
}
boolean canMesure = false;
if (!isVisited[x][maxY]) {
isVisited[x][maxY] = true;
canMesure |= backtrack(x, maxY, target, isVisited);
}
if (!isVisited[maxX][y]) {
isVisited[maxX][y] = true;
canMesure |= backtrack(maxX, y, target, isVisited);
}
if (!isVisited[0][y]) {
isVisited[0][y] = true;
canMesure |= backtrack(0, y, target, isVisited);
}
if (!isVisited[x][0]) {
isVisited[x][0] = true;
canMesure |= backtrack(x, 0, target, isVisited);
}
int yAfterFill = Math.min(maxY, x + y);
if (!isVisited[x + y - yAfterFill][yAfterFill]) {
isVisited[x + y - yAfterFill][yAfterFill] = true;
canMesure |= backtrack(x + y - yAfterFill , yAfterFill, target, isVisited);
}
int xAfterFill = Math.min(maxX, x + y);
if (!isVisited[xAfterFill][x + y - xAfterFill]) {
isVisited[xAfterFill][x + y - xAfterFill] = true;
canMesure |= backtrack(xAfterFill, x + y - xAfterFill, target, isVisited);
}
return canMesure;
}
}