Exercise 2: Kahn's Algorithm on a Build Dependency Graph — Possible Solution ==================================================================== GIVEN ------------------------------ utils.o is needed by main.o AND by app (edges: utils.o -> main.o, utils.o -> app) main.o is needed by app (edge: main.o -> app) STEP 1: COMPUTE IN-DEGREES ------------------------------ in-degree(utils.o) = 0 (nothing points to it) in-degree(main.o) = 1 (one incoming edge, from utils.o) in-degree(app) = 2 (two incoming edges, from utils.o and from main.o) STEP 2: RUN KAHN'S ALGORITHM ------------------------------ Initial queue (every vertex with in-degree 0): [utils.o] Process utils.o: output utils.o. Decrement its neighbors' in- degrees - main.o drops from 1 to 0 (joins the queue), app drops from 2 to 1 (not yet 0, stays out). Queue now: [main.o] Process main.o: output main.o. Decrement its neighbor app's in- degree from 1 to 0 - app joins the queue. Queue now: [app] Process app: output app. No outgoing edges to decrement. Queue now empty - algorithm finished. RESULT ------------------------------ Build order: utils.o, main.o, app Checking every edge points forward: utils.o->main.o (correct), utils.o->app (correct), main.o->app (correct). This matches exactly what a real build tool must do - utils.o is compiled first since nothing else is ready until it exists, then main.o becomes buildable, and only once both utils.o and main.o exist can app finally be linked. WHY THIS WORKS AS AN ANSWER ------------------------------ The in-degree of each file is computed correctly before starting (app correctly counted as having two incoming edges, not one), and Kahn's own "process what's ready, then see what that unlocks" mechanism is followed exactly as this chapter describes it - a vertex only enters the queue at the moment its in-degree reaches zero, not before.