You are on page 1of 39

Graphs

Definition of Graphs and Related Concepts Representation of Graphs The Graph Class Graph Traversal Graph Applications
CS 103 1

Definition of Graphs
A graph is a finite set of nodes with edges between nodes or!all"# a graph G is a str$ct$re %&#'( consisting of
) a finite set & called the set of nodes# and ) a set ' that is a s$bset of &*&+ That is# ' is a set of pairs of the for! %*#"( where * and " are nodes in &
CS 103 2

Examples of Graphs
&,-0#1#2#3#./ ',-%0#1(# %1#2(# %0#3(# %3#0(# %2#2(# %.#3(/
0 1 2 . 3 CS 103 0hen %*#"( is an edge# we sa" that * is adjacent to "# and " is adjacent from *+ 0 is ad1acent to 1+ 1 is not ad1acent to 0+ 2 is ad1acent fro! 1+ 3

A Real-life Example of a Graph


&,set of 2 people3 4ohn# 5ar"# 4oe# 6elen# To!# and 7a$l# of ages 12# 18# 12# 18# 13# and 13# respectivel"+ ' ,-%*#"( 9 if * is "o$nger than "/
5ar" 4ohn 6elen 4oe

To! CS 103

7a$l .

Intuition Behind Graphs


The nodes represent entities %s$ch as people# cities# co!p$ters# words# etc+( 'dges %*#"( represent relationships between entities * and "# s$ch as3
) ) ) ) ) ) ) :* loves "; :* hates "; :* is a friend of "; %note that this not necessaril" reciprocal( :* considers " a friend; :* is a child of "; :* is a half<sibling of "; :* is a f$ll<sibling of ";

=n those e*a!ples# each relationship is a different graph CS 103 8

Graph Representation
or graphs to be co!p$tationall" $sef$l# the" have to be convenientl" represented in progra!s There are two co!p$ter representations of graphs3
) Ad1acenc" !atri* representation ) Ad1acenc" lists representation
CS 103 2

Adjacency Matrix Representation


=n this representation# each graph of n nodes is represented b" an n * n !atri* A# that is# a two<di!ensional arra" A The nodes are %re(<labeled 1#2#?#n A@iA@1A , 1 if %i#1( is an edge A@iA@1A , 0 if %i#1( is not an edge

CS 103

>

Example of Adjacency Matrix


0 0 A, 0 1 0 1 0 0 0 0 0 1 1 0 0 1 0 0 0 . 0 0 0 0 0 0 1 2 . 3

CS 103

Another Example of Adj Matrix


Re<label the nodes with n$!erical labels
0 0 A, 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 5ar" 0 0 0 1 4ohn 2 1 0 To! . 0 6elen 1 4oe 3

7a$l 8

CS 103

!ros and "ons of Adjacency Matrices


7ros3
) Si!ple to i!ple!ent ) 'as" and fast to tell if a pair %i#1( is an edge3 si!pl" checD if A@iA@1A is 1 or 0

Cons3
) Eo !atter how few edges the graph has# the !atri* taDes F%n2( in !e!or"
CS 103 10

Adjacency #ists Representation


A graph of n nodes is represented b" a one< di!ensional arra" G of linDed lists# where
) G@iA is the linDed list containing all the nodes ad1acent fro! node i+ ) The nodes in the list G@iA are in no partic$lar order

CS 103

11

Example of #in$ed Representation


G@0A3 e!pt" G@1A3 e!pt" G@2A3 0# 1# .# 8 G@3A3 0# 1# .# 8 G@.A3 0# 1 G@8A3 0# 1
5ar" 0 4ohn 2 To! . 7a$l 8 6elen 1 4oe 3

CS 103

12

!ros and "ons of Adjacency #ists


7ros3
) Saves on space %!e!or"(3 the representation taDes as !an" !e!or" words as there are nodes and edge+

