CS252 Algorithms Wednesday, 28 September 2022 + Questions about homework, reading, whatever + In-class test on 10/7 - There will be a lighter-weight homework assignment this week - On Friday 9/30 I'll talk through the structure and topics for the exam + BFS & DFS - Intuition is weird - Sample graph & let's run BFS & DFS by hand - Look at the algorithms - analyze running times - Look again: memory usage - stack, queue - recursion and the system stack - Building the tree + Topological sort - Why? - DAGs - Algorithm - try it on some examples - example that results in no-such-sorting - example that succeeds - termination - arguing that a DAG has a no-incoming-edge node ========== BFS(s): [Data structures] 1 T: tree 2 L: list of lists ("layers") 3 Visited: list of bool, one per node 4 current_layer [Initialization] 5 L[0] = [s] -- no additional layers yet 6 current_layer = 0 7 Visited[s] = true 8 Visited[v] = false for all v != s 9 T = ∅ [Traversal] 10 while L[current_layer] is not empty: 11 initialize L[current_layer + 1] = [] 12 for each node u ∈ L[current_layer]: 13 for each edge (u, v): 14 if not Visited[v]: 15 Visited[v] = true 16 add edge (u, v) to T 17 add v to L[current_layer+1] 18 current_layer = current_layer + 1 ==== DFS(s): [Data structures] 1 S: stack of nodes 2 Visited: list of bool, one per node [Initialization] 3 S = [s] [Traversal] 4 while S is not empty 5 u = S.pop() 6BROKEN!!!! if not Visited[u]: 7 Visited[u] = true 8 for each edge (u, v): 9 S.push(v) ==== Topological sort Given: directed graph G TopologicalSort(G): ''' Return None if there is no topological sort ''' v = any node with no incoming edges if no such v exists: return None else: return [v] + TopologicalSort(G - {v})