40 likes | 150 Views
Graph Algorithms 1. http://www.flickr.com/photos/zubrow/6865196143/sizes/o/in/photostream/. Topological sort. Course Prerequisite Example. Each node is a course Each edge (U, V) denotes that U is a pre- req for V Find an order in which these courses can be taken. Topological sort.
E N D
Graph Algorithms 1 http://www.flickr.com/photos/zubrow/6865196143/sizes/o/in/photostream/ Topological sort
Course Prerequisite Example • Each node is a course • Each edge (U, V) denotes that U is a pre-req for V • Find an order in which these courses can be taken
Topological sort • Topological sort: a linear ordering of vertices such that for every arc (u, v), u comes before v in the ordering • Any linear ordering in which all the arrows go “right” is a valid solution. • Any linear ordering in which an arrow goes “left” is invalid. • Any directed graph with a cycle cannot be topologically sorted
Algorithm module topologicalSort(G) { L ← An empty list S ← A list of all nodes in G with in-degree 0 while S is notempty do • M← S.removeFirst() L.append(M) foreach node N with an edge Efrom M to N do remove edge E from G if N has in-degree 0 then S.append(N) endif endforeach endwhile if the size of G is greater than 0 then return error (G is not acyclic) else return L