leetcode1377.T秒后青蛙的位置



思路源自灵神自底向上求解
class Solution {private long dfs(List<List<Integer>> graph, int target, int cur, int parent, int time) {//1.没有剩余时间了,如果当前节点就是目标,那么返回1,否则0if(time==0)return cur == target ? 1 : 0;//2.如果还有剩余时间但是当前点就是目标,那么如果这个目标没有孩子节点就返回1,否则0if(cur==target)return graph.get(cur).size() == 1 ? 1 : 0;//3.有时间且还没有找到目标,那么向下递归累乘分母for (int child : graph.get(cur)) {if (child != parent) {long product = dfs(graph, target, child, cur, time - 1);//3.1向下递归只有找到目标才不会返回0,这里说明找到目标,那么就累乘结果if (product != 0) {return product * (graph.get(cur).size() - 1);}}}//4.向下递归没有找到目标直接返回0return 0;}public double frogPosition(int n, int[][] edges, int t, int target) {//1.用无向图构造一棵树List<List<Integer>> graph = new ArrayList<>();for (int i = 0; i <= n; i++) {graph.add(new ArrayList());}graph.get(1).add(0);//给根节点添加一个虚拟头节点for (int[] edge : edges) {int u = edge[0];int v = edge[1];graph.get(u).add(v);graph.get(v).add(u);}//2.dfs求结果的分母乘积long product = dfs(graph, target, 1, 0, t);//3.如果是0说明目标不能在限定时间内刚好到达或者不存在return product == 0 ? 0 : 1.0 / product;}
}