Cons3
) =t can taDe $p to F%n( ti!e to deter!ine if a pair of nodes %i#1( is an edge3 one wo$ld have to search the linDed list G@iA# which taDes ti!e proportional to the length of G@iA+
CS 103 13

%he Graph "lass


class Graph pu&lic3 typedef int datat"peH typedef datat"pe I datat"peptrH Graph% int n,0(H JJ creates a graph of n nodes and no edges &ool is'dge% int i# int 1(H 'oid set'dge% int i# int 1# datat"pe *(H int getE$!berFfEodes%(-return n$!berFfEodesH/H pri'ate3 datat"peptr IpH JJa 2<D arra"# i+e+# an ad1acenc" !atri* int n$!berFfEodesH /H CS 103 1.

Graph "lass Implementation


Graph33Graph% int n(bool Graph33is'dge%int i# int 1(assert%nK,0(H assert%iK,0 NN 1K,0(H n$!berFfEodes,nH ret$rn p@iA@1A O, 0H if %n,,0( p()*##H /H elsep , ne+ datat"peptr@nAH void Graph3Hset'dge%int i# for %int i,0HiLnHiMM(int 1# datat"pe *(p@iA , ne+ datat"pe@nAH assert%iK,0 NN 1K,0(H for %int 1,0H1LnH1MM( p@iA@1A,*H p@iA@1A,0H /H / / /H CS 103 18

Directed 's *ndirected Graphs


=f the directions of the edges !atter# then we show the edge directions# and the graph is called a directed graph %or a digraph( The previo$s two e*a!ples are digraphs =f the relationships represented b" the edges are s"!!etric %s$ch as %*#"( is edge if and onl" if * is a sibling of "(# then we donPt show the directions of the edges# and the graph is called an undirected graph+
CS 103 12

Examples of *ndirected Graphs


&,set of 2 people3 4ohn# 5ar"# 4oe# 6elen# To!# and 7a$l# where the first . are siblings# and the last two are siblings ' ,-%*#"( 9 * and " are siblings/
5ar" 4ohn 6elen if %*#"( is an edge3 we sa" that * is 4oe adjacent to "# N " ad1acent to *+ 0e also sa" that * and " are 7a$l neighbors 1>

To! CS 103

Representations of *ndirected Graphs


The sa!e two representations for directed graphs can be $sed for $ndirected graphs Ad1acenc" !atri* A3
) A@iA@1A,1 if %i#1( is an edgeH 0 otherwise

Ad1acenc" Gists3
) G@iA is the linDed list containing all the neighbors of i
CS 103 1B

Example of Representations
GinDed Gists3 G@0A3 1# 2# 3 G@1A3 0# 2# 3 G@2A3 0# 1# 3 G@3A3 0# 1# 2 G@.A3 8 G@8A3 .
5ar" 0 4ohn 2 To! . Ad1acenc" 5atri*3 0 1 1 1 0 0 1 0 1 1 0 0 A, 1 1 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 CS 103 1C 6elen 1 4oe 3 7a$l 8

Definition of ,ome Graph Related "oncepts Get G be a directed graph


) The indegree of a node * in G is the n$!ber of edges co!ing to * ) The outdegree of * is the n$!ber of edges leaving *+

Get G be an $ndirected graph


) The degree of a node * is the n$!ber of edges that have * as one of their end nodes ) The neighbors of * are the nodes ad1acent to *
CS 103 20

%hin-s for .ou %o Do


Add a !e!ber f$nction to the class graph# called get=ndegree% int *(# which ret$rns the indegree of node * Add a !e!ber f$nction to the class graph# called getF$tdegree% int *(# which ret$rns the o$tdegree of node *

CS 103

21

!aths
A path in a graph G is a seQ$ence of nodes *1# *2# ?#*D# s$ch that there is an edge fro! each node the ne*t one in the seQ$ence or e*a!ple# in the first e*a!ple graph# the seQ$ence 3# 0# 1# 2 is a path# b$t the seQ$ence 0# 3# . is not a path beca$se %0#3( is not an edge =n the :sibling<of; graph# the seQ$ence /ohn0

Mary0 /oe0 1elen is a path# b$t the seQ$ence 1elen0 %om0 !aul is not a path
CS 103 22

Graph "onnecti'ity
An $ndirected graph is said to be connected if there is a path between ever" pair of nodes+ Ftherwise# the graph is disconnected =nfor!all"# an $ndirected graph is connected if it hangs in one piece

Disconnected CS 103

Connected 23

"onnected "omponents
=f an $ndirected graph is not connected# then each :piece; is called a connected co!ponent+
) A piece in itself is connected# b$t if "o$ bring an" other node to it fro! the graph# it is no longer connected

=f the graph is connected# then the whole graph is one single connected co!ponent Ff =nterest3 Given an" $ndirected graph G#
) =s G connectedR ) =f not# find its connected co!ponents+

CS 103

2.

Graph %ra'ersal %echni2ues


The previo$s connectivit" proble!# as well as !an" other graph proble!s# can be solved $sing graph traversal techniQ$es There are two standard graph traversal techniQ$es3
) Depth-First Search %D S( ) Breadth-First Search %S S(
CS 103 28

Graph %ra'ersal 3"ontd 4


=n both D S and S S# the nodes of the $ndirected graph are visited in a s"ste!atic !anner so that ever" node is visited e*actl" one+ Soth S S and D S give rise to a tree3
) 0hen a node * is visited# it is labeled as visited# and it is added to the tree ) =f the traversal got to node * fro! node "# " is viewed as the parent of *# and * a child of "
CS 103 22

Depth-5irst ,earch
D S follows the following r$les3
1+ Select an $nvisited node *# visit it# and treat as the c$rrent node 2+ ind an $nvisited neighbor of the c$rrent node# visit it# and !aDe it the new c$rrent nodeH 3+ =f the c$rrent node has no $nvisited neighbors# bacDtracD to the its parent# and !aDe that parent the new c$rrent nodeH .+ Repeat steps 3 and . $ntil no !ore nodes can be visited+ 8+ =f there are still $nvisited nodes# repeat fro! step 1+ CS 103 2>

