write java version of code, using better backtracking