I am checking whether the specified word can be formed on this boggle board with the canForm
method. The board has a graph
field which indicates adjacent tiles. I do a DFS and set answer
to true
if the word can be formed.
I understand why the code as it is below doesn't work: answer
is a primitive, its value is copied at every recursion and the initial answer
(in the public method) stays false.
If I change boolean answer
to Set<String> answer = new HashSet<>()
for instance, pass the reference to the set in recursion, eventually add the successfully formed word and test for emptiness in the end, it works.
But why does it not work if I simply declare Boolean answer = new Boolean(false)
and pass this container? It passes the reference to the object all right, but it mysteriously changes the reference at assignment answer = true
(as seen through the debugger), and the initial answer
isn't reset. I don't understand.
public boolean canForm(String word) {
boolean answer = false;
int n = M * N;
char initial = word.charAt(0);
// for each tile that is the first letter of word
for (int u = 0; u < n; u++) {
char c = getLetter(u / N, u % N);
if (c == initial) {
boolean[] marked = new boolean[n];
marked[u] = true;
canForm(u, word, 1, marked, answer);
}
}
return !answer;
}
private void canForm(int u, String word, int d, boolean[] marked, boolean answer) {
if (word.length() == d) {
answer = true;
return;
}
for (int v : graph.adj(u)) {
char c = getLetter(v / N, v % N);
if (c == word.charAt(d) && !marked[v]) {
marked[v] = true;
canForm(v, word, d + 1, marked, answer);
}
}
}