CS2420: Lecture 37 Vladimir Kulyukin Computer Science Department Utah State University
Outline Graph Algorithms (Chapter 9)
Finding Prime Numbers The simplest way of finding the next prime size of your hash table is to double the current size (TableSize) and start testing the numbers from 2TableSize on for being prime. A integer n is prime if there is no integer b/w 1 and n/2 + 1 that divides n.
Finding Prime Numbers The Sieve of Eratosthenes is another commonly used algorithm for finding prime numbers in a specific range. The algorithm is reasonably efficient but requires to allocate an array from 1 to n, where n is the upper bound of the range in which you are looking for primes.
Sieve of Eratosthenes Here is a Wiki link that explains the history and gives a pseudocode: – Here is a link to a C source (I am sure there are many more out there): –
Shortest-Path Algorithms Let G = (V, E) be an unweighted or weighted graph. Let s be a vertex of G. Find the shortest paths from s to every other vertex in G. This problem is sometimes referred to as the single source shortest paths problem.
Two Solutions Breadth-First Search for Unweighted Graphs. Dijkstra’s Algorithm for Positive-Weighted Graphs.
Breadth First Search (BFS): Unweighted Shortest Paths Every vertex W in G has a distance variable associated with it (W.Dist). This is the number of edges that it took the search to reach W. Initially, W.Dist = INF (some big number). Every vertex W in G also has a pointer to the vertex it was reached from (W.Prev). S is the start vertex. Q is a queue of vertices which is initially empty. The input to BFS is the start vertex S and the graph G (adjacency lists).
BFS: Pseudocode
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = { }; The notation means that V2 is a vertex such that V2.Dist = 0 and V2.Prev = NULL;
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = {, <V 5,1,V 2 }; When the vertex is colored yellow, it means it has been popped off the QUEUE.
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = {,, };
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = {, };
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = {, };
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = {, };
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = { };
BFS: Example V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 QUEUE = {};
BFS: Example Notice the order in which the vertices are visited: – ; –, – – ;
BFS: Vertex Visitation Tree V0V0 V6V6 V5V5 V3V3 V4V4 V1V1 V2V2 BFS forms a vertex visitation tree whose root is the start vertex. We can use the tree to find the path from the start vertex to every vertex reachable from the start vertex.