computing fundamentals 2 lecture 2 a theory of graphs lecturer: patrick browne lecture room k320,...

Post on 25-Dec-2015

219 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Computing Fundamentals 2Lecture 2

A theory of Graphs

Lecturer: Patrick Brownehttp://www.comp.dit.ie/pbrowne/Lecture Room K320, Labs A117

Based on Chapter 19. A Logical approach to Discrete Math By David Gries and Fred B. Schneider

A Theory of Graphs

• In this lecture we look at:

• Graph Morphisms

• Hamilton Circuits

• Planar Graphs

• Shortest Path

Similar Graphs

• The two graphs below look different but are structurally the ‘same’.

d

c

b

a3(e)

5(d)

2(c)

1(a)

e4(b)

Graph Morphisms

• The two graphs below look different but are structurally the ‘same’.

d

c

b

a3(e)

5(d)

2(c)

1(a)

e4(b)

• They are the ‘same’ up to the renaming of the vertices. These graphs are isomorphic.

f.a

f.b

f.c

f.d

f.e

Graph Isomorphism•Given two graphs G and G’ with vertices V and V’. The graphs are isomorphic if there exists a 1-to-1 function f:V->V’ such that:

•An isomorphism f “preserves edges” thus preserving properties of graphs that depend on edges e.g. cycles and degrees are preserved.

Isomorphism Invariant

• An isomorphic invariant for simple graphs is the existence of a simple circuit of length k ,where k is an integer > 2. Example: G1 and G2 are isomorphic since we have the invariants, similarity in degree of nodes, number of edges, length of circuits.

G1 G2

Graph Isomorphism

• Sometimes it is easy to check whether two graphs are not isomorphic. The left graph below has two vertices of degree 3 while the right one has none.

• It is much harder to prove that two graphs are isomorphic. The computation is time is exponential wrt. the number of vertices .

Complexity O notation

• Big-O notation can be used to express complexity of an

algorithm or computation. For a problem of size N:• a constant-time is "order 1": O(1)

• a linear-time is "order N": O(N)

• a quadratic-time is "order N squared": O(N2)

• a exponential-time is "order constant to the ": O(CN)

• As the size of the problem increases linearly, the time to

solve the problem increases exponentially (O(C to the

power N)). The shortest route A to A, which visits all points

and returns to point A. The travelling salesman problem, it

takes exponential time.

Homeomorphic Graphs

• Two graphs are homeomorphic if they can both be obtained from the same graph by inserting or removing vertices of degree 2.

1 2 3b

cd

e

• Adding b to 1 gives 2• Adding c,d,e, to 1 gives 3• Hence 2 and 3 are homeomorphic because they were

obtained from 1 by adding vertices of degree 2.

Recall: Euler and Hamiltonian Cycles

• An Euler cycle is a cycle in a graph that includes each edge exactly once. Examples: Designing and optimizing routes refuse trucks, snow ploughs, or postmen. In all of these applications, every edge in a graph must be traversed at least once.

• A Hamiltonian cycle is a cycle in a graph G that contains each vertex exactly once except for the starting and ending vertex that appears twice. Examples: travelling sales man who wishes to visit every city and also minimize his route to each city and return to his home city.

Hamilton Circuit

• A Hamilton path of a graph or digraph is a path that contains each vertex exactly once, except that the end vertices may be the same.

• A Hamilton circuit (or cycle) is a Hamilton path that is a cycle.

• Contrast this with an Euler circuit which contains each edge exactly once.

Hamilton Path and Circuit

• G has Hamilton path but no Hamilton circuit (or cycle).

Hamiltonian cyclesTraveling salesperson problem (TSP)

– To visit every vertex of a graph G only once by a simple cycle.

– Such a cycle is called a Hamilton cycle.

– If a connected graph G has a Hamilton cycle, G is called a Hamiltonian graph.

Hints for finding Hamilton Circuits

• If G has a HC, then deg.v >= 2 for all v on HC.

• If deg.v = 2 then both edges incident on v are in HC.

• If deg.v > 2 and two of the edges incident on v are in a HC, then the other edges incident on v are not in that HC.

• A complete digraph (v>2) has a Hamilton Path.

Hints for finding Hamilton Circuits

Hints for finding Hamilton Circuits

• The number of different Hamiltonian cycles in a complete undirected graph on n vertices is (n − 1)!/2 and in a complete directed graph on n vertices is (n − 1)!

b

a c

d e f g h

i j

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g,c

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g,c,h

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g,c,h,j

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g,c,h,j,f

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g,c,h,j,f,i

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Solution: d,a,e,b,g,c,h,j,f,i,d

Hamilton Circuit

• Find a Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the same graph G.

•Note that while verticies a and b were on previous Hamilton circuit the edge <a.b> was not.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

b

a c

d e f g h

i j

Hamilton Circuit

• Find another Hamilton circuit in the G.

Is HC unique?

• There are graphs with unique Hamiltonian

cycles:

Two classes of Hamiltonian Paths

1. A complete digraph (v>2) has a Hamiltonian path.

2. Let G be an undirected graph of n vertices*. If deg.b + deg.c ≥ n-1 for each pair of vertices b,c then G has a Hamiltonian path. Note direction of implication

