算法思路:
递归终止条件:到达叶子结点,不能再递归,不是叶子结点时,一直递归直到成为叶子结点。
满足题意条件:每层的叶子结点总和,递归的深度就是层数,通过传入深度的参数记录每层的叶子数。
Java代码:(第四个测试点未过)
import java.io.*;
import java.util.Arrays;
public class Main {
static int n, m;
static final int N = 105;
static int []e = new int[N];
static int []ne = new int[N];
static int []h = new int[N];
static int idx;
static int []ans = new int[N];
static int floor;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] split = br.readLine().split(" ");
n = Integer.parseInt(split[0]);
m = Integer.parseInt(split[1]);
Arrays.fill(h, -1);
while(m-- > 0) {
split = br.readLine().split(" ");
int k = Integer.parseInt(split[0]);
int p = Integer.parseInt(split[1]);
for(int i = 2; i < 2 + p; i++) {
int b = Integer.parseInt(split[i]);
add(k, b);
}
}
dfs(0, 1);
System.out.print(ans[0]);
for(int i = 1; i <= floor; i++)
System.out.print(" " + ans[i]);
}
public static void dfs(int step, int u) {
if(h[u] == -1) { //递归到叶子结点,记录并返回
ans[step]++;
floor = Math.max(floor, step);
return;
}
for(int i = h[u]; i != -1; i = ne[i]) //不是叶子结点,继续递归
dfs(step + 1, e[i]);
}
public static void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}