File tree Expand file tree Collapse file tree 1 file changed +43
-1
lines changed Expand file tree Collapse file tree 1 file changed +43
-1
lines changed Original file line number Diff line number Diff line change @@ -39,8 +39,50 @@ class Solution {
39
39
40
40
// Time: O(|V| * |E| * log(|V| * |E|))
41
41
// Space: O(|V| * |E|)
42
- // topological sort
42
+ // bfs
43
43
class Solution2 {
44
+ public:
45
+ vector<vector<int >> getAncestors (int n, vector<vector<int >>& edges) {
46
+ vector<vector<int >> adj (n);
47
+ for (const auto & e : edges) {
48
+ adj[e[1 ]].emplace_back (e[0 ]);
49
+ }
50
+ vector<vector<int >> result (n);
51
+ for (int u = 0 ; u < n; ++u) {
52
+ bfs (adj, u, &result);
53
+ }
54
+ return result;
55
+ }
56
+
57
+ private:
58
+ void bfs (const vector<vector<int >>& adj,
59
+ int i,
60
+ vector<vector<int >> *result) {
61
+
62
+ vector<bool > lookup (size (adj));
63
+ vector<int > q = {i};
64
+ while (!empty (q)) {
65
+ vector<int > new_q;
66
+ for (const auto & u : q) {
67
+ for (const auto & v: adj[u]) {
68
+ if (lookup[v]) {
69
+ continue ;
70
+ }
71
+ lookup[v] = true ;
72
+ new_q.emplace_back (v);
73
+ (*result)[i].emplace_back (v);
74
+ }
75
+ }
76
+ q = move (new_q);
77
+ }
78
+ sort (begin ((*result)[i]), end ((*result)[i]));
79
+ }
80
+ };
81
+
82
+ // Time: O(|V| * |E| * log(|V| * |E|))
83
+ // Space: O(|V| * |E|)
84
+ // topological sort
85
+ class Solution3 {
44
86
public:
45
87
vector<vector<int >> getAncestors (int n, vector<vector<int >>& edges) {
46
88
vector<unordered_set<int >> lookup (n);
You can’t perform that action at this time.
0 commit comments