anushi's blog

By anushi, history, 4 weeks ago, In English,

Usually, topological sort is implemented like

void dfs(int x) {
    vis[x] = true;
    for(int u = 0; u < n; u++) {
        if(!vis[u] && graph[x][u] == 1) {
            dfs(u);
        }
    }
    order.push_back(x);
}

And then printed in reverse order But if I implement this way

void dfs(int x) {
    order.push_back(x);
    vis[x] = true;
    for(int u = 0; u < n; u++) {
        if(!vis[u] && graph[x][u] == 1) {
            dfs(u);
        }
    }
}

And print in same order.

Can someone provide me a test case where 2nd approach will fail

 
 
 
 
  • Vote: I like it  
  • -7
  • Vote: I do not like it  

»
4 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by anushi (previous revision, new revision, compare).

»
4 weeks ago, # |
  Vote: I like it +6 Vote: I do not like it

It fails on the "standard" DAG:

4 4
1 2
1 3
2 4
3 4
»
4 weeks ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

edit: Sorry, I was completely wrong. Confused directed and undirected graphs.

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it +12 Vote: I do not like it

    You can easily have directed graph with n2 edges and no cycles. A simple example is graph with edges from vi to vj when i < j.