All Ancestors of a Node in a Directed Acyclic Graph LeetCode solution in C++
1class Solution {2public:3void dfs(vector<vector<int>> &graph, int i, int j, vector<vector<int>> &ans, vector<bool> &vis) {4vis[j] = true;5for (auto &x : graph[j]) {6if (!vis[x]) {7ans[x].push_back(i);8dfs(graph, i, x, ans, vis);9}10}11}12vector<vector<int>> getAncestors(int n, vector<vector<int>> &edges) {13vector<vector<int>> ans(n), graph(n);14for (auto &v : edges) {15graph[v[0]].push_back(v[1]);16}17for (int i = 0; i < n; i++) {18vector<bool> vis(n);19dfs(graph, i, i, ans, vis);20}21return ans;22}23};