b,c(deg.b + deg.c ≥ n-1) HPIf 2 does not hold we do not know about HP

*Note: every vertex must be on the Hamilton path

Showing there is no HC• The HC itself must contain exactly two edges

incident on each vertex. Hence each vertex v on the HC has degree(v)= 2.

• In any graph sum(degree(v))=2*|E|. In the HC case |V|*2=2*|E|, which reduces to |V|=|E|. Since G (below) has 5 vertices then the HC should have 5 edges. The graph has 6 edges, but can we form a HC without one of the edges? v1

v4

v3

v2

v5 Graph Ge2

e1

e3

e4e6 e5

Showing there is no HC

• Looking just at the HC in G, each vertex on the HC has degree two. Eliminate edges incident on vertices with degree greater than two.

• The edges <v4,v5> and <v2, v5> are incident on v4, v3, v5.

• If we eliminate <v4,v5> and <v2, v5> are left with only 4 edges not enough to complete a HC, because |V|=|E| should hold.

v1

v4

v3

v2

v5

Graph G

v1

v4

v3

v5

v2

Showing there is no HC

• Using this method we must avoid double counting. We must not count an eliminated edges more than once. In this case, when we eliminated one edge incident on v2 and one edge incident on v4 these edges are distinct, and hence our argument is valid.

v1

v4

v3

v2

v5

Graph G; valid reasoning

Incorrect claim: G has no HC.In G2 there are 5 vertices, hence HC must

have 5 edges. Following the method from previous slide we eliminate two edges incident at v5 and one edge incident at each v1,v2,v3, and v4, leaving just 2 edges, hence no HC. This is incorrect reasoning, because the red edges are counted twice.

When we eliminate 2 edges incident on v5 (which we must) we also eliminate edges incident on another vertices. Then we only need to remove 1 other edge. Now we have 5 edges and 5 vertices, hence a HC –correct reasoning.

v1

v4

v3

v2v5

v1

v4

v3

v5

v2

G2

Showing there is no HC

• How could we show that there is no HC in the graph below?

a c

g kji

b

h

l

m

d

e

f

Showing there is no HC

• Suppose HC=H, then edges <a,b>, <a,g>, <b,c>,<c,k> must be in H, since each of these has at least one vertex with degree two.

• Thus <b,d> and <b,f> are not in H since then Deg(b) >2 would be true.

a c

g kji

b

h

l

m

de

f

Showing there is no HC• Therefore edges <g,d>, <d,e>, <e,f>, <f, k> are in H (because d and f are now degree 2).

• The edges now form a cycle C. Adding additional edges to C will give some vertex in H a degree greater that 2. This is a contradiction, showing G does not have HC.

a c

g kji

b

h

l

m

de

f

Hamilton Cycles & Paths

Hamilton Cycles in K4

The number of Hamilton circuits in KN is

(N - 1) × (N - 2) × ... × 3 × 2 × 1 = (N - 1)!

Hamilton Cycles in K4

Summary of Euler and Hamilton cycles

• A Euler cycle is a cycle in a graph that includes all of the edges and all of the vertices in that cycle.

• A Hamilton cycle is a cycle in a graph G the contains each vertex exactly once except for the starting and ending vertex that appears twice.

• Recall:

• A path is a sequence of vertices and edges but with no edge traversed more than once

• A path with at least one edge and with the first and last vertices the same is called a cycle.

Summary of Euler and Hamilton cycles

• Whether a graph does or does not have a Hamilton cycle tells you nothing about whether it has an Euler cycle , and vice versa. The same is true for Hamilton and Euler paths (rather than cycles).

Summary of Euler and Hamilton cycles

• G has a Euler cycle but no Hamilton cycle

A

B

B

C

D

E

F

Summary of Euler and Hamilton cycles

Test for Euler cycle

• If a graph G has an Euler cycle, then G is connected and every vertex has even degree.

• If G is a connected graph and every vertex has even degree, then G has a Euler cycle.

This graph G does not have a Euler cycle, since there are vertices of odd degree, yet G has a Hamiltonian cycle of:

(a,b,c,d,e,f,g,a).

a b

cdf

g

Unlike Euler cycles, no easily verified necessary and sufficient conditions are known to exist for a Hamilton cycle in a graph

edge(a,b), edge(a,f), edge(a,g), edge(a,e), edge(b,f), edge(b,d), edge(b,c), edge(c,d), edge(c,e), edge(e,d), edge(e,f), edge(e,g), edge(g,f)

e

This graph has a Euler cycle but no Hamiltonian cycle.

Cycle or Path?If a graph has a Hamilton cycle does it have to have a Hamilton path? Answer Yes: HC implies HP. If <v1…vn-1,vn>, with v1=vn, is a Hamilton cycle then <v1…vn-1>, is a Hamilton path

. A Hamiltonian cycle exists on a complete graph

• Recall, a Hamilton cycle is a cycle in a graph G the contains each vertex exactly once except for the starting and ending vertex that appears twice.

• Recall, a complete graph on n vertices, Kn, is the simple graph (no loops or parallel edges) with n vertices in which there is an edge between every pair of distinct vertices.