Illustration of D5,
0 0 . 2 8 2 > B D S Tree C 11 10 1 C 10 11 2 Graph G 8 > B 2 1 .

CS 103

2B

Implementation of D5,
Fbservations3
) the last node visited is the first node fro! which to proceed+ ) Also# the bacDtracDing proceeds on the basis of Tlast visited# first to bacDtracD tooT+ ) This s$ggests that a stacD is the proper data str$ct$re to re!e!ber the c$rrent node and how to bacDtracD+
CS 103 2C

=ll$strate D S with a StacD


0e will redo the D S on the previo$s graph# b$t this ti!e with stacDs =n Class

CS 103

30

D5, 3!seudo "ode4


D S%inp$t3 Graph G( StacD SH =nteger *# tH while %G has an $nvisited node *(visit%*(H p$sh%*#S(H while %S is not e!pt"(t 3, peeD%S(H if %t has an $nvisited neighbor "(visit%"(H p$sh%"#S(H / else pop%S(H / / / CS 103 31

"66 "ode for D5,


int I dfs%Graph G(- JJ ret$rns a parent arra" representing the D S tree int n,G+getE$!berFfEodes%(H int I parent , ne+ int@nAH StacD S%n(H &ool visited@nAH for % int i,0H iLnH iMM( visited@iA,falseH int *,0HJJ begin D S fro! node 0 int n$!FfConnectedCo!ponents,0H +hile %*Ln(JJ begin a new D S fro! * n$!FfConnectedCo!ponentsMMH visited@*A,trueH S+p$sh%*(H parent@*A , <1H JJ * is root +hile%OS+is'!pt"%(( JJ traverse the c$rrent piece JJ insert here the "ellow bo* fro! the ne*t slide *, getEe*tUnvisited%visited#n#*(H / co$tLL:Graph has :LL n$!FfConnectedCo!ponentsLL : connected co!ponentsVn;H return pH /

CS 103

32

JJ 7$t this before dfs%?( JJ ret$rns the left!ost $nvisited int t,S+peeD% (H int ",getEe*tUnvisitedEeighbor% JJ neighbor of node t+ =f none JJ re!ains# ret$rns n+ t#G#visited#n(H int getEe*tUnvisitedEeighbor%int t# if %"Ln(graph G# &ool visited@A#int n(visited@"A,trueH for %int 1,0H1LnH1MM( S+p$sh%"(H if %G+is'dge%t#1( NN Ovisited@1A( parent@"A,tH return 1H / JJ if no $nvisited neighbors left3 else S+pop% (H return nH / / JJ7$t this before dfs%?(+ This ret$rns the ne*t $nvisited node# or n otherwise int -et)ext*n'isited3&ool visited@A#int n# int last&isited(int 1,last&isitedM1H +hile %visited@1A NN 1Ln( 1MMH return 1H / -

CS 103

33

Breadth-5irst ,earch
S S follows the following r$les3
1+ Select an $nvisited node *# visit it# have it be the root in a S S tree being for!ed+ =ts level is called the c$rrent level+ 2+ ro! each node W in the c$rrent level# in the order in which the level nodes were visited# visit all the $nvisited neighbors of W+ The newl" visited nodes fro! this level for! a new level that beco!es the ne*t c$rrent level+ 3+ Repeat step 2 $ntil no !ore nodes can be visited+ .+ =f there are still $nvisited nodes# repeat fro! Step 1+ CS 103 3.

Illustration of B5,
0 0 1 8 2 > B 2 C 11 . 10 C 10 11 Graph G 2 8 > B 2 1 .

S S Tree

CS 103

38

Implementation of D5,
Fbservations3
) the first node visited in each level is the first node fro! which to proceed to visit new nodes+

This s$ggests that a Q$e$e is the proper data str$ct$re to re!e!ber the order of the steps+

CS 103

32

=ll$strate S S with a X$e$e


0e will redo the S S on the previo$s graph# b$t this ti!e with Q$e$es =n Class

CS 103

3>

B5, 3!seudo "ode4


S S%inp$t3 graph G( X$e$e XH =nteger *# W# "H while %G has an $nvisited node *( visit%*(H 'nQ$e$e%*#X(H while %X is not e!pt"(W 3, DeQ$e$e%X(H for all %$nvisited neighbor " of W(visit%"(H 'nQ$e$e%"#X(H / / / / CS 103 3B

%hin-s for you to Do


Give a CMM i!ple!entation of S S# $sing the pse$do code as "o$r g$ide Use S S as a wa" to deter!ine of the inp$t graph G is connected# and if not# to o$tp$t the n$!ber of connected co!ponents 5odif" S S so that the level of each node in the S S tree is co!p$ted+ Give another class for graph# this ti!e $sing a linDed lists representation+
CS 103 3C

You might also like