Today I've experienced hard times in topological sort. I'm used to use a simple Depth-First-Search recursively to order the vertexes and store the order in the 'order' vector.
But, if the graph has a cycle ? in this way, the DFS will end normally and won't tell you that, a good strategy is to think to put colors in the nodes, Imagine like if a vertex is 'WHITE' it has not been visited yet, if a vertex is 'GREY' it has been visited, but it sub-trees hasn't been visited yet and 'BLACK' if the vertex has been visited and all it's sub-trees has been visited too. Taking it inside the code is easy, instead of use a 'boolean' array to check if the node is visited or not, use a numerical array 'int' and set values for the colors, in this example I'm using '0' for 'WHITE, '1' for 'GREY' and '2' for black, then here goes the right code. I have to thank AlexDmitriev, dalex and Malinovsky239 who answered me in the Codeforces forum and gave me this strategy. Thank you guys.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); }
void dfs(int x) { vis[x] = 1; for(int u = 0; u < n; u++) { if(vis[u] == 1 && graph[x][u] == 1) has = true; if(vis[u] == 0 && graph[x][u] == 1) { dfs(u); } } vis[x] = 2; order.push_back(x); }
No comments:
Post a Comment