• Since there is an edge between every pair of vertices and this edge may be traversed in either direction, it follows that any permutation of vertices is a Hamilton path.

A Hamilton cycle exists on a complete graph.

• Moreover, a Hamilton cycle is obtained by including the edge from the final to the initial vertex of such a path.

• So in summary

• Every complete graph has a Hamilton path and a Hamilton cycle.

Hamiltonian cycles can take a long time to compute!

• For a general graph, every known algorithm for finding Hamiltonian cycles requires factorial time in the worst case. For a complete undirected graph with n vertices, there are a possible (n-1)!/2 essentially different Hamiltonian cycles. The number of addition operations required to obtain the lengths of these cycles is O(n!). For example for n=12 it will take 5 seconds to perform the computation, for n=50 it will take 1049 years (assuming 108 (100,000,000, or 100 million) additions per second). For this reason, methods that produce near-minimum-length cycles are often used.

Planar Graphs

• A graph is called planar if it can be drawn

on the plane in a way that no two of its

edges cross each other

Planar graphs

A graph is planar if it can be drawn in the plane without crossing edges

Planar graphs K4 can be drawn with no edges crossing.

A planar graph the points in the plane into regions or faces. Any planar embedding of a given graph has the same numbers of faces.

Planar graphs Two points (not vertices) are in the

same region iff it is possible to draw an edge (curved) between them without touching an edge of the region.

Each interior region (e.g. C and B) is characterized by a cycle that forms its boundary. The exterior region (D) contains all the points not bounded by some cycle.

Theorem : Euler's planar graph theorem

For all connected planar graph or multigraph: v – e + r = 2

numberof vertices

numberof edges

numberof regions or faces

Euler’s Planar Graph TheoremEuler’s Characteristic

Planar implies v – e + r = 2

Recall the Handshaking Theorem

Theorem: Let G=(V,E) be an undirected graph. Then

Example of Handshaking Theorem

• Draw a graph with 4 edges and 4 vertices , having

degrees 1,2,3,4.

• Solution: No such graph exists. The sum of the

degrees of all the vertices should be equal to twice

the number of edges. Half of the sum of the degrees

is 5, which is not equal to actual number of edges

required in the question (4).

• (1+2+3+4)/2 = 5, 5 =/= 4.

Planar Graphs

Example where Euler’s theorem holds

A planar graph divides the planeinto several regions (faces), one of them is the infinite externalregion.

• v=4,e=5,r=3,• v-e+r=2•4-5+3=2

Planar graphsA graph (or multigraph) G is called planar if G can be drawn in the plane with its edges intersecting only at vertices of G, such a drawing of G is called an embedding of G in the plane. Used in VLSI design, where overlapping edges requires extra layers, wires cannot overlap on the circuit board. Representation examples: K1,K2,K3,K4 are planar, Kn for n>4 are non-planar

Edges in series

Edges in series:

• If vV(G) has degree 2 and there are edges (v, v1), (v, v2) with v1 v2,

• we say the edges (v, v1) and (v, v2) are in series.

Series reduction• A series reduction consists

of deleting the vertex v V(G) and replacing the edges (v,v1) and (v,v2) by the edge (v1,v2)

• The new graph G’ has one vertex and one edge less than G and is said to be obtained from G by series reduction

Homeomorphic graphs

• Two graphs G and G’ are said to be homeomorphic if G’ is obtained from G by a sequence of series reductions.– By convention, G is said to be obtainable from

itself by a series reduction, i.e. G is homeomorphic to itself.

• Define a relation R on graphs: GRG’ if G and G’ are homeomorphic.

• R is an equivalence relation on the set of all graphs.

Kuratowski’s theorem

• G is a planar graph if and only if G does not contain a sub-graph homeomorphic to either K 5 or K 3,3

Utility Problem(again)

• There are three houses and three utility companies--say, gas,

electric, and water--and asks if each utility can be connected to

each house without having any of the gas-water-electric lines

pass over any other. This is equivalent to the equation "Can a

planar graph be constructed from each of three nodes

('houses') to each of three other nodes ('utilities')?" No such

planar graph exists.

Not planarHere is an example of a graph which doesn't have K5 or K3,3 as its subgraph. However, it has a subgraph that is homeomorphic to K3,3 (replace red lines with yellow line) and is therefore not planar.

A finite graph is planar if and only if it does not contain a subgraph that is homeomorphic to K5 or K3,3.

Euler’s formula• We can test if a graph is non-planar, but there is

no simple check for planarity. If v is the number of vertices (at least 3) and e is the number of edges, then (e 3v−6 ) is a necessary (but not sufficient) condition for planarity.

• That is, every connected planar graph satisfies (e 3v−6 ), but there are graphs that satisfy that constraint which are not planar.

• Planar => (e 3v−6 )

• not(e 3v−6 ) => not(Planar)

Euler’s formula

• Euler’s formula forms the basis of two theorems

that provide conditions for non-planarity :

• Theorem 1: If v ≥ 3 then e ≤ 3v − 6;

• Theorem 2: If v > 3 and there are no cycles of

