Frog Position After T Seconds

Given an undirected tree consisting of n vertices numbered from 1 to n, a frog starts jumping from vertex 1.

In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog cannot jump back to a visited vertex. If the frog can jump to several vertices, it chooses one of them randomly with the same probability. Otherwise, when the frog cannot 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] = [ai, bi] means there is an edge connecting vertices ai and bi.

Return the probability that after t seconds the frog is on vertex target. Answers within 10^-5 of the actual answer will be accepted.

Example 1
Inputn = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output0.16666666666666666
The frog moves from vertex 1 to vertex 2 with probability 1/3 after the first second, then from vertex 2 to vertex 4 with probability 1/2 after the second second, so the probability is 1/6.
Example 2
Inputn = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
Output0.3333333333333333
The frog starts at vertex 1 and jumps to vertex 7 after one second with probability 1/3.

Constraints

  • 1 <= n <= 100
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 <= ai, bi <= n
  • 1 <= t <= 50
  • 1 <= target <= n

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate