Skip to content

Commit c993042

Browse files
authored
Update frog-position-after-t-seconds.cpp
1 parent ef716c1 commit c993042

File tree

1 file changed

+75
-1
lines changed

1 file changed

+75
-1
lines changed

C++/frog-position-after-t-seconds.cpp

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,80 @@
11
// Time: O(n)
22
// Space: O(n)
33

4+
// bfs solution with better precision
45
class Solution {
6+
public:
7+
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
8+
unordered_map<int, vector<int>> G;
9+
G[1] = {};
10+
for (const auto& edge : edges) {
11+
G[edge[0]].emplace_back(edge[1]);
12+
G[edge[1]].emplace_back(edge[0]);
13+
}
14+
15+
vector<tuple<int, int, int, int>> stk = {{t, 1, 0, 1}};
16+
while (!stk.empty()) {
17+
vector<tuple<int, int, int, int>> new_stk;
18+
while (!stk.empty()) {
19+
const auto [t, node, parent, choices] = stk.back(); stk.pop_back();
20+
if (!t || !(G.at(node).size() - int(parent != 0))) {
21+
if (node == target) {
22+
return 1.0 / choices;
23+
}
24+
continue;
25+
}
26+
for (const auto& child : G.at(node)) {
27+
if (child == parent) {
28+
continue;
29+
}
30+
new_stk.emplace_back(t - 1, child, node,
31+
choices * (G.at(node).size() - int(parent != 0)));
32+
}
33+
}
34+
stk = move(new_stk);
35+
}
36+
return 0.0;
37+
}
38+
};
39+
40+
// Time: O(n)
41+
// Space: O(n)
42+
// dfs solution with stack with better precision
43+
class Solution2 {
44+
public:
45+
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
46+
unordered_map<int, vector<int>> G;
47+
G[1] = {};
48+
for (const auto& edge : edges) {
49+
G[edge[0]].emplace_back(edge[1]);
50+
G[edge[1]].emplace_back(edge[0]);
51+
}
52+
53+
vector<tuple<int, int, int, int>> stk = {{t, 1, 0, 1}};
54+
while (!stk.empty()) {
55+
const auto [t, node, parent, choices] = stk.back(); stk.pop_back();
56+
if (!t || !(G.at(node).size() - int(parent != 0))) {
57+
if (node == target) {
58+
return 1.0 / choices;
59+
}
60+
continue;
61+
}
62+
for (const auto& child : G.at(node)) {
63+
if (child == parent) {
64+
continue;
65+
}
66+
stk.emplace_back(t - 1, child, node,
67+
choices * (G.at(node).size() - int(parent != 0)));
68+
}
69+
}
70+
return 0.0;
71+
}
72+
};
73+
74+
// Time: O(n)
75+
// Space: O(n)
76+
// dfs solution with recursion with better precision
77+
class Solution3 {
578
public:
679
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
780
unordered_map<int, vector<int>> G;
@@ -35,7 +108,8 @@ class Solution {
35108

36109
// Time: O(n)
37110
// Space: O(n)
38-
class Solution2 {
111+
// dfs solution with recursion
112+
class Solution4 {
39113
public:
40114
double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
41115
unordered_map<int, vector<int>> G;

0 commit comments

Comments
 (0)