length 3, then e ≤ 2v − 4.

• If either of these theorems fail to hold then the

graph is not planar.

Euler’s formula

• The graph K3,3 has 6 vertices, 9 edges,

and no cycles of length 3. Using Theorem 2 we get the implication.

• If (v > 3) and not(cycle(length(3)) then e ≤ 2v − 4.

• RHS = 9 ≤ (2*6) – 4 = 9 ≤ 8 = false

• The LHS of the implication is true, but RHS is false (T=>F is false1) .

• By theorem 2, K3,3 cannot be planar.

Satisfies Euler’s formula but not

planar.• By itself, Euler's formula does not provide us

with a tool for showing that some graphs are not

planar, because it refers to the set of regions in

a potential planar drawing of the graph.

• There are graphs that satisfy Euler’s formula but

are not planar

Planar Example• Euler Characteristic: r = e – v + 2, (4 = 8 – 6 + 2) (true)

• r = regions or faces

f D

d c

ba

e

C

A

B

• For all planar graphs (e 3v − 6), 8 > 12 = true • Note, this test cannot be used to prove

planarity.

Planar Example

Planar embedding for K2,2, K2,3 , & K2,4

Kuratowski’s theorem• Kuratowski’s Theorem: A graph is non-planar if and only if it contains a

subgraph homeomorephic to K3,3 or K5 . • The graph G on the left contain K,3,3. Deleting vertex h and its incident

edges gives the middle graph. We can replace c-g-f by c-f (homeomorphic graphs). Then the graph on the left is K3,3 therefore G contains a subgraph that is homeomorphic to K3,3. (Page 447, course text)

Theorem on vertices, edges,

regions• If the planar representation divides the

plane then, v – e + r = 2

• If v≥3 then, e ≤ 3v – 6

• If v≥3 and there are no cycles of length 3

then, e ≤ 2v – 4

Proof that K5 is not planar

• A planar graph is a graph that can be drawn on the plane in such a way that its edges intersect only at their endpoints.

• Solution: K5 has 5 vertices each with degree 4, so by

the handshaking theorem it has 5*4/2 = 10 edges. By theorem 1 of Euler’s formula, every connected planar graph must satisfy E ≤ 3V – 6, gives 10 ≤ 3*5 – 6 or 10 ≤ 9, which is false. So K5 cannot be a connected planar

graph.

• Or more simply, if K5 was planar then m ≤ 15 - 6 = 9, but

this is not the case because m = 10

Trees

• A tree is a loop-free connected graph that

contains no cycles.

• Each pair of vertices of a tree is connected

by a unique simple path. A Tree Not a tree

Trees

• A tree with at least two vertices has at

least two vertices of degree 1.

• For every tree <V,E>, #V = 1 + #E.

A Tree Not a tree

Trees

• Let G=<V,E> be a loop free graph, then the following are equivalent statements:

• G is a tree

• G is connected and the removal of any edge yields two trees

• G contains no cycles and #V = 1 + #E

• G is connected and #V = 1 + #E

• G has no cycles and adding one edge introduces one cycle

Trees

• Every tree has the following properties:

• Any connected subgraph is a tree.

• There is a unique simple path between every pair of vertices.

• Adding an edge between two vertices creates a cycle.

• Removing any edge disconnects the graph.

• If it has at least two vertices, then it has at least two leaves.

• The number of vertices is one larger than the number of edges.

Trees : File Directories

• A graph may contain a cycle. There is the possibility that deleting a sub-directory could delete the directory from which the delete command was issued. A tree structure prohibits the sharing of files, but an acyclic graph would permit file sharing

• A tree structure prohibits the sharing of files or directories. Acyclic graphs allow directories to have shared subdirectories and files, but deletion of file is difficult.

Trees : File Directories

• Acyclic graphs provide an extension of tree-structured directories. It is possible for two directories to contain the same file or subdirectory.

A spanning tree of a graph contains the minimum number of edges to keep the graph connected.

A spanning tree of a connected graph is a tree that is a sub-graph and that contains all the vertices of the graph. In the middle below is a graph; on either side of it is a spanning tree of that graph.

Spanning Tree Example

A spanning tree of a graph contains the minimum number of edges to keep the graph connected.

An algorithm used to construct a spanning tree is non-deterministic in two ways: 1) the choice of vertex u is arbitrary, 2) the choice of the edge incident on u to add to the tree is arbitrary.

Spanning Tree Example

The edges are traversed in the order specified by the numbers above.

A spanning tree of a graph contains the minimum number of edges to keep the graph connected.

We can limit the choice of vertex by either breath first search (BFS) or depth first search (DFS).

BFS Original Graph DFS

Spanning Tree Example

1

2

3

45

76

1 2

3 45

6

7

Shortest path

V the set of vertices in the graph, xpaths are next step

F set of vertices whose shortest-path lengths remain to be calculated

V – F (permanent labels) set of vertices whose shortest-path lengths have been calculated

Each iteration moves one vertex from F to (V – F)

Invariant : PF : (V – F) b ∊ (V – F)

Permanent Labels Temporary LabelsPermanent Labels Temporary Labels

