-
Notifications
You must be signed in to change notification settings - Fork 2
/
structures.tex
3289 lines (3042 loc) · 136 KB
/
structures.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Structures}
Much of computer science deals with representing and manipulating
information. To do this, people have devised various \textbf{structures}
for organizing chunks of data in a way that makes it easy to store, search,
and retrieve. There's a whole course in most computer science curricula
called ``data structures" which covers how to implement these structures in
code. In this book, we won't be talking about the code, but rather the
abstract structures themselves. This chapter has a lot of pictures in it,
which depict examples of the various structures in a very general way. The
concepts here map directly to code when you need to put them into practice.
\index{data structures}
\index{graphs}
\index{trees}
There are all kinds of data structures --- arrays, linked lists, queues,
stacks, hashtables, and heaps, to name a few --- but they almost all boil
down to one of two fundamental kinds of things: graphs, and trees. These
are the two structures we'll focus on in this chapter. A graph is just
about the most general structure you can envision: a bunch of scattered
data elements that are related to each other in some way. Almost every data
structure imaginable can be recast as a type of graph. Trees are sort of a
special case of graphs, but also sort of a topic in their own right, kind
of like functions were a special type of relation, but also kind of
different. A tree can be seen as a type of graph that imposes extra special
conditions which give some navigational benefit.
\section{Graphs}
\index{graphs}
\index{vertex/vertices}
\index{edges}
\index{Booth, John Wilkes}
\index{Lincoln, Abraham}
In many ways, the most elegant, simple, and powerful way of representing
knowledge is by means of a \textbf{graph}. A graph is composed of a bunch of
little bits of data, each of which may (or may not) be attached to each of the
others. An example is in Figure~\ref{graph}. Each of the labeled ovals is
called a \textbf{vertex} (plural: \textit{vertices}), and the lines between
them are called \textbf{edges}. Each vertex does, or does not, contain an edge
connecting it to each other vertex. One could imagine each of the vertices
containing various descriptive attributes --- perhaps the \textsl{John Wilkes
Booth} oval would have information about Booth's birthdate, and
\textsl{Washington, DC} information about its longitude, latitude, and
population --- but these are typically not shown on the diagram. All that
really matters, graph-wise, is what vertices it contains, and which ones are
joined to which others.
\begin{figure}[ht]
\centering
\resizebox{0.95\textwidth}{!}{
\begin{tikzpicture}[every node/.style={ellipse,draw}]
\node (Abe) at (0,0) {Abraham Lincoln};
\node (DC) at (-2,-1.5) {Washington, DC};
\node (Ford) at (1,-3) {Ford's Theatre};
\node (Pres) at (3,1) {President};
\node (JWB) at (4,-1) {John Wilkes Booth};
\node (Actr) at (7,-2) {Actor};
\node (CW) at (4.2,-2.5) {Civil War}; % Really tempted to change this to 'Vampire'
\node (Getys) at (5,-4) {Gettysburg}; % and this to 'Vampire Hunter'
\draw (Pres) -- (Abe) -- (DC) -- (Ford) -- (JWB) -- (Actr);
\draw (Abe) -- (Ford);
\draw (CW) -- (Getys);
\end{tikzpicture}
}
\caption{A graph (undirected).}
\label{graph}
\end{figure}
\index{psychology}
Cognitive psychologists, who study the internal mental processes of the
mind, have long identified this sort of structure as the principal way that
people mentally store and work with information. After all, if you step
back a moment and ask ``what is the `stuff' that's in my memory?" a
reasonable answer is ``well I know about a bunch of things, and the
properties of those things, and the relationships between those things." If
the ``things" are vertices, and the ``properties" are attributes of those
vertices, and the ``relationships" are the edges, we have precisely the
structure of a graph. Psychologists have given this another name: a
\index{semantic network}
\textit{semantic network}. It is thought that the myriad of concepts you
have committed to memory --- \textsl{Abraham Lincoln}, and \textsl{bar of
soap}, and \textsl{my fall schedule}, and perhaps millions of others ---
are all associated in your mind in a vast semantic network that links the
related concepts together. When your mind recalls information, or deduces
facts, or even drifts randomly in idle moments, it's essentially traversing
this graph along the various edges that exist between vertices.
\index{MapQuest}
\index{Facebook}
\index{World Wide Web}
\index{Internet}
That's deep. But you don't have to go near that deep to see the appearance
of graph structures all throughout computer science. What's MapQuest, if
not a giant graph where the vertices are travelable locations and the edges
are routes between them? What's Facebook, if not a giant graph where the
vertices are people and the edges are friendships? What's the World Wide
Web, if not a giant graph where the vertices are pages and the edges are
hyperlinks? What's the Internet, if not a giant graph where the vertices
are computers or routers and the edges are communication links between
them? This simple scheme of linked vertices is powerful enough to
accommodate a whole host of applications, which is why it's worth studying.
\subsection{Graph terms}
The study of graphs brings with it a whole bevy of new terms which are
important to use precisely:
\begin{description}
\index{vertex/vertices}
\index{nodes (of a graph)}
\index{empty graph}
\item[vertex.] Every graph contains zero or more vertices.\footnote{The
phrase ``zero or more" is common in discrete math. In this case, it
indicates that the \textbf{empty graph}, which contains no vertices at all,
is still a legitimate graph.} (These are also sometimes called nodes,
concepts, or objects.)
\index{edges}
\index{links (in a graph)}
\index{loops (in a graph)}
\item[edge.] Every graph contains zero or more edges. (These are also
sometimes called links, connections, associations, or relationships.) Each
edge connects exactly two vertices, unless the edge connects a vertex to
itself, which is possible, believe it or not. An edge that connects a
vertex to itself is called a \textbf{loop}.
\index{paths (in a graph)}
\item[path.] A path is a sequence of consecutive edges that takes you from
one vertex to the other. In Figure~\ref{graph}, there is a path between
\textsl{Washington, DC} and \textsl{John Wilkes Booth} (by means of
\textsl{Ford's Theatre}) even though there is no direct edge between the
two. By contrast, no path exists between \textsl{President} and
\textsl{Civil War}. Don't confuse the two terms edge and path: the former
is a single link between two nodes, while the second can be a whole
step-by-step traversal. (A single edge does count as a path, though.)
\index{directed graphs}
\index{undirected graphs}
\item[directed/undirected.] In some graphs, relationships between nodes are
inherently bidirectional: if $A$ is linked to $B$, then $B$ is linked
to $A$, and it doesn't make sense otherwise. Think of Facebook: friendship
always goes both ways. This kind of graph is called an \textbf{undirected}
graph, and like the Abraham Lincoln example in Figure~\ref{graph}, the
edges are shown as straight lines. In other situations, an edge from $A$ to
$B$ doesn't necessarily imply one in the reverse direction as well. In the
World Wide Web, for instance, just because webpage $A$ has a link on it to
webpage $B$ doesn't mean the reverse is true (it usually isn't). In this
kind of \textbf{directed} graph, we draw arrowheads on the lines to
indicate which way the link goes. An example is Figure~\ref{directedGraph}:
the vertices represent famous boxers, and the directed edges indicate which
boxer defeated which other(s). It is possible for a pair of vertices to
have edges in both directions --- Muhammad Ali and Joe Frazier each
defeated the other (in separate bouts, of course) --- but this is not the
norm, and certainly not the rule, with a directed graph.
\begin{figure}[ht]
\centering
\resizebox{0.7\textwidth}{!}{
\begin{tikzpicture}[every node/.style={ellipse,draw}]
\node (MA) at (0,0) {Muhammad Ali};
\node (JF) at (0,-2) {Joe Frazier};
\node (SL) at (3,1) {Sonny Liston};
\node (GF) at (4,-1) {George Foreman};
\graph [multi] {
(MA) ->[bend left] (JF) ->[bend left] (MA);
(MA) -> (SL);
(MA) -> (GF);
(GF) -> (JF);
};
\end{tikzpicture}
}
\caption{A directed graph.}
\label{directedGraph}
\end{figure}
\index{weighted graphs}
\index{weight (of an edge)}
\item[weighted.] Some graphs, in addition to merely containing the
\textit{presence} (or absence) of an edge between each pair of vertices,
also have a number on each edge, called the edge's \textbf{weight}.
Depending on the graph, this can indicate the distance, or cost, between
vertices. An example is in Figure~\ref{weightedGraph}: in true MapQuest
fashion, this graph contains locations, and the mileage between them. A
graph can be both directed and weighted, by the way. If a pair of vertices
in such a graph is attached ``both ways," then each of the two edges will
have its own weight.
\begin{figure}[ht]
\centering
\resizebox{0.7\textwidth}{!}{
\begin{tikzpicture}
\node[ellipse,draw] (DC) at (0,0) {Washington, DC};
\node[ellipse,draw] (F) at (0,-2) {Fredericksburg};
\node[ellipse,draw] (R) at (0,-4) {Richmond};
\node[ellipse,draw] (V) at (5,-3) {Virginia Beach};
\graph [multi] {
(DC) --["50"] (F) --["60"] (R) --["100"'] (V);
(F) --["150"] (V);
};
\end{tikzpicture}
}
\caption{A weighted (and undirected) graph.}
\label{weightedGraph}
\end{figure}
\index{adjacent (vertices)}
\item[adjacent.] If two vertices have an edge between them, they are said
to be adjacent.
\index{connected (vertices/graphs)}
\item[connected.] The word \textbf{connected} has two meanings: it applies
both to pairs of vertices and to entire graphs.
\index{reachable}
We say that two vertices are connected if there is at least one path
between them. Each vertex is therefore ``reachable" from the other. In
Figure~\ref{graph}, \textsl{President} and \textsl{actor} are connected,
but \textsl{Ford's Theatre} and \textsl{Civil War} are not.
``Connected" is also used to describe entire graphs, if \textit{every}
node can be reached from all others. It's easy to see that
Figure~\ref{weightedGraph} is a connected graph, whereas Figure~\ref{graph}
is not (because \textsl{Civil War} and \textsl{Gettysburg} are isolated
from the other nodes). It's not always trivial to determine whether a graph
is connected, however: imagine a tangled morass of a million vertices, with
ten million edges, and having to figure out whether or not every vertex is
reachable from every other. (And if that seems unrealistically large,
consider Facebook, which has over a billion nodes.)
\index{degree (of a vertex)}
\item[degree.] A vertex's degree is simply the number of edges that connect
to it. \textsl{Virginia Beach} has degree 2, and \textsl{Fredericksburg} 3.
In the case of a directed graph, we sometimes distinguish between the
number of incoming arrows a vertex has (called its \textbf{in-degree}) and
the number of outgoing arrows (the \textbf{out-degree}). \textsl{Muhammad
Ali} had a higher out-degree (3) than in-degree (1) since he won most of
the time.
\index{cycles}
\item[cycle.] A cycle is a path that begins and ends at the same
vertex.\footnote{We'll also say that a cycle can't repeat any edges or
vertices along the way, so that it can't go back and forth repeatedly and
pointlessly between two adjacent nodes. Some mathematicians call this a
\textbf{simple cycle} to distinguish it from the more general
\textbf{cycle}, but we'll just say that no cycles can repeat like this.} In
Figure~\ref{weightedGraph}, \textsl{Richmond}-to-\textsl{Virginia
Beach}-to-\textsl{Fredericksburg}-to-\textsl{Richmond} is a cycle. Any
loop is a cycle all by itself. For directed graphs, the entire loop must
comprise edges in the ``forward" direction: no fair going backwards. In
Figure~\ref{directedGraph},
\textsl{Frazier}-to-\textsl{Ali}-to-\textsl{Foreman}-to-\textsl{Frazier}
is a cycle, as is the simpler
\textsl{Ali}-to-\textsl{Frazier}-to-\textsl{Ali}.
\index{DAGs (directed acyclic graphs)}
\item[DAG (directed, acyclic graph).] One common use of graphs is to
represent flows of dependencies, for instance the prerequisites that
different college courses have for one another. Another example is project
management workflows: the tasks needed to complete a project become
vertices, and then the dependencies they have on one another become edges.
The graph in Figure~\ref{DAG} shows the steps in making a batch of
brownies, and how these steps depend on each other. The eggs have to be
cracked before the ingredients can be mixed, and the oven has to be
preheated before baking, but the pan can be greased any old time, provided
that it's done before pouring the brown goop into it.
\begin{figure}[ht]
\centering
\resizebox{0.81\textwidth}{!}{
\begin{tikzpicture}
\node[ellipse,draw] (Mix) at (2,0) {mix ingredients};
\node[ellipse,draw] (Pour2Bowl) at (2,3) {pour brown stuff in bowl};
\node[ellipse,draw] (Crack) at (0,2) {crack two eggs};
\node[ellipse,draw] (Measure) at (4.5,2) {measure 2 tbsp oil};
\node[ellipse,draw] (Preheat) at (0,1) {preheat oven};
\node[ellipse,draw] (Bake) at (1,-1.3) {bake for 30 mins};
\node[ellipse,draw] (Grease) at (5.5,1) {grease pan};
\node[ellipse,draw] (Pour2Pan) at (5,-0.75) {pour into pan};
\node[ellipse,draw] (Cool) at (0,-2.5) {cool};
\node[ellipse,draw] (Enjoy) at (6,-2) {enjoy!};
\graph [multi] {
(Crack) ->[bend left] (Mix);
(Measure) ->[bend right] (Mix);
(Pour2Bowl) -> (Mix) -> (Pour2Pan) -> (Bake);
(Grease) ->[bend left] (Pour2Pan);
(Preheat) ->[bend right] (Bake) ->[bend right] (Cool) -> (Enjoy);
};
\end{tikzpicture}
}
\caption{A DAG.}
\label{DAG}
\end{figure}
\index{directed graphs}
\index{acyclic (graphs)}
A graph of dependencies like this must be both \textbf{directed} and
\textbf{acyclic}, or it wouldn't make sense. Directed, of course, means
that task X can require task Y to be completed before it, without the
reverse also being true. If they both depended on each other, we'd have an
infinite loop, and no brownies could ever get baked! Acyclic means that
\textit{no} kind of cycle can exist in the graph, even one that goes
through multiple vertices. Such a cycle would again result in an infinite
loop, making the project hopeless. Imagine if there were an arrow from
\textsl{bake for 30 mins} back to \textsl{grease pan} in Figure~\ref{DAG}.
Then, we'd have to grease the pan before pouring the goop into it, and we'd
have to pour the goop before baking, but we'd also have to bake before
greasing the pan! We'd be stuck right off the bat: there'd be no way to
complete any of those tasks since they'd all indirectly depend on each
other. A graph that is both directed and acyclic (and therefore free of
these problems) is sometimes called a \textbf{DAG} for short.
\end{description}
\subsection{Spatial positioning}
\index{spatial positioning}
\index{Ali, Muhammad}
\index{Liston, Sonny}
\index{Foreman, George}
\index{Frazier, Joe}
One important thing to understand about graphs is which aspects of a
diagram are relevant. Specifically, \textit{the spatial positioning of the
vertices doesn't matter.} In Figure~\ref{directedGraph} we drew
\textsl{Muhammad Ali} in the mid-upper left, and \textsl{Sonny Liston} in
the extreme upper right. But this was an arbitrary choice, and irrelevant.
More specifically, this isn't part of the information the diagram claims to
represent. We could have positioned the vertices differently, as in
Figure~\ref{directedGraphDiff}, and had \textit{the same graph}. In both
diagrams, there are the same vertices, and the same edges between them
(check me). Therefore, these are mathematically the same graph.
\begin{figure}[ht]
\centering
\resizebox{0.97\textwidth}{!}{
\begin{tikzpicture}[every node/.style={ellipse,draw}]
\node (SL) at (-0.5,0) {Sonny Liston};
\node (MA) at (4,0) {Muhammad Ali};
\node (GF) at (-5,0) {George Foreman};
\node (JF) at (0,-2) {Joe Frazier};
\graph [multi] {
(MA) -> (SL);
(MA) -> (JF) ->[bend right] (MA);
(GF) -> (JF);
(MA) ->[bend right] (GF);
};
\end{tikzpicture}
}
\caption{A different look to \textbf{the same graph as
Figure~\ref{directedGraph}}.}
\label{directedGraphDiff}
\end{figure}
\index{MapQuest}
\index{extensional}
This might not seem surprising for the prize fighter graph, but for graphs
like the MapQuest graph, which actually represent physical locations, it
can seem jarring. In Figure~\ref{weightedGraph} we could have drawn
\textsl{Richmond} north of \textsl{Fredericksburg}, and \textsl{Virginia
Beach} on the far west side of the diagram, and still had the same graph,
provided that all the nodes and links were the same. Just remember that the
spatial positioning is designed for human convenience, and isn't part of
the mathematical information. It's similar to how there's no order to the
elements of a set, even though when we specify a set extensionally, we have
to list them in \textit{some} order to avoid writing all the element names
on top of each other. On a graph diagram, we have to draw each vertex
\textit{somewhere}, but where we put it is simply aesthetic.
\subsection{Relationship to sets}
\index{sets}
\index{Harry Potter}
\index{endorelations}
We seem to have strayed far afield from sets with all this graph stuff. But
actually, there are some important connections to be made to those original
concepts. Recall the wizards set $A$ from chapter~\ref{chap:relations}
that we extended to contain \{~Harry, Ron, Hermione, Neville~\}. Now
consider the following endorelation on $A$:
\begin{center}
(Harry, Ron) \\
(Ron, Harry) \\
(Ron, Hermione) \\
(Ron, Neville) \\
(Hermione, Hermione) \\
(Neville, Harry)
\end{center}
This relation, and all it contains, is represented faithfully by the graph
in Figure~\ref{relationgraph}. The elements of $A$ are the vertices of
course, and each ordered pair of the relation is reflected in an edge of
the graph. Can you see how \textit{exactly} the same information is
represented by both forms?
\begin{figure}[ht]
\centering
\resizebox{0.9\textwidth}{!}{
\begin{tikzpicture}[every node/.style={ellipse,draw}]
\node (Hr) at (4,4) {Hermione};
\node (R) at (2,5) {Ron};
\node (N) at (7,5) {Neville};
\node (Ha) at (0,4) {Harry};
\graph [multi] {
(R) -> (Hr);
(R) -> (N) ->[bend left] (Ha);
(R) ->[bend right] (Ha);
(Ha) ->[bend right] (R);
};
\draw
(Hr) edge [->,loop above] (Hr);
\end{tikzpicture}
}
\caption{A graph depicting a endorelation.}
\label{relationgraph}
\end{figure}
\index{undirected graphs}
\index{symmetric (relation)}
Figure~\ref{relationgraph} is a directed graph, of course. What if it were
an undirected graph? The answer is that the corresponding relation would be
\textit{symmetric}. An undirected graph implies that if there's an edge
between two vertices, it goes ``both ways." This is really identical to
saying a relation is symmetric: if an $(x,y)$ is in the relation, then the
corresponding $(y,x)$ must also be. An example is
Figure~\ref{symrelationgraph}, which depicts the following symmetric
relation:
\begin{center}
(Harry, Ron) \\
(Ron, Harry) \\
(Ron, Hermione) \\
(Hermione, Ron) \\
(Harry, Harry) \\
(Neville, Neville)
\end{center}
\begin{figure}[ht]
\centering
\resizebox{0.9\textwidth}{!}{
\begin{tikzpicture}[every node/.style={ellipse,draw}]
\node (Ha) at (0,1) {Harry};
\node (R) at (4,0.5) {Ron};
\node (Hr) at (0,-1) {Hermione};
\node (N) at (4,-1) {Neville};
\graph [multi] {
(Ha) -- (R) -- (Hr);
};
\draw[every loop/.style={}]
(Ha) edge [in=175,out=235,loop] (Ha)
(N) edge [in=-25,out=20,loop] (N);
\end{tikzpicture}
}
\caption{A graph depicting a symmetric endorelation.}
\label{symrelationgraph}
\end{figure}
\index{loops (in a graph)}
Notice how the loops (edges from a node back to itself) in these diagrams
represent ordered pairs in which both elements are the same.
\index{partitions}
Another connection between graphs and sets has to do with partitions.
Figure~\ref{symrelationgraph} was not a connected graph: Neville couldn't
be reached from any of the other nodes. Now consider: isn't a graph like
this similar in some ways to a \textit{partition} of $A$ --- namely, this
one?
\begin{center}
\{~Harry, Ron, Hermione~\} and
\{~Neville~\}.
\end{center}
We've simply partitioned the elements of $A$ into the groups that are
connected. If you remove the edge between Harry and Ron in that graph, you
have:
\begin{center}
\{~Harry~\},
\{~Ron, Hermione~\}, and
\{~Neville~\}.
\end{center}
Then add one between Hermione and Neville, and now you have:
\begin{center}
\{~Harry~\} and
\{~Ron, Hermione, Neville~\}.
\end{center}
\index{connected (vertices/graphs)}
In other words, the ``connectedness" of a graph can be represented
precisely as a partition of the set of vertices. Each connected subset is
in its own group, and every vertex is in one and only one group: therefore,
these isolated groups are mutually exclusive and collectively exhaustive.
Cool.
\subsection{Graph traversal}
If you had a long list --- perhaps of phone numbers, names, or purchase
orders --- and you needed to go through and do something to each element of
the list --- dial all the numbers, scan the list for a certain name, add up
all the orders --- it'd be pretty obvious how to do it. You just start at
the top and work your way down. It might be tedious, but it's not
confusing.
\index{traversal}
Iterating through the elements like this is called \textbf{traversing} the
data structure. You want to make sure you encounter each element once (and
only once) so you can do whatever needs to be done with it. It's clear how
to traverse a list. But how to traverse a graph? There is no obvious
``first" or ``last" node, and each one is linked to potentially many
others. And as we've seen, the vertices might not even \textit{be} fully
connected, so a traversal path through all the nodes might not even exist.
There are two different ways of traversing a graph: breadth-first, and
depth-first. They provide different ways of exploring the nodes, and as a
side effect, each is able to discover whether the graph is connected or
not. Let's look at each in turn.
\subsubsection{Breadth-first traversal}
\index{BFT (breadth-first traversal)}
With \textbf{breadth-first traversal}, we begin at a starting vertex (it
doesn't matter which one) and explore the graph cautiously and delicately.
We probe equally deep in all directions, making sure we've looked a little
ways down each possible path before exploring each of those paths a little
further.
\index{queue}
\index{enqueueing}
\index{dequeueing}
\index{FIFO}
To do this, we use a very simple data structure called a \textbf{queue}. A
queue is simply a list of nodes that are waiting in line. (In Britain, I'm
told, instead of saying ``line up" at the sandwich shop, they say ``queue
up.") When we enter a node into the queue at the tail end, we call it
\textbf{enqueueing} the node, and when we remove one from the front, we
call it \textbf{dequeueing} the node. The nodes in the middle patiently
wait their turn to be dealt with, getting closer to the front every time
the front node is dequeued.
An example of this data structure in action is shown in Figure~\ref{queue}.
Note carefully that we always insert nodes at one end (on the right) and
remove them from the \textit{other} end (the left). This means that the
first item to be enqueued (in this case, the triangle) will be the first to
be dequeued. ``Calls will be answered in the order they were received."
This fact has given rise to another name for a queue: a ``\textbf{FIFO},"
which stands for ``first-in-first-out."
\afterpage{\clearpage}
\begin{figure}[ht]
\centering
\begin{tabular}{l l}
\textit{Start with an empty queue:} & $|$ \\
\hline
\textit{Enqueue a triangle, and we have:} & $|\triangle$ \\
\hline
\textit{Enqueue a star, and we have:} & $|\triangle \bigstar$ \\
\hline
\textit{Enqueue a heart, and we have:} & $|\triangle \bigstar \heartsuit$ \\
\hline
\textit{Dequeue the triangle, and we have:} & $|\bigstar \heartsuit$ \\
\hline
\textit{Enqueue a club, and we have:} & $|\bigstar \heartsuit \clubsuit$ \\
\hline
\textit{Dequeue the star, and we have:} & $|\heartsuit \clubsuit$ \\
\hline
\textit{Dequeue the heart, and we have:} & $|\clubsuit$ \\
\hline
\textit{Dequeue the club. We're empty again:} & $|$ \\
\end{tabular}
\caption{A queue in action. The vertical bar marks the ``front of the
line," and the elements are waiting to be dequeued in order from left to
right.}
\label{queue}
\end{figure}
Now here's how we use a queue to traverse a graph breadth-first. We're
going to start at a particular node, and put all of its adjacent nodes into
a queue. This makes them all safely ``wait in line" until we get around to
exploring them. Then, we repeatedly take the first node in line, do
whatever we need to do with it, and then put all of \textit{its} adjacent
nodes in line. We keep doing this until the queue is empty.
\index{marking (a node)}
Now it might have occurred to you that we can run into trouble if we
encounter the same node multiple times while we're traversing. This can
happen if the graph has a cycle: there will be more than one path to reach
some nodes, and we could get stuck in an infinite loop if we're not
careful. For this reason, we introduce the concept of \textbf{marking}
nodes. This is kind of like leaving a trail of breadcrumbs: if we're ever
about to explore a node, but find out it's marked, then we know we've
already been there, and it's pointless to search it again.
So there are two things we're going to do to nodes as we search:
\index{visiting (a node)}
\begin{itemize}
\item To \textbf{mark} a node means to remember that we've already
encountered it in the process of our search.
\item To \textbf{visit} a node means to actually do whatever it is we need
to do to the node (call the phone number, examine its name for a pattern
match, add the number to our total, whatever.)
\end{itemize}
\index{algorithm}
Now then. Breadth-first traversal (BFT) is an \textbf{algorithm}, which is
just a step-by-step, reliable procedure that's guaranteed to produce a
result. In this case, it's guaranteed to visit every node in the graph
that's reachable from the starting node, and not get stuck in any infinite
loops in the process. Here it is:
\index{BFT (breadth-first traversal)}
\vspace{.1in}
\begin{framed}
\textbf{Breadth-first traversal (BFT)}
\begin{compactenum}
\itemsep.1em
\item Choose a starting node.
\item Mark it and enqueue it on an empty queue.
\item While the queue is not empty, do these steps:
\begin{compactenum}
\item Dequeue the front node of the queue.
\item Visit it.
\item Mark and enqueue all of its \textit{unmarked} adjacent nodes (in
any order).
\end{compactenum}
\end{compactenum}
\end{framed}
\vspace{.2in}
\index{Facebook}
\index{queue}
Let's run this algorithm in action on a set of Facebook users.
Figure~\ref{BFT} depicts eleven users, and the friendships between them.
First, we choose Greg as the starting node (not for any particular reason,
just that we have to start somewhere). We mark him (in grey on the diagram)
and put him in the queue (the queue contents are listed at the bottom of
each frame, with the front of the queue on the left). Then, we begin our
loop. When we take Greg off the queue, we visit him (which means we ``do
whatever we need to do to Greg") and then mark and enqueue his adjacent
nodes Chuck and Izzy. It does not matter which order we put them into the
queue, just as it did not matter what node we started with. In pane 3,
Chuck has been dequeued, visited, and \textit{his} adjacent nodes put on
the queue. Only one node gets enqueued here --- Adrian --- because
obviously Greg has already been marked (and even visited, no less) and this
marking allows us to be smart and not re-enqueue him.
It's at this point that the ``breadth-first" feature becomes apparent.
We've just finished with Chuck, but instead of exploring Adrian next,
\textit{we resume with Izzy.} This is because she has been waiting
patiently on the queue, and her turn has come up. So we lay Adrian aside
(in the queue, of course) and visit Izzy, enqueueing her neighbor Elaine in
the process. \textit{Then}, we go back to Adrian. The process continues, in
``one step on the top path, one step on the bottom path" fashion, until our
two exploration paths actually meet each other on the back end. Visiting
Jackie causes us to enqueue Brittany, and then when we take Kim off the
queue, we do not re-enqueue Brittany because she has been marked and so we
know she's already being taken care of.
For space considerations, Figure~\ref{BFT} leaves off at this point, but of
course we would continue visiting nodes in the queue until the queue was
empty. As you can see, Hank and Danielle will not be visited at all in this
process: this is because apparently nobody they know knows anybody in the
Greg crowd, and so there's no way to reach them from Greg. This is what I
meant earlier by saying that as a side effect, the BFT algorithm tells us
whether the graph is connected or not. All we have to do is start
somewhere, run BFT, and then see whether any nodes have not been marked and
visited. If there are any, we can continue with another starting point, and
then repeat the process.
\begin{figure}[ht]
\centering
\begin{custommargins}{-1.4cm}{-1.8cm}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {1};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian -- Jackie -- Brittany --
Faith -- Kim -- Elaine --
Izzy -- Greg[marked] -- Chuck --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Greg};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {2};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian -- Jackie -- Brittany --
Faith -- Kim -- Elaine --
Izzy[marked] -- Greg[visited] -- Chuck[marked] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Chuck $\vert$ Izzy};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {3};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[marked] -- Jackie -- Brittany --
Faith -- Kim -- Elaine --
Izzy[marked] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Izzy $\vert$ Adrian};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {4};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[marked] -- Jackie -- Brittany --
Faith -- Kim -- Elaine[marked] --
Izzy[visited] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Adrian $\vert$ Elaine};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {5};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[visited] -- Jackie[marked] -- Brittany --
Faith -- Kim -- Elaine[marked] --
Izzy[visited] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Elaine $\vert$ Jackie};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {6};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[visited] -- Jackie[marked] -- Brittany --
Faith[marked] -- Kim[marked] -- Elaine[visited] --
Izzy[visited] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Jackie $\vert$ Kim $\vert$ Faith};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {7};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[visited] -- Jackie[visited] -- Brittany[marked] --
Faith[marked] -- Kim[marked] -- Elaine[visited] --
Izzy[visited] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Kim $\vert$ Faith $\vert$ Brittany};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {8};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[visited] -- Jackie[visited] -- Brittany[marked] --
Faith[marked] -- Kim[visited] -- Elaine[visited] --
Izzy[visited] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Faith $\vert$ Brittany};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {9};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian[visited] -- Jackie[visited] -- Brittany[marked] --
Faith[visited] -- Kim[visited] -- Elaine[visited] --
Izzy[visited] -- Greg[visited] -- Chuck[visited] --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12) {Queue: Brittany};
\end{tikzpicture}
}
}
\caption{The stages of breadth-first traversal. Marked nodes are grey, and
visited nodes are black. The order of visitation is: G, C, I, A, E, J, K,
F, B.}
\label{BFT}
\end{custommargins}
\end{figure}
\afterpage{\clearpage}
\subsubsection{Depth-first traversal (DFT)}
\index{DFT (depth-first traversal)}
With \textbf{depth-first traversal}, we explore the graph boldly and
recklessly. We choose the first direction we see, and plunge down it all
the way to its depths, before reluctantly backing out and trying the other
paths from the start.
\newcommand{\stackcell}[2][c]{%
\begin{tabular}[#1]{@{}c@{}}#2\end{tabular}}
\index{stack}
\index{top (of a stack)}
\index{push (on a stack)}
\index{pop (off a stack)}
The algorithm is almost identical to BFT, except that instead of a queue,
we use a \textbf{stack}. A stack is the same as a queue except that
instead of putting elements on one end and taking them off the other, you
\textit{add and remove to the same end.} This ``end" is called the
\textbf{top} of the stack. When we add an element to this end, we say we
\textbf{push} it on the stack, and when we remove the top element, we say
we \textbf{pop} it off.
\begin{figure}
\centering
\begin{tabular}{l l}
\textit{Start with an empty stack:} & $\underline{\quad}$ \\
\hline
\textit{Push a triangle, and we have:} & $\underline{\triangle}$ \\
\hline
\textit{Push a star, and we have:} & \stackcell{$\bigstar$ \\ $\underline{\triangle}$} \\
\hline
\textit{Push a heart, and we have:} & \stackcell{$\heartsuit$ \\ $\bigstar$ \\ $\underline{\triangle}$} \\
\hline
\textit{Pop the heart, and we have:} & \stackcell{$\bigstar$ \\ $\underline{\triangle}$} \\
\hline
\textit{Push a club, and we have:} & \stackcell{$\clubsuit$ \\ $\bigstar$ \\ $\underline{\triangle}$} \\
\hline
\textit{Pop the club, and we have:} & \stackcell{$\bigstar$ \\ $\underline{\triangle}$} \\
\hline
\textit{Pop the star, and we have:} & $\underline{\triangle}$ \\
\hline
\textit{Pop the triangle. We're empty again:} & $\underline{\quad}$
\end{tabular}
\caption{A stack in action. The horizontal bar marks the bottom of the
stack, and the elements are pushed and popped from the top.}
\label{stack}
\end{figure}
\index{LIFO}
You can think of a stack as...well, a stack, whether of books or cafeteria
trays or anything else. You can't get anything out of the middle of a
stack, but you can take items off and put more items on. Figure~\ref{stack}
has an example. The first item pushed is always the last one to be popped,
and the most recent one pushed is always ready to be popped back off, and
so a stack is also sometimes called a ``\textbf{LIFO}" (last-in-first-out.)
The depth-first traversal algorithm itself looks like d\'ej\`a vu all over
again. All you do is replace ``queue" with ``stack":
\index{DFT (depth-first traversal)}
\vspace{.1in}
\begin{samepage}
\begin{framed}
\textbf{Depth-first traversal (DFT)}
\begin{compactenum}
\item Choose a starting node.
\item Mark it and push it on an empty stack.
\item While the stack is not empty, do these steps:
\begin{compactenum}
\item Pop the top node off the stack.
\item Visit it.
\item Mark and push all of its \textit{unmarked} adjacent nodes (in
any order).
\end{compactenum}
\end{compactenum}
\end{framed}
\end{samepage}
\vspace{.2in}
\index{stack}
The algorithm in action is shown in Figure~\ref{DFT}. The stack really made
a difference! Instead of alternately exploring Chuck's and Izzy's paths, it
bullheadedly darts down Chuck's path as far as it can go, all the way to
hitting Izzy's back door. Only then does it back out and visit Izzy. This
is because the stack always pops off what it just pushed on, whereas
whatever got pushed first has to wait until everything else is done before
it gets its chance. That first couple of pushes was critical: if we had
pushed Chuck before Izzy at the very beginning, then we would have explored
\textit{Izzy's} entire world before arriving at Chuck's back door, instead
of the other way around. As it is, Izzy got put on the bottom, and so she
stayed on the bottom, which is inevitable with a stack.
DFT identifies disconnected graphs in the same way as BFT, and it similarly
avoids getting stuck in infinite loops when it encounters cycles. The only
difference is the order in which it visits the nodes.
\afterpage{\clearpage}
\begin{figure}[ht]
\centering
\begin{custommargins}{-1.4cm}{-1.8cm}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {1};
\graph [simple necklace layout, grow'=down, node sep=3em,nodes={draw,ellipse},
visited/.style={fill=black,text=white},
marked/.style={thick,fill=gray}]
{
Adrian -- Jackie -- Brittany --
Faith -- Kim -- Elaine --
Izzy -- Greg[marked] -- Chuck --
Adrian;
Brittany -- Kim;
Elaine -- {Faith, Jackie};
Hank -- Danielle;
};
\node[draw=none,align=center,font=\huge] at (0,-12.5) {
\begin{tabular}{r l}
\multirow{1}{*}{Stack:} & Greg
\end{tabular}
};
\end{tikzpicture}
}
}
\framebox{
\resizebox{0.32\textwidth}{!}{
\begin{tikzpicture}
\node[draw=none,align=left,font=\huge,thick] at (-5,0) {2};