Anushi1998's blog

By Anushi1998, history, 7 years 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

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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

»
7 years 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
»
7 years 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.

  • »
    »
    7 years 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.