Dijkstra’s Shortest Path Algorithm

• Dijkstra’s algorithm for finding the shortest from a to v, involves assigning labels to vertices. Let L(v) denote the label of vertex v. At any point, some vertices have temporary labels and the rest have permanent labels, these are shown in red in the following slides. We let T denote the set of vertices having temporary labels.

Dijkstra’s Shortest Path Algorithm

• If L(v) is a permanent label of v the L(v) is the shortest path to v.

• Initially all vertices have temporary labels.

• Each iteration of the algorithm changes the status of one of the labels from temporary to permanent .

• Terminate when z is not an element of T.

Dijkstra’s Shortest Path Algorithm

• Initialize:• L(a):= 0 • all vn (except a) are labelled .• T := set of all temporary verticeswhile z ∊ T [ choose v ∊ T with min L(v) T := T – {v} for each x ∊ T adjacent to v [ L(x) := min{(L(x), L(v) + w(v,x)}]]

Where w(v,x) is distance from v to x.

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Example Graph G(*)

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Initialized Graph G(*)

0

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

After First Iteration Graph G(*)

2

1

LabelsL(a)=min(,0)L(f) = min{,0+1} sorted L(b) = min{,0+2}

Chose (v= f ) T as minimum L(v)∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(a)=min(,0)L(f) = min{,0+1} L(b) = min{,0+2} sorted L(d) = min{,0+1+3} L(g) = min{,0+1+5}

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

After Second Iteration Graph G(*)

2

6

4

1

Chose (v= b ) T as minimum L(v)∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(a)=min(,0)L(f) = min{,0+1} L(b) = min{,0+2} L(c) = min{,0+2+2} sorted L(d) = min{,0+1+3} L(d) = min{4,0+2+2} --dif. pathL(e) = min{,0+2+4} L(g) = min{,0+1+5}

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

After Third Iteration(*)

42

6

64

1

Chose (v= c ) T as minimum L(v) ∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(a)=min(,0)L(f) = min{,0+1} L(b) = min{,0+2}L(c) = min{,0+2+2} L(d) = min{,0+1+3} sorted L(d) = min{4,0+2+2} dif. PathL(e) = min{,0+2+4} L(z) = min{,0+2+2+1} L(g) = min{,0+1+5} L(e) = min{6,0+2+2+3} dif. Path

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Fourth Iteration(*)

5

42

6

64

1

Chose (v= d ) T as minimum L(v)∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(a)=min(,0)L(f) = min{,0+1} L(b) = min{,0+2}L(c) = min{,0+2+2} L(d) = min{4,0+2+2} L(z) = min{,0+2+2+1} sorted L(e) = min{,0+2+4} L(g) = min{,0+1+5} L(e) = min{6,0+2+2+3} dif. Path b c e

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Fourth Iteration(*)

5

42

6

64

1

Chose (v= z ) T as minimum L(v)∊

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

LabelsL(a)=min(,0)L(f) = min{,0+1} L(b) = min{,0+2}L(c) = min{,0+2+2} L(d) = min{,0+1+3} L(d) = min{4,0+2+2} dif. PathL(z) = min{,0+2+2+1} L(e) = min{,0+2+4} sorted L(g) = min{,0+1+5} L(e) = min{6,0+2+2+3} dif. Path

a z

b c

d e

2

2

2

4

4

1

3

f g

1

3

5

76

Fourth Iteration(*)

5

42

6

64

1Terminate zT

Path to Z shorter than any unexplored path

For each x in T adjacent to v: L(x) = min{Lold(x),L(v)+w(v,x)} Where w(v,x) is distance from v to x. T := set of all temporary vertices

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 1

LabelsL(b) = min{,0+2} L(d) = min{,0+1}

Choose v ∊ T with minimum L(v)=d

a.2

a,1

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 2

LabelsL(b) = min{,0+2} L(d) = min{,0+1} L(e)=min{,0+1+1}

Choose v ∊ T with minimum L(v)=d

d.2

a,2

a.1

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 3

LabelsL(b) = min{,0+2} L(d) = min{,0+1} L(e)=min{,0+1+1} L(c)=min{,0+2+3} L(e)=min{,0+2+1} diff path

Choose v ∊ T with minimum L(v) =e

d.2

a,2

a.1

b,5

a z

b c

0

2

2

1

1

2

3

d e

1

Another Example: 4

Choose v ∊ T with minimum L(v)=z

d.2

a,2

e,4

a.1

b,5

LabelsL(b) = min{,0+2} L(d) = min{,0+1} L(e)=min{,0+1+1} L(c)=min{,0+2+3} L(e)=min{2,0+2+1} diff pathL(z)=min{,0+1+1+2}

Each node is labelled with its source node and the distance from the start node

Shortest path: a,d,e,z

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

a

f

d

5

2

e

7

4

Find shortest path a-f

a(0,a)

2

7

10

6

b

c

3

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6}

Each node is labelled with its source node and the distance from the start node

a(0,a)

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6} L(d) = min{,0+5+7} L(f) = min{,0+5+10}L(e) = min{,0+5+2}L(c) = min{,0+5+3}

Each node is labelled with its source node and the distance from the start node

