leetcode-1377-Frog Position After T Seconds
问题
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:
1 | Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 |
Example 2:
1 | Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 |
Example 3:
1 | Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6 |
Constraints:
1 <= n <= 100
edges.length == n-1
edges[i].length == 2
1 <= edges[i][0], edges[i][1] <= n
1 <= t <= 50
1 <= target <= n
- Answers within
10^-5
of the actual value will be accepted as correct.
分析
我们首先可以建立一个图,然后从点1开始使用深度优先搜索找到一条从1到target的路径。然后在求出选出这条路径的概率。
这个题目的carner case要考虑的比较多。
首先考虑,target就是1的情况,在这种情况下,要么t就是0,或者节点1的度为0才能返回概率1否则返回概率0.
如果我们经过了k步依然没有到达target,那么达到target的概率是0.
- 如果我们在k(k != 0)步之间到达了target,且target的度大于1,则达到target的概率是0.
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/14/leetcode-1377/
License: 知识共享署名-非商业性使用 4.0 国际许可协议