LeetCode 1377. Frog Position After T Seconds
Question
Given an undirected tree consisting of n
vertices numbered from 1 to n
. A frog starts jumping from the vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices it jumps randomly to one of them with the same probability, otherwise, when the frog can not jump to any unvisited vertex it jumps forever on the same vertex.
The edges of the undirected tree are given in the array edges
, where edges[i] = [fromi, toi]
means that exists an edge connecting directly the vertices fromi
and toi
.
Return the probability that after t
seconds the frog is on the vertex target
.
Example
1 | Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 |
Solution
首先理解题目意思,只要有选择可以跳,frog就会在t步内继续跳。这里也涉及到如果target是在叶子节点,然后无法再跳,我们就可以不管t的大小。但是如果target在途中的话,我们还有多的选择以及剩余t值,那么就无法到达。这道题也是一个无向图,所以构建的时候也需要小心。
Code
1 | // time: O(n) space:O(n) |