a(0,a)

c

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6} L(d) = min{,0+5+7} L(f) = min{,0+5+10}L(e) = min{,0+5+2}L(c) = min{,0+5+3}

Each node is labelled with its source node and the distance from the start node

a(0,a)

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} L(c) = min{,0+6} L(d) = min{,0+5+7} L(f) = min{,0+5+10}L(e) = min{,0+5+2}L(c) = min{,0+5+3}L(e) = min{,0+6+7}Each node is labelled with its source node and the distance from the start node

a(0,a)

a

f

d

5

2

e

7

4

Find shortest path a-f

2

7

10

6

b

c

3

LabelsL(b) = min{,0+5} –from aL(c) = min{,0+6} –from aL(d) = min{,0+5+7} –from bL(f) = min{,0+5+10} – from bL(e) = min{,0+5+2} –from bL(c) = min{6,0+5+3} –from bL(c) = min{,0+5+2 +7} –from eL(f) = min{, 0+5+2 +4} – from ed not explored because (5+2+4)<12

a(0,a)

Shortest path: a,b,e,f

Length of path =11

Minimum

Paths

Shortest Path Example

Shortest Path Example

v1 v6

v2 v3

0

3

3

1

4

6

5

v4 v5

6

31

2

v1 v6

v2 v3

0

3

3

1

4

6

5

v4 v5

6

31

2

Step Vertex to be

marked

Distance to vertex Marked vertices

v1 v2 v3 v4 v5 v6

0 v1 0 3 6 v1

1 v2 0 3 ,8 6,4 ,6 v1,v2

2 v4 0 3 8,5 4 6,8 v1,v2,v4

3 v3 0 3 5 4 6,8 ,11 v1,v2,v4,v3

4 v5 0 3 5 4 6 11,9 v1,v2,v4,v3,v5

5 v6 0 3 5 4 6 9 v1,v2,v4,v3,v5,v6

v1 v6

v2 v3

0

3

3

1

4

6

5

v4 v5

6

31

2

Step Vertex to be

marked

Distance to vertex Marked vertices

v1 v2 v3 v4 v5 v6

0 v1 0 3 6 vi

1 v2 0 3 ,8 6,4 ,6 v1,v2

2 v4 0 3 8,5 4 6,8 v1,v2,v4

3 v3 0 3 5 4 6,8 ,11 v1,v2,v4,v3

4 v5 0 3 5 4 6 11,9 v1,v2,v4,v3,v5

5 v6 0 3 5 4 6 9 v1,v2,v4,v3,v5,v6

Step Vertex

to be

marked

Distance to vertex Unmarked vertices

A B C D E F

0 A 0 2 3 B,C,D,E,F

1 B 0 2 3 3 6 C,D,E,F

2 D 0 2 3 3 5 C,E,F

3 C 0 2 3 3 5 8 E,F

4 E 0 2 3 3 5 6 F

5 F 0 2 3 3 5 6

Path = <A,D,E,F>

Len = 6

Step Vertex

to be

marked

Distance to vertex Unmarked vertices

A B C D E F

0 A 0 2 3 B,C,D,E,F

1 B 0 2 3 3 6 C,D,E,F

2 D 0 2 3 3 5 C,E,F

3 C 0 2 3 3 5 8 E,F

4 E 0 2 3 3 5 6 F

5 F 0 2 3 3 5 6

Path = <A,D,E,F>

Len = 6

Find path a to f

UML for Dijkstra

Example of Rewriting Logic1mod VENDING-MACHINE {

[ Coin Item < Place < Marking ]

op null : -> Marking -- empty marking

ops $ q : -> Coin

ops a c : -> Item var M : Marking

op _ _ : Marking Marking -> Marking {assoc comm id: null}

rl [add-q] : M => M q .

rl [add-$] : M => M $ .

rl [buy-c] : $ => c .

rl [buy-a] : $ => a q .

rl [change] : q q q q => $ . }

A Petri net of the vending machine

-- Show one way to spend 3 dollars ($ $ $)

exec $ $ $ .

-- Show all ways to spend 3 dollars ($ $ $)

red $ $ $ =(*)=> m:Marking .

-- How can I get 2 apples with 3 dollars?

red $ $ $ =(*)=> a a M:Marking .

Example of Rewriting Logic

Example of Rewriting Logic

If I have a dollar and three quarters, can I get a cake and an apple? Yes.

red $ q q q =(*,*)=>! a c M:Marking .

Transitions

River Puzzle1

