110 likes | 214 Views
Modified. Chapter 15 Graphs. Part C – Graph Algorithms 1. Basic Graph Algorithms. Un-weighted graphs/digraphs Connectivity Cycle detection Shortest path Spanning tree Topological sort. Basic Graph Algorithms. Weighted graphs/digraphs Minimum spanning tree Cheapest path
E N D
Modified Chapter 15 Graphs Part C – Graph Algorithms 1
Basic Graph Algorithms • Un-weighted graphs/digraphs • Connectivity • Cycle detection • Shortest path • Spanning tree • Topological sort Java Software Structures, 4th Edition, Lewis/Chase
Basic Graph Algorithms • Weighted graphs/digraphs • Minimum spanning tree • Cheapest path • Traveling salesman problem Java Software Structures, 4th Edition, Lewis/Chase
Dynamic graphs • Adding and removing vertices • Adding and removing edges Java Software Structures, 4th Edition, Lewis/Chase
Connectivity • For a graph (undirected) how can we determine if it is connected? • Answer: Do a depth first traversal and see if all of the vertices are reached. • For a digraph, how do can we determine if it is connected? • Answer: Do a depth first traversal from every vertex and see if all other vertices are reached. Java Software Structures, 4th Edition, Lewis/Chase
Cycle detection • For a graph, how can we detect if it contains any cycles? • Do a depth first traversal and look for “back edges”, edges from current node to a node already visited. • For a digraph – • Do the same, for every vertex as starting vertex. Java Software Structures, 4th Edition, Lewis/Chase
Finding shortest path (un-weighted) • For a graph, how do we find the shortest path (fewest edges) from vertex A to vertex B? • Do a breadth first traversal starting at A and going until B is reached, recording the path length and predecessor at each node visited. • Need more info stored at each node visited. • For a digraph – • Same Java Software Structures, 4th Edition, Lewis/Chase
Shortest path form A to B create a queue Q visit A, mark Aas visited, set path length=0, set pred=null,and put A into Q repeat until B is visited remove the head element u of Q for each w: (unvisited) neighbors of u visit w, mark w, set path length of w, set pred of w=u, and enqueue w Follow the preds backwards from B to A Java Software Structures, 4th Edition, Lewis/Chase