Transcript
Use with ChatGPT / Claude Auto-scroll A
we just started a new unit on graph theory which is going to be sort of our focus for the next couple lectures uh in 6.06 uh and so i thought we'd give a little bit of review at thebeginning of lecture because as usual i muddled together a lot of notions in our previous lecture uh and then start with some new ideas so basically in our previous lecture we talked about an algorithm called breadth first searchuh and then almost always you see that paired with the second algorithm called depth first search uh and following tradition and basically logic we'll uh do the same thing uh in 06 today uh but in any event fortoday we'll we'll stick to the technical material so as a little bit of review i guess actually the one thing i didn't do on this slide was actually draw a graph so we should probably start with that uh
so if you recall graph is a collection of nodes or vertices depending i don't know is it like a european american thing or something uh and edges right so here's an example which as usual i'm not managing todraw particularly clearly uh so this uh graph is kind of like a cycle so i have directed edges here here here and here and of course uh there are many kind of variations on the theme right so ourbasic uh sort of definition of a graph is that we have some set v which is like the set of vertices
and then we have a set e which is set of edges
and this was a subset of v cross v and this is nothing more than fancy notation for saying that an edge is a pair of vertices right like a from and a two vertex of course there are manyvariations on this theme you could have a directed versus an undirected uh graph so this one is directed meaning the edges look like arrows if they didn't have arrowheads they'd be undirected uh we defined something called a simplegraph where you have essentially no repeated edges so for instance you can't do something like this where you have the same edge twice um and then there are a couple different definitions that were kind of useful right soin particular i'm gonna erase this oops useless edge here maybe make my graph slightly more interesting so i'll add another edge going in the reverse direction so maybe i have um i'm going to give my vertices labels x
y z and w then uh we talked about the uh the neighbors of a given vertex which are the vertices that you can reach by following edges in or out of your your vertex right so in particular theoutgoing neighbors uh which we sort of implicitly defined in our previous lecture but didn't call it out um we're going to notate with adj plus and these are all of the things that you can reach by going outof a vertex into the next one so for example uh adj plus of w is going to be the set of vertices well notice i can get from w to y and also from w to z yeah sooop nope y comma z okay uh so to continue just our tiny amount of review for the day uh remember that a graph uh there are many different ways to represent a graph uh the sort of brain dead
one will be just like a big long list of edges but of course for our algorithms that's not a particularly efficient way to check things like does this edge exist in my graph uh so the the basic representationthat i think we're mostly working from in this course is to think of a graph like a set of vertices each of which maps to another set of vertices so roughly every vertex maybe stores its outgoing uh setof edges right and and so this is kind of nice because of course uh very quickly we can answer questions like is this edge inside of our graph or we can iterate over the neighbors of a vertex andso on which are the kind of typical things that we do in a lot of graph algorithms and then finally in our previous lecture we started talking about paths right so a path is like a chain of vertices
that can get me from one vertex to the other only following edges of my graph there was a term that i think i forgot to define last time because it didn't really matter a ton which is a simplepath which is just a path that doesn't have the same vertex more than once uh and then of course there are many different questions you can ask about a graph that are basically different problems involving computing paths rightso for instance the shortest path between two vertices is sort of our canonical one and graph theory or you could ask questions about reachability and so on so there's our uh our basic review from our previous lecture uhdo our does our course staff have any questions about uh things so far excellent okay and uh there's one additional piece of terminology that i fudged a little bit last time or other uh my my co-instructors suggested a
bit of an attitude adjustment so i thought i'd better uh uh clarify really quick there's this interesting phrase uh linear time which we all know and love in in computer science theory and and the sort of implicit thingespecially in this course is that when we say linear time we mean in the size of the input right and so if we have a linear time graph algorithm well how much space does it take to store agraph well we need a list of vertices and a list of edges and nothing else so a reasonable way to interpret this phrase linear time is that it's an algorithm that looks like what we've shown on the screenright the the times proportional to maybe the sum of the number of vertices and the number of edges if that makes you uncomfortable like it does for me because one of these can kind of scale on the other
i think it's always fine to add more detail right so if you want to say linear in the sum of the number of vertices and edges that's that's perfectly fine but if you see this phrase that's uh howyou should interpret it hopefully that's a fair way to put it excellent okay so um last time we talked about an algorithm called breath first search bfs for those in the know breath first search uh is an algorithmuh and and the reason we use the word breath is because it's kind of remember we we talked about level sets last time uh because we talked about breath first search in the context of computing shortest paths uhand in particular uh we have our our source uh node all the way on the left hand side and then breadth first search constructed all the nodes that were distance one away right that's the first level set and
then all the distance two away and then all the distance three away and so on right so in particular like the level set l3 isn't visited until we're completely done with level set l2 today we're going to defineanother algorithm which is called depth first search which doesn't do that but rather starts with the source vertex and just starts walking all the way out until it can't do that anymore and then kind of backtracks it's oneway to think about it uh and so somehow in breath first search we're like drawing concentric circles in depth first search we're doing the opposite we're like shooting outward until we reach the outer boundary and then exploring agraph that way okay and these are sort of the two extremes in terms of graph search kind of techniques uh that are typically used under the basic building blocks for for algorithms and graph theory so in order to
motivate and think about death for search we're going to define a second problem which is closely related to shortest path but not exactly the same and that's the reachability problem so here i have the world's simplest uh directedgraph so the black things are the edges and the circles are the uh notes or the vertices and i've marked one special note in blue uh and his name is the source node and now the question i wantto ask is what are all of the other nodes in my graph that i can reach by following edges directed edges starting with the source right so obviously i can get to the node in the lower right noproblem and of course once i get there i can traverse an edge upward to get to that second green vertex notice that i was really sneaky and evil and i drew edges in this graph that might make you
think that the red note is reachable the red one being on the upper left i'm realizing now that for colorblind people this isn't a great slide uh but of course uh because all the edges from the red vertexon the left here point out i can't actually reach it from the blue source node so the reachability problem is just asking which nodes can i reach from a given source it's pretty straightforward i think of course thereare many ways uh to solve this right in fact one way we could do it uh would be to use our previous lecture right we could compute the shortest path distance from the source to all the other nodesand then what would the length of the shortest path from the source to an unreachable node b any thoughts from our audience here infinity thank you uh professor domain uh right so in addition to this uh of course
a totally reasonable question thinking back to our shortest path lecture uh there are sort of two queries we might make right one is just what is the length of the shortest path the other is like what is theactual shortest path from the source to a given vertex we can ask a very similar thing here right which is like okay you tell me that the green guy is reachable but like how like give me a pathas as evidence or a certificate if you want to be fancy about it so uh in order to do that just like last time remember we defined a particular data structure that was the shortest path tree uh wecan do something very similar here right in particular this is like the extent of my powerpoint skill here if i have a reachability problem i can additionally store i can decorate every node in my graph with one other
piece of information which is the previous node along some path from my source to that thing right and just like last time if i want to get an actual path from the source to w what could i doi could start with w and then just keep following those parent relationships until i get back to the source then if i flip the order of that list of vertices i get a path from the source to thetarget that's valid right so this object is called a path tree just like we talked our parent tree rather uh just like we talked about in our last lecture uh there's no reason why this thing should ever havea cycle in it uh it's certainly a tree um right so uh that's the basic reachability problem and in addition to that we can compute this object p which is going to give me sort of information about how
any given node was reachable there's a slight difference between the parent tree that i've defined here and the shortest path tree which i defined last time which is i'm not going to require that the shortest path i getor oh man the path i get when i backtrack along my my tree p is the shortest path it's just a path right because for the reachability problem i actually don't care right like i could have a weirdcircuitous crazy long path and it still tells me that a node is reachable uh right so that's our basic setup and our data structure and now we can introduce a problem to to solve reachability again we already havean algorithm for doing that right which is to compute shortest paths and and remember that our shortest path algorithm from previous lecture took linear time and the size of the input right it took uh v plus e time
now the question is can we do a little better the answer obviously is yes because i just asked it and i gave you this problem okay and here's a here's a technique for doing that which unsurprisingly is arecursive algorithm i'm going to swap my notes for my handwritten notes and this uh algorithm is called death first search and here's the basic strategy i'm going to choose a source node i've labeled that node one here isuppose actually would have made sense for me to actually zero index this maybe in the slides i'll i'll fix it later but in any event i'm going to mark my my source node and now i'm going to lookat every node every edge coming out of that node and i'm going to visit it recursively right so that's our sort of for loop inside of this function visit and then for each neighboring node if i haven't visited
it before in other words i currently haven't given it a parent right that's our if statement here i'm going to say well now they do have a parent and that parent is me and i'm going to recurse youguys see what this is doing it's kind of crawling outward inside of our graph so let's uh let's let's do the example on the screen and i purposefully designed this experiment or this example to look a little bitdifferent from breath first search at least if you choose to do the ordering that i did so here's our graph one two five three four okay and let's uh think about the traversal order uh that that's first searchis gonna do right so here's our sourceand now what does the source do it record so let's think about a recursion tree so we have uh the source all the way up in here and now he's gonna start calling uh the visit function recursively so
um and i'll go ahead and number these the same as on the screenwell he has one outgoing neighbor and it hasn't been visited yet so of course the very first recursive call that i'll make is to that neighbor too now the neighbor two also recurses hopefully this kind of schematic picturemakes some sense what i'm trying to draw here and well now the two has two neighbors right a three and a five so let's say that we choose three firstwell the three now recurses he calls four and then the recursion tree is kind of done so now it goes back out and then finally well now the three are oh boy yeah the two looks at its nextneighbor which is the five uh and envisions that recursively notice that this is not following the level sets right the death first search algorithm got all the way to the end of my tree in the recursive uh calls
and then kind of backed its way out to the two before calling the five these are not the same technique one goes all the way to the end and then kind of backtracks whereas when i say backtrack whati mean is the recursion is kind of unraveling um whereas in breadth first search i visit everything in one level set before i work my way out does that distinction make sense okay so of course we need toprove that this algorithm does something useful uh so let's do that now so in particular we need a correctness proof so our claim is going to bethat uh let's see here the depth first search algorithm visits oh uh i guess reachable
v um and that it correctly sets uh the parent in in the process
um okay so in order to prove this uh of course as with almost everything in this course we're going to use induction uh and in particular what we're going to do is do induction on the distance from thesource so we're going to say that like for all vertices in distance k from the source this statement is true and then we're going to prove this inductively on k okay so we want to do induction on kwhich is the distanceto the source vertex so uh as with all of our inductive proofs we have to do our base uh case and then our inductive step so in the base case k equals zero this is a hella easy casebecause of course uh what is the thing that is distance zero from the source it's the source yeah and take a look at our our strategy all the way at the top of this slide we explicitly set the
correct parent for the source and in some sense visit it because the very first thing we do is call visit of s so there's kind of nothing to say here yeah or there's plenty to say if you writeit on your homework but your lazy instructor is going to write a check mark here okay so now we have to do our inductive step
so what does that mean we're going to assume that our statement is true for all nodes within a distance k and then we're going to prove that our statement is true for all nodes within a distance k plusone okay uh so uh let's do that let's considera vertex v that's distance k plus one away so in other words the distance from the source to v is equal to k plus one right and what's our goal our goal is to show that the parent ofv is is set correctly yeah what's thatoh sorry i forgot that the distances in this class are ordered yeah that's absolutely right so it should be the distance from s to v yeah sorry i'm really not used to thinking about directed graphs but that's that'sa good fix okay so uh now what can we do well there's this number is distance here so in particular there's some shortest path from s to v so remember our argument last time right that essentially when we
look at shortest path and we kind of truncate by one it's still the shortest path uh that property doesn't matter so much here but at least we know that there's another vertex on the path which is one adistance one less away so let's let's take youwhich is also a vertex to be the previous node on the shortest path
from s to v right and so in particular we know that the distance from s to u is equal to k and conveniently of course by our inductive uh hypothesis here we know that our property is true forthis guy okay so now our algorithm what do we know well because our property is true the visit function at some point in its life is called on this vertex u right that's sort of what our induction assumesso we have two cases um right so uh when we uh when we visit you um we know that when we call this uh uh visit function well remember that v kind of by definition is in adj plusof view right so in particular dfs is going to consider
v when it gets called okay and now there's two cases right so either when this happens p of v does not equal none right well what does that mean well it means that we already kind of found asuitable parent for v uh and we're in good shape otherwise p of v does equal none well in this case a very next line of code correctly sets the parent and and we're all set right so in bothof these two cases uh we show that the parent of uh you was set correctly either by that line of code right here or just previously uh and and so in either case our our induction is done allright i guess uh given the feedback i received from our previous lecture we now can and end our latex uh suitably okay so what did we just show we showed that the death first search algorithm can dig around
in a graph and tell me all of the things that are are searchable or rather are reachable from a given source just basically by calling visit on that source and then expanding outward recursively okay so i think thisis certainly straightforward from an intuitive uh perspective it's easy to get lost when you write these kind of formal uh induction proofs because they always feel a tiny bit like tautology so you should go home and kind ofconvince yourself that it's that it's not okay so of course what do we do in this class we always follow the same kind of boring pattern the first thing we do define an algorithm second thing we do makesure it's the right algorithm what's the third thing we need to do analyze it that's right in particular make sure that it like finishes before the heat death of the universe uh and indeed uh death first search uh
doesn't really take all that long which is a good thing um so let's think about this a bit so what's going to end up happening in depth first search well we're going to visit every vertex at most onceright kind of by definition here and in each case we're going to just visit its neighboring edges can we ever traverse an edge more than one time right because the visit function only ever gets called uh one timeper vertex and our edges are directed right so kind of you think about the from of every edge uh the from vertex is only ever visited one time and hence every edge is only visited one time do weever visit ah yes does dfs work an undirected graph uh absolutely so there's sort of uh different ways to think about it uh one is to think of an undirected graph like a directed graph with two edges pointed
either way which i think is in this class how we actually kind of notated it in the previous lecture um yeah actually that's that's probably a reasonable way to reduce it so we'll stick with that uh right nowdoes dfs ever visit a vertex that is not reachable from the source well the answer is no right because all i ever do is recursively call on my neighbors and so kind of by definition if i'm not reachabledfs will never see it so if i think about my run time carefully it's not quite the same as breath first search remember that breath for search took v plus e time in depth first search it just takesorder e time because i'm expanding outward from the source vertex hitting every edge adjacent to every uh every vertex that i've seen so far uh but i never reach a vertex that i have in the that isn't reachable
right and so because this only ever touches every edge one time uh we're in good shape uh and i see a question here yeah does vfs reach vertices that are not reachable uh does bffs reach vertices that arenot reachable i guess not now that you mention it but at least in my boring proof of of order v time last time our very first step of bfs reserved space proportional to v um which is enough toalready uh make that that run time correct good question yeah so i guess the way that we've talked about it where you construct one level set after a time um if you think of that as reachability then thenno it doesn't reach it in the for loop but just by construction when we started uh we already took the time that we're talking about here so notice these runtimes aren't exactly the same so for example if my
graph has no edges bfs still is going to take time yeah because it still has to uh take order v time at least the way in the sort of brain dead way that we we've implemented it last timeobviously in that case we could probably do something better whereas the way that we we've defined the dfs algorithm it only takes edge time i see confusion on my instructor's face no okay good uh the one thing tonotice is that these are algorithms for slightly different tasks in some sense right the way that we wrote down breadth first search last time conveniently it gives us the shortest path um there are breath first algorithms that doesn'ti think we're in this class we kind of think of breath first search uh we motivate it in terms of the shortest path problem but it's it's just kind of a strategy of working outwards from from a vertex
um whereas here uh the way we've written down death first search there's no reason why the path that we get should be the shortest right so to think of a really extreme example let's say that i have acycle graph
right so i get a big loop like this let's say that i do depth first search starting from this vertex well what will this what will happen well this guy will call its neighbor uh recursively who will thencall its neighbor recursively we'll then call his name recursively and so on so of course when i do a death first search when i get to this vertex there's a chain of one two three four vertices behind itis that the shortest path from the source to uh the target here well clearly not right i could have could have traversed that edge i just chose not to okay so that's the death first search algorithm it's justa essentially a recursive strategy where i traverse all my neighbors uh and and each of my neighbors versus their neighbors and and so on okay so why might we want to use this algorithm well we've already solved the
uh the reachability problem so let's uh solve a few more things using the same uh basic strategy here so there's some notions that we've sort of actually in some sense already used in the lecture here but we mightas well call them out for what they are which is this idea of connectivity so a graph is connected if there's a path getting from every vertex to every other vertex right now connectivity in a directed graph iskind of a weird object right like it could be like for instance think of a directed graph with just two edges and one edge goes from u to v right then i can get from v to u butnot vice versa that's kind of a weird uh notion so here uh in in 606 we'll mostly worry about connectivity only for undirected graphs because they're the vertices just basically come in like big connected uh clumps uh or
the more technical term for a big connected clump is a connected component yeah so let's see an example so let's say that i have a graph which has an edge and then a triangle this is one graph doyou see that there's a collection of vertices and there's a collection of edges but uh it has two connected components right the guy on the right and the guy on the left meaning that each vertex here is reachablefrom every other vertex here each vertex here is reachable from every vertex here but there's no edge that goes from the triangle to the line segment yep and so in the connected components problem we're given a graph likethis guy and initially we don't you know okay when i draw it like this it's pretty clear that uh you know my graph has two connected components maybe my graph embedding algorithm failed and it drew an edge like
that well then maybe i don't know it's still pretty obvious that there's two connected components but you can imagine a universe where you don't know that a priori and and the problem you're trying to solve is just toenumerate all these clumps of vertices that are reachable from one another in a an undirected graph and conveniently um we can use depth first search to solve this problem pretty easily right so how could we do it wellin some sense how can we find one connected component so let's say that i just choose a vertex in my graph well what do i know about everything in this connected component well it's reachable from that vertex rememberwe just solved the reachability problem which says if i have a vertex i can now tell you all the other vertices that are reachable from this guy right so i could call dfs on well any vertex of this
cycle here called the reachability thing and i know that for every vertex there's one of two things right either that vertex has a parent in that object p or it's the source right so i could very easily findthe connected component corresponding to that vertex does that make sense have i found all the connected components no i found one right i found the one corresponding to the arbitrary vertex that i just chose so how could ifix this well it's super simple i could put a for loop on the outside which just loops over all the vertices maybe and if that vertex is not part of a connected component yet then i need to makea new one so then i call dfs on that vertex i collect all the vertices that i got and i iterate so this is a the algorithm that uh in this class we're going to call full dfs by
the way you could do the same thing with full breadth first search that's perfectly fine um just kind of by analogy here right so what is full d oh this chalk is easier uh well i'm going to iterateover all my vertices where i stands for for loop
right so if v is unvisited
then i'm going to do d f s starting at v i guess we use we use visit to refer to this in the previous slide and that's going to kind of flood fill that whole connected component and theni can connect you know collect that connected component and continue be a little bit careful because of course we don't want like checking things something to be visited to somehow take a bunch of time and make my algorithmslower than it needs to be but of course we have a set data structure that we know uh can do that in in order one time at least in expectation okay so this is the full dfs algorithm it'sreally simple well it's dfs because i called dfs on every vertex it was full because i looped over all the vertices uh right and so if we think about it how much time does this algorithm take it's a
little bit sneaky because somehow i have a for loop over all the vertices that i could imagine a universe where i get like vertices times some other number because there's a for loop and there's something inside of itright i think that's how we're used to thinking about run time of for loops but in this case that actually doesn't happen because there's never a case where an edge gets traversed more than one time because if i'min one connected component then by definition i can't be in another connected component right and so what happens is in some sense this innocent looking call to dfs i suppose if you were like a lisp programmer you somehowwouldn't like this it has a side effect right which is that i marked all the vertices in that connected component as don't touch me again right and so implicitly i kind of removed edges uh in this process so
if you think through it carefully the runtime of this full dfs algorithm is v plus e time because every edge is touched no more than one time kind of amortized over all the the different calls to d ofs here uh and there's this for loop over vertices so there's clearly an an order v that you you need here does that argument make sense so again we call that linear in the size of the the inputi'm going to say it many times to get it in my own head correctly okay uh right so this is the the basic problem this comes up all the time by the way like it seems like somehow atotally brain dead weird algorithm like somehow why would you want an algorithm finds connected components like why would you even have a graph that's disconnected or something um but of course that can happen a lot so if like
for instance maybe work at a social media company and people have friends but like you know eric and i are friends and we're not friends with anybody else we have a we have a there's like a blood oathkind of thing uh then you know that might be not so easy to find uh in the graph because of course we're just two among a sea of students in this classroom uh uh all of which have differentinterconnections that are just enumerated uh based on the list of edges right and and so even though like pictorially it's kind of hard to draw uh connected component algorithm in a way that doesn't make it sound kind oflike a useless technique from the start because like it's very clear there are two connected components there uh of course we still have to be able to write code to solve this uh this sort of thing okay so
for once i think i'm almost on time uh in lecture today so we have one additional uh application of of death first search uh in our class today uh which is sort of on the opposite end of thespectrum so we just talked about uh graphs that are undirected and thinking about cycles uh now on the opposite end we might think of a dag so a dag is a directed acyclic graph can anybody think of aspecial case of a dag i suppose i should define it first and then we'll come back to that question uh which means uh exactly what it sounds like so it's a graph that has directed edges now and doesn'thave any cycles in it so actually the graph i gave you all the meaning of lecture um i think secretly was an example of one of these so let's say that i have directed edges maybe if i make
the header triangle that's a little easier to see i'm not so sure uh in any event so i'm going to have an edge up and an edge to the right and similarly an edge down an edge to theright
this graph looks like a cycle but it's not because the only direction that i can move is from the left-hand side to the right-hand side so this is a directed graph and it doesn't contain any cycles meaning there'sno path that i can take from a vertex that gets back to itself along the directed edges okay and dags show up all the time now that i've defined what a dag is can somebody give me an exampleof a dag that we've already seen in 6006
a tree at least if we orient all the edges kind of pointing downward in the tree yep otherwise i guess kind of debatable whether it's a dagger you know if there's if there's no direction to the edges thensomehow the definition just doesn't apply um okay so in uh in processing directed acyclic graphs uh there's a really useful thing that you can do that's going to show up in this class apparently quite a bit which iskind of interesting to me i'm curious to see what that looks like which is to compute a topological order on the graph where topology is here so as a geometry professor in my day job i get all exciteduh but in this case a topological order is a fairly straightforward thing actually it's defined on the screen and i have bad handwriting anyway so let's just stick with that so topological ordering so if we think of like
f as a function that assigns maybe every node an index in array i should i guess i shouldn't use the word right here but it's just like an index in ordering so like this is the first vertex andthis is the second vertex and so on then a topological order uh is one that has the property shown here which is that if i have a directed edge from u to v then f of u is lessthan f of v so in other words if i look at the ordering that i get in my topological order u has to appear before v yeah so let's uh let's look at our example again so let's numberlet's give our nodes names so here's a b c d well what clearly has to be the first node in my topological order a right because all the way on the left-hand side yeah well after that it's a
bit of a toss up what do we know we know that b and c have to appear before d so maybe just to be annoying i do a c b that's b and then d right so it's atopological order notice that things that are on the left appear in my graph before things that are on the right where the word before here uh means that there's an edge that points from one to the other okayby the way are topological orderings uh unique no so if we look at our graph example here a b c d is also a topological order uh and what that means is it's somehow very liberating right it meansthat when we design an algorithm for finding a topological order uh there's some design decisions that we can make uh and we just have to find one among uh many uh but in any event we're gonna define a
slightly different notion of order and then we're gonna show that they're closely linked to each other and that is the finishing order so in the finishing order we're going to call full dfs on our graph remember that meanswe iterate over all our nodes and if we haven't seen that node yet we call dfs on it and now uh we're going to make an order in which as soon as the call to a node in thatvisit function is complete meaning i've already iterated over all my neighbors then i add my node to the ordering that makes sense it's like a little bit backward from what we're used to thinking about so the order inwhich full dfs finishes visiting each vertex yeah and now here's uh here's the claim is that if we have a reverse finishing order meaning that we take the finishing order and then we flip it backward that's exactly uh
gonna give us a topological ordering of the vertices in our graph um right so let's uh do that really quickly so in other words our claim herei think yeah let's see is that if i have a directed graph so g is a dag then um uh let's see here then oops my notes are backwards so i should switch to my jason's notes which ofcourse are correct
right so if if i have a graph that's a dag then the reverse of the finishing order
is a topological order
by the way we're not going to prove the converse that if i have a topological order that somehow that thing is the reverse of uh dfs at least the way that maybe i coded it there's a slightly differentstatement which is does there exist a dfs that has that ordering but that's one that we'll worry about another time around piazza or whatever okay so uh let's see here so we need to prove this thing so whatare we gonna do well what do we need to check if is a top large quarter is that if i look at any edge in my graph it obeys the relationship that i have on the screen here uhso in particularly we're going to take the u v inside of my set of edges and then what i need
is the u is ordered before v uh using uh the reverse of the finishing order that we've defined here okay so let's think back to our call to the dfs algorithm remember we call this visit function right sowe have two cases right either u is visited before v or it ain't yeah uh so let's let's do those uh those two cases
so case number one is u is visited before v
okay
all right so what does that mean well remember that there's an edge like pictorially what's going on well there's like all kinds of graph stuff going on and then there's u and we know that there's a directed edgefrom u to v right that's our our picture right and maybe there's other stuff going on outside of v so in particular well just by the way that we've defined that visit function what do we know we knowthat when we call visit on u well v is one of its outgoing neighbors so in particular a visit on you is going to call
visit v and we know that because well you visited before v right so currently v's parent is none when i get to u that makes sense now here's where reverse ordering we're gonna have to keep it in ourhead right because now well you visit a view called visitor v so notice that visit of v has to complete before visited of you
right v completes beforevisit of u well so in reverse uh uh sorting in reverse finishing order here what does that mean well if this completes before uh the other guy then they get flipped backward in the list which is exactly whati want because there's an edge from u to v okay so case one is done now we have case 2 which is that v is visited before you
okay so now um i'm gonna make one additional observation okay so uh let's now i'm gonna go back to my other notes because i like my schematic better
right so what's our our basic picture uh here i don't know i oh you know what it was i printed out another copy of this that's okay i can do it on my head okay so here's my mysource vertex his name is s now there's a bunch of edges and whatever there's a long path and now eventually what happens well i have a node v and somewhere out there in the universe there's another node uand what do i know i know that uh there's by assumption i know that there's an edge from u to v that makes sense so that's our sort of picture so far okay so what do we know weknow that our graph is acyclic yeah right that kind of by definition that's our assumption so can we reach u from v in other words does there exist a path from v to u right so that would look
like this
no because our graph is a cyclic and i just drew a cycle right so this is a big x there's a frowny face here can't do it he has hair unlike your instructor okay so uh right so whatdoes this mean well okay so by this uh picture i suppose we know that uh u cannot be reached from v
yeah so what does that mean well it means that the visit to v is going to complete and never see you right because remember though the visit to v only ever calls things that are kind of descendants ofv right so in other words visit a v completes
without seeing you
well that's exactly the same thing that we showed in our first case right so by the same uh reasoning right what does that mean in our reverse finishing order right the ordering from from u to v is ispreserved okay so that sort of completes our proof here the reverse finishing order gives me a topological order which is kind of nice and so this is a nice convenient way of taking all of the nodes in adirected acyclic graph and ordering them in a way that respects the topology or the connectivity of that graph so we're going to conclude with one final problem uh which i don't have a slide on but that's okay andthat's cycle detection so there's a bit of a an exercise left to the reader here so the problem that we're looking for now
is that we're given a directed graphthere's a g in graph case you're wondering but now we don't know if it's a dag or not and so the question that we're trying to ask is does there exist a cycle in our directed acyclic graph rightso we're just given our graph and we want to know like can we do this let's think through the logic of this a bit so what do we know we know that if our graph were a dag theni could call dfs get the ordering out and then i guess flip it it's ordering backwards so i could compute uh the reverse finishing order and it would give me a topological order of my graph right so ifi were a dag i would get a topological order when i called dfs so let's say that i ran dfs i got whatever ordering i got and now i found an edge that points in the wrong direction i
i can i can just double check my list of edges and i find one uh that does not respect the relationship that i see in the second bullet point here can my graph be a dag no because ifmy graph were a dag the algorithm would have worked i just proved it to you right so if if there were if my my graph were a tag then i could do a reverse finishing order and what iwould get back is a topological order so if i found a certificate that my order wasn't topological something went wrong and the only thing that could go wrong is that my graph is in a dag or yeah it'sin a deck in fact uh sort of an exercise left to the reader and or to your section do we still have section i think we do as of now um is that this is an if and only
if meaning that the only time that you even have a topological ordering in your graph is if your graph is a dac this is a really easy fact to sanity check by the way so it's not not likea particularly challenging problem but you should think through it because it's a good exercise to make sure you understand the definitions which is to say that if you have a topological order your graph is a dag if youdon't have a topological order your graph isn't a dag so in other words we secretly gave you an algorithm for checking if a graph is a dag at all right what could i do i could compute reverse finishingorder check if it obeys the relationship on the second bullet point here for every edge and if it does then we're in good shape my graph is a tag if it doesn't something went wrong and the only thing
that could have gone wrong is not being a dag okay so in other words uh secretly we just solved well i guess the way that i've written it here we've solved the cycle detection problem here which is tosay that well i have a cycle if and only if i don't i'm not a dag which i can check using this technique of course the word detection here probably means that i actually want to find that cycleand i haven't told you how to do that yet right all we know how to do so far is say like yeah somewhere in this graph there's a cycle and that's not so good um so we can doone additional piece of information in the two minutes we have remaining to sort of complete our story here which is to modify our algorithm ever so slightly to not only say like thumbs up thumbs down is there a
cycle in this graph but also to actually return the vertices as a cycle and here's the the property that we're gonna do that which is uh the following which is that if g contains a cycle
uhright then a full dfs will traversean edge from a vertex v to some ancestor v
i guess we haven't carefully defined the the term ancestor here essentially uh if you think of the sort of the running of of the dfs algorithm then an ancestor is like something that appears in the recursive call treebefore i got to v okay so how could we prove that welllet's take a cycle um and we'll give it a name in particular we'll say that it's a cycle from v0 v1 to vk and then it's a cycle so it goes back to v0 okay and i can orderthis cycle any way i want notice that if i permute the vertices in this list in a cyclical way meaning that i like take the last few of them and stick them at the beginning of the list it'sstill a cycle it's the nice thing about cycles uh so in particular without loss of generality
we're going to assume uh that v zero is the first vertex uh visited by by by dfs
what does that mean that means like when i do my dfs algorithm making all these recursive calls the very first vertex to be touched by this technique is v naught okay well now what's going to end up happeningwell think about the recursive call tree starting at v zero by the time that completes anything that's reachable from v zero is also going to be complete do you see that so like for instance v zero somewhere inhis call tree might call v one if it and notice that v one was not already visited so in fact it will for v1 i got to call v2 and so on and in particular we're going to getall the way to vertex k right so in other words we're going to visit vertex v k and notice what's going to happen so remember our algorithm in fact we should probably just put it up on the screen
would be easier than talking about it a bunch well v k is now going to iterate over every one of the neighbors of v k and in particular it's going to see vertex v naught right so we're goingto seethe edge from vk to v0 which is an edge kind of by definition right because we took this to be a cycle here well notice that's exactly the thing we set out to prove right namely that full dfstraverses an edge from a vertex to one of its ancestors here's the vertex k here's his ancestor v naught why do we know that it's an ancestor well because v naught was called in our call tree before anyof these other guys right so we wanted an algorithm that not only did cycle detection but also actually gave me this cycle what could i do well it's essentially a small modification of what we already have right so
whoops uh right if i want to compute topological order or whatever i can just do dfs and that'll tell me like year nay does their existing cycle if i want to actually find that cycle all i have todo is sort of check that topological order property at the same time that i traverse the graph during dfs and the second that i find an edge that loops back i'm done and so that's our basic algorithm hereand this is a technique for actually defining the cycle in a graph using the dfs algorithm