1377. Frog Position After T Seconds
https://leetcode.com/problems/frog-position-after-t-seconds/submissions/


Last updated
https://leetcode.com/problems/frog-position-after-t-seconds/submissions/


Last updated
Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4
Output: 0.16666666666666666
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7
Output: 0.3333333333333333
Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 20, target = 6
Output: 0.16666666666666666class Solution {
public:
double frogPosition(int n, vector<vector<int>>& edges, int T, int target) {
queue<int> q;
q.push(1);
vector<bool> v(n + 1, false);
vector<double> p(n + 1, 0);
p[1] = 1.0;
v[1] = true;
vector<vector<int>> g(n + 1, vector<int>());
for (const auto e : edges) {
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}
for (int i = 0; i < T && !q.empty(); ++i) {
for (int j = q.size(); j > 0; --j) {
const auto t = q.front(); q.pop();
int cnt = 0;
for (const auto n : g[t]) {
if (v[n]) continue;
++cnt;
}
if (cnt == 0) continue;
const double prob = 1.0 / (double)(cnt);
for (const auto n : g[t]) {
if (v[n]) continue;
v[n] = true;
q.push(n);
p[n] = p[t] * prob;
}
p[t] = 0.0;
}
}
return p[target];
}
};