mod! RIVER-CROSSING {

[ Side Group ]

ops west east : -> Side

op change : Side -> Side

ops farmer wolf goat cabbage : Side -> Group

op __ : Group Group -> Group { assoc comm }

ops initial final : -> Group

vars S S' : Side

eq change(west) = east .

eq change(east) = west .

River Puzzle1

-- constraint for goat eaten

ceq wolf(S) goat(S) farmer(S') =

wolf(S) farmer(S') if S =/= S' .

-- constraint for cabbage eaten

ceq cabbage(S) goat(S) wolf(S') farmer(S') =

goat(S) wolf(S') farmer(S') if S =/= S' .

-- initial configuration all elements on the west.

eq initial = farmer(west) wolf(west) goat(west) cabbage(west) .

-- final configuration all elements on the east

eq final = wolf(east) farmer(east) goat(east) cabbage(east) .

River Puzzle1

trans [farmer-alone] : farmer(S) => farmer(change(S)) .

trans [wolf] : farmer(S) wolf(S) => farmer(change(S)) wolf(change(S)) .

trans [goat] : farmer(S) goat(S) => farmer(change(S)) goat(change(S)) .

trans [cabbage] : farmer(S) cabbage(S) => farmer(change(S))cabbage(change(S)) . }

open RIVER-CROSSING

-- Evaluate using the rewrite predicate =(*)=>

red initial =(*)=>

wolf(east) farmer(east) goat(east) cabbage(east) .

-- The following command will show the states

show path 27

Starts with Farmer, Wolf, Goat, Cabbage on all West (W) bank

[state 1] farmer(west) wolf(west) goat(west) cabbage(west)

[state 2] farmer(east) wolf(west) goat(east) cabbage(west)

[state 3] farmer(west) wolf(west) goat(east) cabbage(west)

[state 4] farmer(east) wolf(east) goat(east) cabbage(west)

[state 5] farmer(west) wolf(east) goat(west) cabbage(west)

[state 6] farmer(east) wolf(east) goat(west) cabbage(east)

[state 7] farmer(west) wolf(east) goat(west) cabbage(east)

[state 8] farmer(east) wolf(east) goat(east) cabbage(east)

River-CrossingFarmer, Wolf, Goat, Cabbage on all West (W) bank

River-Crossing possible states & safe states

Safe states

A directed graph or digraph g1

c

a

d

b

e

Fig. 19.1

Sample Graph g2v1

v4

v3

v2v5

Graph g2

Sample Graph g3

v1

v4

v3

v2v5

Graph g2

v7

v6

Sample Graph g3

a

b

2 e

8

3

d

[('a','c',2), ('a','d',6), ('b','a',3) ,('b','d',8), ('c','d',7), ('c','e',5) ,('d','e',10)]

67

c 5

build graphs makes edges bidirectional

10

fromList [('a',[('b',3.0),('d',6.0),('c',2.0)]),

('b',[('d',8.0),('a',3.0)]),

('c',[('e',5.0),('d',7.0),('a',2.0)]),

('d',[('e',10.0),('c',7.0),('b',8.0),('a',6.0)]),

('e',[('d',10.0),('c',5.0)])

]

buildGraph [('a','c',2), ('a','d',6), ('b','a',3) ,('b','d',8), ('c','d',7), ('c','e',5) ,('d','e',10)]

Review

• Definitions for path, simple path, degree of

vertex.

• Understand real world examples where

these concept could be used.

• Find path, simple path, cycle, or simple

cycle.

Review

• Handshaking Theorem

• Holds for a particular graph

Review

• Showing Euler Cycle exists in a graph

• Finding an Euler Cycle in a particular

graph.

• Finding a Hamilton Cycle in a particular

graph.

Review

• Definitions complete graph and planar

graph.

• Prove that the complete graph K5 is not

planar.

Review

• What is a bipartite graph.

• The complete K3 is not bipartite.

• Shortest path a-f

Shortest Path in C#

• A=0(A) B=2(A) C=3(D) D=1(A) E=3(D) F=6(G)

G=5(D)

A Z

B C

D E

2

2

2

4

4

1

3

F G

1

3

5

76

x

x

x

Graph Summary

• A complete digraph (v>2) has a Hamilton

Path.

Application of Graph Theory to

Programming• Control flow graph use graph notation to show

all paths that might be traversed through a

program during its execution.

Application of Graph Theory to

Programming• Cyclomatic complexity is a software metric . It is used to indicate the

complexity of a program. It directly measures the number of linearly

independent paths through a program's source code. Cyclomatic complexity

is computed using the control flow graph of the program. The nodes of the

graph correspond to indivisible groups of commands of a program, and a

directed edge connects two nodes if the second command might be

executed immediately after the first command. Cyclomatic complexity may

also be applied to individual functions, modules, methods or classes within a

program.

• It can also be used to test each linearly independent path through the

program, the number of test cases will equal the cyclomatic complexity of

the program

Order Sorted Algebra and

Preorder Algebra • CafeOBJ includes two distinct algebras:

• OSA is good for representing abstract data type

and values (a being ontology)

• POA representing states and reasoning about

transitions between states (a doing ontology).

• The intuitive distinction is the difference between

you as an individual and your life as a process.

The Blocks World Definition - Actions

• Blocks are picked up and put down by the arm

• Blocks can be picked up only if they are clear, i.e.,

without any block on top

• The arm can pick up a block only if the arm is empty, i.e.,

if it is not holding another block, i.e., the arm can be pick

up only one block at a time

• The arm can put down blocks on blocks or on the table

A problem from blocks world

• Find a sequence of robot moves to

rearrange blocks from the initial state to

the goal or final state.

Initial State Goal State

Blocks world state space

Start

Goal

Block Worlds

• In general, if there are n places, there

should be n*(n-1) possible moves.

• In this case 3*2=6 possible moves

Block Worlds

• There are 9 possible positions for each of the

3 blocks but we cannot use a permutation

calculation because many configurations such

as are not allowed.

• There are 10 possible arrangements of blocks

if the letters are disregarded. Three block can

be arranged in 6 ways, there are 10x6=60

possible configurations.

Block Worlds

• There are permCalc(9,3) = 504 possible

ways to distinctly configure 3 items from 9.

But in this case the rules of the block

world only allows 10*6 = 60 possible

states

Block Worlds

• Holding as a state

Block Worlds

• In general, if there are n places, there

should be n*(n-1) possible moves.

• In this case the first set of moves 3*2=6

Blocks World Complexity

• An optimal solution performs the

transformation using as few steps as

possible. Any solution: linear complexity

• Optimal solution: exponential complexity

(NP hard: see later).

Complexity

• Linear time O(N) : Finding an item in an unsorted list.

• Polynomial time O(NK) : computing square roots, powers,

and logarithms (k is a constant ).

• Exponential Time O(KN): The shortest route A to A,

which visits all points and returns to point A. This is

called the travelling salesman problem. As the size of the

problem increases linearly (O(N)), the time to solve the

problem increases exponentially (O(K to the power N)).

P and NP

• The time of efficient algorithms of type P grow

as a polynomial function (such as n, n2, or n3)

of the size of the input.

• NP problems could be solved in exponential

time by checking through all candidate

solutions. But such an algorithm whose

running time is 2n or above is useless in

practice.

Blocks world state space(Maude: specification and programming in rewriting logic

M. Clavel, F. Duran , S. Eker , P. Lincoln , N. Marti-Oliet,J. Meseguer , J.F. Quesada

, )

Instead of equations (denoted =)we use user-defined transition rules denoted => .

Blocks world state spacelet Start = empty & clear('b) & table('a) & on('b,'a) .let Goal = empty & clear('a) & table('b) & on('a,'b) .-- Start & goal configurationslet Start = empty & clear('b) & table('a) & on('b,'a) .

let Goal = empty & clear('a) & table('b) & on('a,'b) .-- Search for solutionred Start =(1,*)=>* Goal .

-- Examine solution pathshow path 4empty&clear('b)&table('a)& on('b,'a)[state 1] unstack (hold('b)&clear('a)& table('a))[state 2] putdown empty&clear('b)&table('b)&clear('a) &table('a)[state 3] pickup hold('a) & clear('b) & table('b)[state 4] stack empty&clear('a)&on('a,'b)&table('b)

Could be written as transition name followed by argument as follows:unstack(b) ; putdown(b) ; pickup(a) ; stack(a,b)

Sorting• An algorithm for sorting N distinct elements could potentially

have N! states. We will ignore duplicates for the moment.

• In this case 3! = 3 * 2 * 1 = 6 states.

• [0] 3 . 2 . 1 =swap=> [1] 2 . 3 . 1

• [1] 2 . 3 . 1 =swap=> [3] 2 . 1 . 3

• [3] 2 . 1 . 3 =swap=> [5] 1 . 2 . 3

• Sorting involves finding a path through the states <0,1,3,4>

• Sorting a list involves finding one of permutation p from N!

such that p will be in sorted order, in this case state 5 is such

a permutation. It can be reached in two distinct but equivalent

ways.

How many states?

• If there are N elements then there are N!=M

potential states. To find a solution path use the

command: show path M. CafeOBJ numbers the

states from 0. Termination can be proved.

• Disorder becomes lower along transitions between

some of the states. Using CafeOBJ Diaconescu[1]

proved that, s ==> s’ implies disorder

(s’) < disorder(s).

Preorder algebra (POA)(A Methodological Guide to the CafeOBJ Logic: Razvan Diaconescu)

Note this is a transition rule.

ctrans N . N’ => N’ . N if (N’ <= N) and (N =/= N’)

This transition equation says swap elements if they are in the wrong

order. We can use exec or the search command (next slide)to execute

transition rules.

CafeOBJ’s search command(Futatsugi)

• The search command searches the state space of POA

models. Written red (t1 =(m,n)=>* t2) it returns

true if t1 can be translated (or rewritten), via more than

0 times transitions, to some term which matches to t2.

Otherwise, it returns false . Possible transitions are

searched in breadth first fashion. n is upper bound of

the depth of the search, m is upper bound of the number

of terms which match to t2. If either of the depth of the

search or the number of the matched terms reaches to

the upper bound, the search stops.

CafeOBJ’s search command(Futatsugi)

• Fruit salad is a combination of apples,

grapes and bananas. We don't care what

order the fruits are in.

• The permutation that will open the lock is

942, we do care about the order.

• There are fewer combinations than

permutations. See the Calculations.cafe.

Permutation & Combination

State Space• State space = Directed graph

• Nodes = Problem situations

• Arcs = Actions, legal moves

• Problem = ( State space, Start, Goal)

• Note: several nodes may satisfy goal condition

• Solving a problem = Finding a path

• Problem solving = Graph search

• Problem solution = Path from start to a goal

top related