100 likes | 257 Views
Modified. Chapter 15 Graphs. Part D – Graph Algorithms 2. Basic Graph Algorithms. Un-weighted graphs/digraphs Spanning tree Topological sort. Constructing a spanning tree. Assume an undirected graph
E N D
Modified Chapter 15 Graphs Part D – Graph Algorithms 2
Basic Graph Algorithms • Un-weighted graphs/digraphs • Spanning tree • Topological sort Java Software Structures, 4th Edition, Lewis/Chase
Constructing a spanning tree • Assume an undirected graph • A spanning tree is a subgraphof the original graph which includes all of the vertices but only some of the edges. • If the graph has N vertices, the spanning tree will have N-1 edges. • It will have no cycles; it is a tree • It uses the minimum number of edges to connect all of the vertices together • Lots of practical applications • If a network contains any cycles, an edge can be removed and the graph is still connected. Java Software Structures, 4th Edition, Lewis/Chase
Finding a spanning tree • Do a depth first traversal and record all edges traversed to get to a “new” edge. Java Software Structures, 4th Edition, Lewis/Chase
Find Spanning tree – DFT starting from vertex v create a stack S Initialize spanning tree edge list to empty mark v as visited and push v onto S while S is non-empty peek at the top u of S if u has an (unvisited) neighbor w, add edge from u to w to spanning tree, mark w and push it onto S else pop S Java Software Structures, 4th Edition, Lewis/Chase
Topological sort A diagraph is acyclic if it has no cycles. Such a graph is often referred to as a directed acyclic graph, or DAG, for short. DAGs are used in many applications to indicate precedence among events. A directed graph G is acyclic if and only if a depth-first search of G yields no back edges. Topological sort of a DAG: a linear ordering (sequence) of vertices such that if (u, v) is an edge of the DAG, then u appears somewhere before v in that ordering. Java Software Structures, 4th Edition, Lewis/Chase
Topological sort • Do a DFT of the DAG and put vertices onto the front of a linked list as they are finished. • https://www.cs.usfca.edu/~galles/visualization/TopoSortDFS.html Java Software Structures, 4th Edition, Lewis/Chase
Alternate algorithm for top. sort of DAG • Compute the indegrees of all vertices • Find a vertex U with indegree 0 and append it to the ordering • If there is no such vertex then there is a cycleand the vertices cannot be ordered. Stop. • Remove U and all its edges (U,V) from the graph. • Update the indegrees of the remaining vertices. • Repeat steps 2 through 4 while there are vertices to be processed. Java Software Structures, 4th Edition, Lewis/Chase