Graphs
CS61B Spring 2019 Discussion 11
Administrivia
Graph Basics
Graphs are data structures that have 2 components:
Path
Cycle
a
a
b
a
b
a
b
Directed
Undirected
a
b
d
c
a
b
d
c
Undirected
Directed
Directed with edge weights
How to represent a graph
2. Adjacency list
3. List of edges: (0, 1), (1, 2), (0, 2)
0
1
2
| 0 | 1 | 2 |
0 | 0 | 1 | 1 |
1 | 0 | 0 | 1 |
2 | 0 | 0 | 0 |
0
1
2
[1, 2]
[2]
Runtimes
idea | addEdge(s, t) | for(w : adj(v)) | printgraph() | hasEdge(s, t) | space used |
adjacency matrix | Θ(1) | Θ(V) | Θ(V2) | Θ(1) | Θ(V2) |
list of edges | Θ(1) | Θ(E) | Θ(E) | Θ(E) | Θ(E) |
adjacency list | Θ(1) | Θ(1) to Θ(V) | Θ(V+E) | Θ(degree(v)) | Θ(E+V) |
Graph Traversals: DFS
DFS traversal of a graph is very similar to DFS traversal of a tree. The only difference is, since graphs can have cycles, you need to prevent your function from visiting nodes that have already been visited in an effort to avoid infinite loops.
PreOrder: Process the node when you first visit it
PostOrder: Process the node the last time you visit it.
Graph Traversals: BFS
BFS differs from DFS in that instead of exploring a path all the way to the end, it takes a layer-by-layer approach
BFS pseudocode is exactly the same as DFS except with a Queue instead of a stack!
This is actually really cool, because it means we can recycle the entire algorithm but get a completely different traversal!
BFS also has the cool feature of finding the shortest path from one node to all other nodes in terms of number of edges.
Topological Sort
Berkeley CS courses Topological Sort
Give a valid topological sort for a student who is on the software track (light blue) given that they would need to take all of the red and blue classes.
Problem 1.1
Problem 1.1 SOLUTION
Problem 2.1
Problem 2.1 SOLUTION
Hint: A valid topological sorting can be obtained by reversing the DFS postorder.
Problem 2.1 SOLUTION
Hint: A valid topological sorting can be obtained by reversing the DFS postorder.
Problem 2.2
Problem 2.2 SOLUTION
Hint: How is order defined in the graph
Problem 2.2 SOLUTION
Hint: How is order defined in the graph
Problem 2.2 SOLUTION
Hint: How is order defined in the graph
Problem 2.3
Problem 2.3 SOLUTION
Hint: Consider every possible situation in which dfs could be called.
For any edge (u,v), what happens when dfs(u) is called
Problem 2.3 SOLUTION
Hint: Consider every possible situation in which dfs could be called.
For any edge (u,v), what happens when dfs(u) is called
Problem 2.3 SOLUTION
Hint: Consider every possible situation in which dfs could be called.
For any edge (u,v), what happens when dfs(u) is called
Problem 2.3 SOLUTION
Hint: Consider every possible situation in which dfs could be called.
For any edge (u,v), what happens when dfs(u) is called
Problem 3.1
right
Problem 3.1 SOLUTION
Problem 3.2
Problem 3.2 SOLUTION
Problem 3.3
Problem 3.3 SOLUTION