So I replicated a C++ n^2 solution in Java but it gave the wrong answer. What am I doing wrong? I think the problem is probably in the recursion but I am not sure.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Stack;
public class clocktree {
static ArrayList<Integer> adj [];
static int [] clocks;
static int [] using;
static boolean [] finished;
static int n;
static int dfst [];
static int[] t;
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("clocktree.in"));
PrintWriter pw = new PrintWriter(new FileWriter("clocktree.out"));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
clocks = new int[n];
dfst = new int [10000];
adj = new ArrayList[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
clocks[i] = Integer.parseInt(st.nextToken());
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n-1; i++) {
st = new StringTokenizer(br.readLine());
int first = Integer.parseInt(st.nextToken())-1;
int last = Integer.parseInt(st.nextToken())-1;
adj[first].add(last);
adj[last].add(first);
}
int total = 0;
for (int i = 0; i < n; i++) {
dfst = clocks.clone();
dfs(i,-1);
if (dfst[i] == 1 || dfst[i] == 12) {
total++;
}
}
pw.println(total);
pw.close();
}
public static int dfs(int curr, int parent) {
for (int i : adj[curr]) {
if (i != parent) {
dfst[i]++;
dfst[curr] += (12 - dfs(i, curr));
dfst[curr] = (dfst[curr]-1)%12 + 1;
}
}
if (parent != -1) dfst[parent]++;
return dfst[curr];
}
}