- Algorithms-Graph Traversals, BFS, DFS, Graph

Find all the Mother Vertices of a graph

  #include using namespace std;  void dfs_helper(int u,                vector& adj,                bool visited[]){    if (visited[u])        return;      visited[u] = true;      for (auto v : adj[u]) {        if (!visited[v])            dfs_helper(v, adj, visited);    }}  void getTransposeGraph(    vector& adj,    vector& trans_adj){    for (int u = 0; u < adj.size(); u++) {        for (auto v : adj[u]) {            trans_adj[v].push_back(u);        }    }}  void initialize_visited(bool visited[], int n){    for (int u = 0; u < n; u++)        visited[u] = false;}  vector findAllMotherVertices(    vector& adj){    int n = adj.size();    bool visited[n];              initialize_visited(visited, n);    int last_dfs_called_on = -1;      for (int u = 0; u < n; u++) {        if (!visited[u]) {            dfs_helper(u, adj, visited);            last_dfs_called_on = u;        }    }                  initialize_visited(visited, n);    dfs_helper(last_dfs_called_on, adj, visited);      for (int u = 0; u < n; u++) {                          if (!visited[u]) {            vector emptyVector;            emptyVector.push_back(-1);              return emptyVector;        }    }                      int motherVertex = last_dfs_called_on;              vector trans_adj(n);              getTransposeGraph(adj, trans_adj);                          initialize_visited(visited, n);    dfs_helper(motherVertex, trans_adj, visited);              vector ans;      for (int u = 0; u < n; u++) {        if (visited[u])            ans.push_back(u);    }          return ans;}  int main(){        int V = 8;    vector adj(V);      adj[0].push_back(1);    adj[1].push_back(2);    adj[1].push_back(4);    adj[1].push_back(5);    adj[2].push_back(3);    adj[2].push_back(6);    adj[3].push_back(2);    adj[3].push_back(7);    adj[4].push_back(0);    adj[4].push_back(5);    adj[5].push_back(6);    adj[6].push_back(5);    adj[6].push_back(7);          vector motherVertices        = findAllMotherVertices(adj);          if (motherVertices[0] == -1)        cout