Graphs Reference:
Terminology A set of nodes (or vertices) connected by edges (or arcs). – Edges can be directed (one-way) or undirected (two-way) – A graph has a cycle if there is a path from a node back to itself.
A few applications Maps States of a Rubik’s (to find a solution) Speech models (for speech recognition) Regular Expressions (regex) ( see ) Compiler design …
Representation Two of the most common: – Adjacency List: a list of edges (for each) node of all the neighboring nodes. – Adjacency Matrix: a 2d array of edges “Apple” “Carrot” “Date”“Fox” “Eagle” “Bubble”
Adjacency List “Apple” “Carrot” “Date”“Fox” “Eagle” “Bubble” “Apple”(15,”Carrot”) “Bubble”(4,”Date”) “Carrot”(9, “Fox”)(1, “Eagle”)(3, “Bubble”) “Date”(6, “Eagle”) “Eagle”(12, “Date”) “Fox”(7, “Apple”) Good for sparse graphs (like this one)
Adjacency Matrix “Apple” “Carrot” “Date”“Fox” “Eagle” “Bubble” AppleBubbleCarrotDateEagleFox Apple Bubble Carrot Date Eagle Fox Good for dense graphs
Common Algorithms Breadth-first search: spread out evenly from a seed node. Depth-first search: tunnel down from a seed node, backing up if you’ve visited all neighboring nodes. Both algorithms need to track visited nodes – Perhaps inside the node structure. – Perhaps as a separate tree structure (a search tree) Depth-first search is naturally done using recursion (or with a stack). Breadth-first search needs a vector (the frontier of the search)
Example Graph A C E D J F B G I H ABCDEFGHIJ A2 B6 C29113 D98 E18 F617 G75 H6 I564 J
Breadth-first search A C E D J F B G I H ABCDEFGHIJ A2 B6 C29113 D98 E18 F617 G75 H6 I564 J
Depth-First Search A C E D J F B G I H ABCDEFGHIJ A2 B6 C29113 D98 E18 F617 G75 H6 I564 J
Pseudo-code On the board, come up with a prototype graph class (and Node class) with DFS and BFS algorithms (to print all nodes)
Floyd-Warshall Algorithm (1962) A slowish algorithm to find the shortest path which finds the shortest path from any node to any other node in the graph. (python) pseudocode 1.def floyd(adjMat, n): 2. Dist = matrix(n, n, infinity) 3. Next = matrix(n, n, None) 4. for v in range(0, n): 5. Dist[v][v] = for i in range(0, n): 7. for j in range(0, n): 8. if isEdge(adjMat, i, j): 9. Dist[i][j] = adjMat.cost(i, j) 10. for k in range(0, n): 11. for i in range(0, n): 12. for j in range(0, n): 13. if Dist[i][k] + Dist[k][j] < Dist[i][j]: 14. Dist[i][j] = Dist[i][k] + Dist[k][j] 15. Next[i][j] = k
Floyd’s Algorithm ABCDEFGHIJ A2 B6 C29113 D98 E18 F617 G75 H6 I564 J34 A C E D J F B G I H