Given that your schedule is acyclic, this is the way to do it: -
Will DFS on the chart start at the top of the source (only for external borders)
For each edge (u, v) in the graph associated with [u] [v] = true
Try to save the previous node in the DFS stack in an array and for each verified vertex v check the previous nodes in the stack and make [u] [v] = true, where u is the previous node.
If the graph is not acyclic, then first calculate the SCC using Kosaraju or Tarjan, and then reduce the graph to acyclic and connect [u] [v] = true for each pair in SCC
pseudo-code for a modified DFS procedure: -
bool connected[n][n] = {false}; bool visited[n] = {false}; int stack[n]; for each source vertex v do : DFS(v,stack,0); void DFS(int u,int stack[n],int depth) { if(!visited[v]) { visited[v] = true; for(int i=0;i<depth;i++) { connected[stack[i]][v] = true; } stack[depth] = u; for each edge(u,v) { connected[u][v] = true; DFS(v,stack,depth+1); } } }
Cosmic complexity: O(V^2)
Difficulty of time: O(V^2)
Note: -
If the number of queries is less, try using DFS for them separately and cache the results, as this will be more time consuming than that.
source share