You are on page 1of 42

Introduction to Graph Theory, Finite

Automata, Grammars and Turing


Machines

13 de noviembre de 2019
Graph theory

1.1. Graph theory: fundamentals


Motivation. Graphs represent a conexionist approach to model relations between
diferent objects. When modeling and solving problems with graphs it is possible to
apply theorems and other interesting mathematical results. Applications of graph
theory include data traffic management, design of people transport networks, optimal
distribution for supermarket logistic, and efficient connection of computers, among ot-
hers. Therefore, it is convenient to know the benefits that graphic theory offers. Let’s
start.

Goal. To understand fundamental concepts of graph theory and its appli-


cations.

Definition 1 Graph.

A graph G = {V, A, γ} is conformed by:

A finite set V of vertices (nodes),

A finite set A of edges (links), and

A function γ that maps each edge to a subset {v,w}, where v y w are vertices
(they could be the same vertex).

An edge a that connects v and w is denoted by γ(a) = {v, w}. In that case, the
vertices v and w are the end-nodes of a.

1
2 Graph theory

Figura 1.1: Graphical representation for graph of Example 1.1.1.

1 2

4 3

Figura 1.2: A second representation for graph of Example 1.1.1.

1 2

3 4

Example 1.1.1 Let V = {1, 2, 3, 4}, A = {a1 , a2 , a3 , a4 , a5 , a6 , a7 }, and the mapping


function γ given by γ(a1 ) = γ(a5 ) = {1, 2}, γ(a2 ) = γ(a7 ) = {4, 3}, γ(a3 ) = {1, 3},
γ(a4 ) = {2, 4} y γ(a6 ) = {1, 4}.
Then G = (V, A, γ} is a graph.
A possible visual representation for graph G is shown in Figure 1.1, which is not
unique. See, for example, other representation in Figure 1.2.
Definition 2 Vertex degree is the number of edges that shares that end-vertex.
Definition 3 Bucle (loop). An edge from a vertex to itself.
Example 1.1.2 Figure 1.3 shows a visual representation for a graph where vertex A
has degree equal to 2, vertex B with degree equal to 4, vertex C with degree equal to
3, vertex D with degree equal to 4, vertex E with decree equal to zero, and vertex F
with degree equal to 1.

Oscar Herrera Alcántara


1.1. Graph theory: fundamentals 3

Figura 1.3: Visual representation for graph of Example 1.1.2.


A B

C
E
D
F

Figura 1.4: Figura 4.


a b

Definition 4 Isolated vertex. A zero degree vertex.


Definition 5 Adjacent vertices. Two vertices that are the ends of the same edge.
Definition 6 Multiple edges. Two or more edges with the same ends.
Example 1.1.3 In Figure 1.3 the edges γ(e1) = {A, B} y γ(e2) = {B, A} are
multiple. In Figure 1.3 vertex E is an isolated vertex. In Figure 1.4 vertices c and d
are adjacents. In Figure 1.4 vertices b and d are not adjacents.

Definition 7 Trajectory or path. A vertex sequence τ : v1 , v2 , . . . , vk , where vi and


vi+1 are adjacents, and edges (vi , vi+1 ) are not chosen more than once.
Definition 8 Circuit. A path that starts and ends in the same vertex.
Definition 9 Simple Trajectory . A path τ : v1 , v2 , . . . , vk where vertices are not used
more than once.

Introducción a la teorı́a de gráficas y a los autómatas finitos


4 Graph theory

Figura 1.5: Figura 6.


2 5

1 6

Definition 10 Simple circuit. A sequence of different vertices v1 , v2 , . . . , vk−1 (except


the first and the last that correspond to the same vertex).

Example 1.1.4 A path is represented in Figure 1.2 is τ1 : 1, 4, 3.


Example of trajectories in graph of Figura 1.3 are τ2 : D, B, C, C, τ3 : A, B, D and
τ4 : C, B, A.

For graph in Figure 1.4 some trajectories are: τ5 : a, b, c, d and τ6 : d, c, b, a, a.

In Figure 1.4 the sequence a, b, c, d, c is not a path, since edge given by d and c are
chosen twice.

Path τ2 in Figure 1.3 is not simple since vertex C is considered twice.

Sequence τ5 : a, c, b, a in Figure 1.4 conforms a circuit.


Examples of circuits are: τ6 : A, B, A, τ7 : D, D and τ8 : C, C as is shown in Figure 1.3.

Definition 11 Connected graph. A graph where there exist a path from a vertex to
any other.

Oscar Herrera Alcántara


1.1. Graph theory: fundamentals 5

Figura 1.6: Figura 7.


D1 D2 D3 D4 D5

Definition 12 Disconnected graph. A graph where is not possible to find a path


from a vertex to some other in the graph.

Definition 13 Subgraph of graph components are the parts that conform a discon-
nected graph.

Example 1.1.5 Graphs 1.1 and 1.2 are connected graphs (individually). Graph 1.3
is disconnected since vertex E has no edges as a path toward the rest of the vertices.
Grapf of Figure 1.3 has two components, the former given by vertices A, B, C, D, F
and the other conformed by vertex E.

Definition 14 Discrete graph Dn . A graph where for each integer n ≥ 1 it has n


vertices without edges.

Example 1.1.6 Figure 1.6 shows discret graph: D1 , D2 , D3 , D4 and D5 with one,
two, three, four, and five vertices respectively.

Definition 15 Complete graph Kn with n vértices v1 , v2 , . . . , vn is that graph where


for n ≥ 1 and edge {vi , vj } for i, j where i, j = 1, 2 . . . , n.1

Definition 16 Regular graph. Each vertex has the same degree.

Note:
All complete graph Kn is regular and each vertex has degree equal to n − 1.
All discrete graph is regular since each vertex has zero degree.
Figure 1.7 illustrate complete graphs K3 , K4 , and K5 .

Definition 17 Linear graph Ln with n vértices is a graph where n ≥ 1 and edges


{vi , vi+1 } for 1 ≤ i < n.

Example 1.1.7 Figure 1.8 shows linear graphs L2 , L3 , L4 and L5 .

Introducción a la teorı́a de gráficas y a los autómatas finitos


6 Graph theory

Figura 1.7: Figura 8.

K3 K4 K5 K6

Figura 1.8: Figura 9.

L2 L3 L4 L5

Oscar Herrera Alcántara


1.1. Graph theory: fundamentals 7

Figura 1.9: Figura 10.


E

D
B C

Figura 1.10: Figura 11.


2 4
3

1 5

Note: All graphs Kn are connected graphs.


All graphs Ln are connected graphs.
All graphs Dn are disconnected graphs with n components.

Definition 18 An Eulerian path is a path in graph G that includes each edge just
once.

Definition 19 An Eulerian circuit is an Eulerian path in graph G which is also a


circuit.

Example 1.1.8 An Eulerian path in Figure 1.9 is τ : E, D, B, A, C, D. An Eulerian


circuit in Figure 1.18 is τ : 5, 3, 2, 1, 3, 4, 5.
1
It means that each vertex in Kn is connected with each other.

Introducción a la teorı́a de gráficas y a los autómatas finitos


8 Graph theory

Figura 1.11: Figura 12.


a b

e
c d

f g

Theorem 1.1.1 On the existence of Eulerian circuits:

1. If a graph G has at least one vertex with odd degree, then there is no an Eulerian
circui in G.

2. If G is a connected graph and all vertices has even degree, then there exist an
Eulerian circuit in G.

Theorem 1.1.2 On the existence of Eulerian trajectory:

1. If a graph G has more that two vertices with even degree, then there is no an
Eulerian path G.

2. If G is connected grapg and it has two vertices exacly with odd degree, then
there exist an Eulerian path in G. Moreover, any Eulerian path must start in a
vertex with odd degree and end in the second with odd degree.

Definition 20 An edge {vi , vj } is a bridge in graph G when eliminating {vi , vj } it


becomes a disconnected graph.

Example 1.1.9 An edge {B, E} in graph of Figure 1.3 is a bridge.

Definition 21 A hamiltonian path contains each vertex of a graph just once.

Oscar Herrera Alcántara


1.1. Graph theory: fundamentals 9

Figura 1.12: Figura 13.


d

c e

Definition 22 A hamiltonian circuit contains each vertex once, with exceptions of


the first vertex which matches the last vertex.

Example 1.1.10 Path a, b, c, d, e is a hamiltonian path, since it uses each vertex just
once.
Note that all complete graph Kn has hamiltonian circuits.
Example 1.1.11 When starting in any vertex, it is possible to visit all the vertex
sequentially in some desired order. For K3 it is possible to verify the next hamiltonian
trajectories as is shown in Figure 1.13: {a, b, c}, {a, c, b}, {b, a, c}, {b, c, a}, {c, a, b},
{c, b, a}.
Example 1.1.12 It is possible to verify all 4! = 16 hamiltonian trajectories according
to graph K4 (right side in Figure 1.13) that corresponds to pertumations of 4 vertices:
{1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 2, 4}, {1, 3, 4, 2}, {2, 1, 3, 4}, {2, 1, 4, 3},
{2, 4, 3, 1}, {2, 4, 1, 3}, {3, 1, 2, 4}, {3, 1, 4, 2}, {3, 2, 4, 1}, {3, 2, 1, 4},
{4, 1, 2, 3}, {4, 1, 3, 2}, {4, 2, 1, 3}, {4, 2, 3, 1}.
Let G a connected graph with n vértices, n ≥ 2 without loops and with no multiple
vertices.
Theorem 1.1.3 A graph G with n vértices has a hamiltoniano circuit if for any pair
of non-adjacents vertices u and v in G, the degree of u plus the degree of v is greater
than or equal to n.

Introducción a la teorı́a de gráficas y a los autómatas finitos


10 Graph theory

Figura 1.13: Figura 14.


a 1 2

b
c 4 3
K3 K4

Corollary. A graph G has at least one hamiltonian circuit if each vertex has a
degree greater than or equal to n2 .

Theorem 1.1.4 let m the number of edges in G and let n the number of vertices,
then G has a hamiltonian circuit if m ≥ 12 (n2 − 3n + 6).

Example 1.1.13 Para una gráfica completa K4 cada vértice tiene grado 3, enton-
ces según el Teorema 1.1.3 para cualquier par de vértices no adyacentes la suma de
sus grados es 6, que es mayor que n = 4, por lo tanto existe al menos un circuito
hamiltoniano.

Example 1.1.14 Los recı́procos de los Teoremas 1.1.3 y 1.1.4 no son válidos, es decir
las condiciones dadas son suficientes pero no necesarias, para la conclusión. Considere
la gráfica de la figura 1.14. El número de vértices es n = 8, cada vértice tiene grado
igual a 2, y para cualquier par de vértices no adyacentes la suma de sus grados es
4. El número total de aristas también es 8. Por lo tanto, las premisas de los Teore-
mas 1.1.3 y 1.1.4 no son satisfechas pero existen circuitos hamiltonianos para la gráfica
de la figura 1.14, por ejemplo: {A, B, C, D, E, F, G, H}, {B, C, D, E, F, G, H, A}, . . . ,
{H, A, B, C, D, E, F, G}.

1.2. Exercices
Exercise 1.2.1 Definir los elementos la gráfica G = (V, E, γ} asociada con la figu-
ra 1.3.

Oscar Herrera Alcántara


1.2. Exercices 11

Figura 1.14: Figura 15.


A

H B

G C

F D

Solution 1.2.1 G = (V, E, γ) donde el conjunto de vértices es V = {A, B, C, D, F },


el conjunto de aristas es E = {e1, e2, e3, e4, e5, e6} y donde γ está dada por γ(e1) =
{A, B}, γ(e2) = {B, A}, γ(e3) = {B, C}, γ(e4) = {B, E}, γ(e5) = {E, F }, y γ(e6) =
{F, F },
Exercise 1.2.2 Usando la definición de path como una sucesión de vértices, reescriba
la definición de una path de Euler.
Solution 1.2.2 Una path de Euler es una sucesión τ : v1 , v2 , . . . , vk de vértices, cada
uno adyacente al siguiente, y una elección de una arista entre vi y vi+1 de modo que
ninguna arista es elegida más de una vez e incluye a cada una de las aristas (sólo una
vez).
Exercise 1.2.3 Usando la definición de path reescriba la definición de circuito como
una sucesión de vértices.
Solution 1.2.3 Un circuito es una una sucesión τ : v1 , v2 , . . . , vk−1 de vértices, cada
uno adyacente al siguiente, y una elección de una arista entre vi y vi+1 de modo que
ninguna arista es elegida más de una vez que inicia y termina con el mismo vértice,
por lo tanto v1 = vk−1 .
Exercise 1.2.4 Usando la definición de path y circuito reescriba la definición de
circuito de Euler como una sucesión de vértices.

Introducción a la teorı́a de gráficas y a los autómatas finitos


12 Graph theory

Solution 1.2.4 Un circuito de Euler es una sucesión τ : v1 , v2 , . . . , vk−1 de vértices,


cada uno adyacente al siguiente, y una elección de una arista entre vi y vi+1 de modo
que ninguna arista es elegida más de una vez, incluye a cada una de las aristas (sólo
una vez) e inicia y termina con el mismo vértice, por lo tanto v1 = vk−1 .
Exercise 1.2.5 ¿La gráfica K4 (ver figura 1.8) tiene al menos un circuito de Euler?
Solution 1.2.5 No. Dado que es una gráfica regular donde cada uno de los cuatro
vértices tiene grado 3, y según la primera parte del Teorema 1.1.1 no puede existir un
circuito de Euler.
Exercise 1.2.6 ¿La gráfica K4 (ver ilustrada en la figura 1.8) tiene al menos una
path de Euler?
Solution 1.2.6 No. Dado que es una gráfica regular donde cada uno de los cuatro
vértices tiene grado 3, y según la primera parte del Teorema 1.1.2 no puede existir una
path de Euler.
Exercise 1.2.7 ¿Existe al menos un circuito de Euler en la gráfica de la figura 1.11?
Solution 1.2.7 No. La gráfica tiene dos vértices de grado impar (igual a 3), entonces
por la primera parte del Teorema 1.1.1 no existe un circuito de Euler.
Exercise 1.2.8 ¿Existe al menos una path de Euler en la gráfica de la figura 1.11?
Solution 1.2.8 Sı́. La gráfica tiene exactamente dos vértices de grado impar (los
vértices a y g tienen grado igual a 3), entonces por la segunda parte del Teorema 1.1.2
sı́ existe una trayectorua de Euler, y de hecho se puede construir comenzando en el
vértice a (o en el vértice g) y terminar en el vértice g (o en el vértice a).
Exercise 1.2.9 Defina formalmente la gráfica asociada a la figura 1.3
Solution 1.2.9 G = (V, E, γ) donde el conjunto de vértices es V = {A, B, C, D, F },
el conjunto de aristas es E = {e1, e2, e3, e4, e5, e6} y donde γ está dada por γ(e1) =
{A, B}, γ(e2) = {B, A}, γ(e3) = {B, C}, γ(e4) = {B, D}, γ(e5) = {D, F }, y γ(e6) =
{F, F },
Exercise 1.2.10 Defina formalmente la gráfica asociada a la figura 1.4
Solution 1.2.10 G = (V, E, γ) donde el conjunto de vértices es V = {a, b, c, d, e}, el
conjunto de aristas es E = {e1, e2, e3, e4, e5} y donde γ está dada por γ(e1) = {a, a},
γ(e2) = {a, b}, γ(e3) = {a, c}, γ(e4) = {b, c}, y γ(e5) = {c, d},

Oscar Herrera Alcántara


1.2. Exercices 13

1.2.1. Computer experiments


File graph.pl
See original path rule:
https://www.cse.unsw.edu.au/~billw/cs9414/notes/prolog/path-trace.html

edge(a,b). edge(a,c). edge(a,d). edge(b,d).


edge(c,d). edge(d,e). edge(d,f). edge(d,g).
edge(f,g). edge(e,g).

path(Node, Node, _, [Node]). % rule 1


path(Start, Finish, Visited, [Start | Path]) :- % rule 2
edge(Start, X),
not(member(X, Visited)),
path(X, Finish, [X | Visited], Path).

$ swipl

?- [graph].
true.

?- path(a,g,[a],Path).
Path = [a, b, d, e, g] ;
Path = [a, b, d, f, g] ;
Path = [a, b, d, g] ;
Path = [a, c, d, e, g] ;
Path = [a, c, d, f, g] ;
Path = [a, c, d, g] ;
Path = [a, d, e, g] ;
Path = [a, d, f, g] ;
Path = [a, d, g] ;
false.

?-

Introducción a la teorı́a de gráficas y a los autómatas finitos


14 Graph theory

Oscar Herrera Alcántara


Árboles

1.3. Conceptos de árboles

Objetivo. Comprender los conceptos básicos de los árboles.

Motivación.
Ası́ como se establecen relaciones entre los individuos en la sociedad, es posible definir
matemáticamente relaciones entre los elementos de dos o más conjuntos. La represen-
tación de objetos del mundo real como elementos de conjuntos matemáticos permite
darle solución a problemas asociados al aplicarles diferente operadores y explorar sus
propiedades. Ejemplo de ello son la identificación de clientes que suelen comprar cierto
tipo de productos (libros, pelı́culas, etc.) o servicios (usuarios de diferentes estaciones
de radio, proveedores de internet, etc.) y con ello realizar predicciones y elecciones
de nuevos productos o servicios. Por lo tanto, conviene conocer las bondades que los
conceptos de árboles nos brindan. Comencémos con este tema.
Definition 23 Relación binaria.
Dados dos conjuntos A y B, una relación binaria es un subconjunto de A × B.
Una forma usual para expresar relaciones entre elementos de dos conjuntos A y B es
mediante un par ordenado (a, b). También suele usarse la notación a R b para denotar
que existe una relación entre a ∈ A y b ∈ B.
Example 1.3.1 Dé una representación visual de la relación R entre el conjunto de
personas A y el conjunto de sus colores favoritos B donde A = {Alberto, Benito, Carlos}, B =
{azul, blanco} y R = {(Alberto, azul), (Alberto, blanco), (Benito, azul), (Carlos, blanco)}.

15
16 Árboles

Figura 1.15: Figura 0.


Alicia
azul
Benito
blanco
Carlos

Figura 1.16: Figura 01.


1
a
2
b
3
c
4

Oscar Herrera Alcántara


1.3. Conceptos de árboles 17

Exercise 1.3.1 Represente en forma de conjuntos y pares ordenados la relación


ilustrada en la figura 1.16.

Solution 1.3.1 El primer conjunto es A = {a, b, c}, el segundo conjunto es B =


{1, 2, 3, 4} y la relación de A en B es R = {(a, 2), (a, 3), (a, 4), (b, 3), (b, 4), (c, 1), (c, 4)}.

Un árbol es un tipo especial de gráfica. En un árbol no existen ciclos e incluye aristas


que están dirigidas de un vértice origen a un vértice destino que se denota mediante
el par (vi , vj ).

Definition 24 Árbol.
Un árbol T es una relación sobre un conjunto A de vértices, tal que existe un vértice
raı́z vr con una única trayectoria hacia cualquier otro vértice en A, pero no existe una
trayectoria de vr a vr .

Definition 25 Hoja de un árbol.


Es un vértice del árbol tal que ninguna trayectoria comienza en él.

Example 1.3.2 Sea el conjunto de vértices A = {v0 , v1 , v2 , v3 , v4 , v5 , v6 , v7 , v8 , v9 , v10 },


y T = {(v2 , v3 ), (v2 , v1 ), (v4 , v5 ), (v4 , v6 ), (v5 , v8 ), (v6 , v7 ), (v4 , v2 ), (v7 , v9 ), (v7 , v10 )} la re-
lación sobre A.
Los vértices v1 , v3 , v8 , v9 y v10 son hojas del árbol dado que ninguna trayectoria
comienza con ellos.
Los vértices v2 , v5 , v6 y v7 no son hojas.
Los vértices v2 , v5 , v6 y v7 no tienen trayectorias hacia el vértice v4 por lo que no
pueden ser raı́ces.
Si existe una raı́z éste debe ser vr = v4 . En efecto, se puede demostrar que existe
una trayectoria de v4 hacia los demás vértices v0 , v1 , v2 , v3 , v5 , v6 , v7 , v8 , v9 , v10 , pero no
existe una trayectoria de v4 a v4 .

La figura 1.17 muestra una representación visual del árbol del ejemplo 1.3.2.

Definition 26 Profundidad de un árbol. Es el número máximo de aristas de las


trayectorias que conectan el vértice raı́z con las hojas.

Definition 27 Nivel de los vértices de un árbol. Es el número de aristas de las


trayectorias del vértice raı́z hacia los vértices que comparten esa misma longitud.

Exercise 1.3.2 ¿Cuál es la profundidad del árbol de la figura 1.17?

Introducción a la teorı́a de gráficas y a los autómatas finitos


18 Árboles

Figura 1.17: Figura Arbol1.


v4

v2 v5 v6

v1 v3 v8 v7

v9 v10

Oscar Herrera Alcántara


1.3. Conceptos de árboles 19

Solution 1.3.2 Las trayectorias π1 : v4 v2 v1 , π2 : v4 v2 v3 , π3 : v4 v5 v8 , π4 : v4 v6 v7 v9 ,


π5 : v4 v6 v7 v10 tienen por longitud 3 vértices (2 aristas), 3 vértices (2 aristas), 3 vértices
(2 aristas), 4 vértices (3 aristas) y 4 vértices (3 aristas) respectivamente, por lo que la
profundidad del árbol es 4 − 1 = 3.

Exercise 1.3.3 ¿Cuál es el nivel del vértice v4 en el árbol de la figura 1.17?

Solution 1.3.3 No se involucran aristas por lo tanto el vértice v4 está en el nivel 0


del árbol.

Exercise 1.3.4 ¿Cuál es el nivel de los vértices v9 y v10 en el árbol de la figura 1.17?

Solution 1.3.4 Las trayectorias π4 : v4 v6 v7 v9 y π4 : v4 v6 v7 v10 involucra 3 aristas por


lo tanto ambos vértices está en el nivel 3 del árbol.

Definition 28 Número de hijos de un vértice de un árbol. Es el número de aristas


que tienen por origen al vértice en cuestión.

Exercise 1.3.5 ¿Cuál es el número de hijos de las hojas de un árbol?

Solution 1.3.5 Las hojas no tienen trayectorias que inicien en esos vértices, por lo
tanto no tienen hijos.

Definition 29 Árbol n-ario.


Un árbol que tiene n hijos en cada uno de sus vértices.

Definition 30 Árbol completo.


Un árbol que tiene el mismo número de hijos en cada uno de sus vértices.

Exercise 1.3.6 Describa un árbol binario con profundidad dos.

Solution 1.3.6 Sea v0 el vértice raı́z con dos hijos y sus correspondientes aristas
que tienen por destino a los vértices v1 y v2 . Cada vértice v1 y v2 tiene a su vez dos
vértices v3 , v4 y v5 , v6 respectivamente. La trayectoria de v0 a cualquiera de los vértices
v3 , v4 , v5 o v6 es 2 por lo tanto el árbol se describe mediante A = {0, 1, 2, 3, 4, 5, 6} y
T = {(v0 , v1 ), (v0 , v2 ), (v1 , v3 ), (v1 , v4 ), (v2 , v5 ), (v2 , v6 )}.

Definition 31 Subárbol.
Dado un vértice vs ∈ A, un subárbol es el árbol que se obtiene al considerar los vértices
hijos de vs y las aristas que los conectan. El vértice vs es la nueva raı́z del subárbol.

Introducción a la teorı́a de gráficas y a los autómatas finitos


20 Árboles

Figura 1.18: Figura 11.

* 4

2 +

1 3

Definition 32 Recorrido de un árbol.


Es el orden en el que se visitan los vértices de un árbol.

El recorrido de un árbol binario involucra los vértices vC , vL , vR en donde los vértices


vL y vR son los hijos de vC y se considera que éstos estan ordenados, es decir, vL está
a la izquierda de vR , y vC está al centro de ambos.
El recorrido de un árbol con una única raı́z, que a su vez es la única hoja es trivial,
y la acción suele ser la impresión del contenido del vértice. Aquı́ se usará la sentencia
“IMPRIME ” para indicar la visita correspondiente al vértice en cuestión durante el
recorrido del árbol.
La acción que se toma al recorrer un vértice vi ∈ A se define por el usuario, y puede
consistir en imprimir la etiqueta asociada a cada vértice o bien recorrer en un orden
predeterminado el subárbol con raı́z vi .

Oscar Herrera Alcántara


1.3. Conceptos de árboles 21

1.3.1. Recorrido en entreorden


Se recorre en forma recursiva en entreorden el subárbol con raı́z vL , seguido de vC y
seguido del entreorden del subárbol con raı́z vR .

Example 1.3.3 Para el árbol de la figura 1.18 muestre el recorrido en entreorden.


1. vL : el subárbol de la izquierda tiene por raı́z al asterisco
2. VC : el vértice central tiene el signo menos
3. VR : el subárbol de la derecha tiene por raı́z al número 4
4. Se procede a recorrer en entreorden el subárbol con raı́z asterisco:
5. vL : subárbol de la izquierda tiene por raı́z al número 2, IMPRIME 2
6. VC : el vértice central tiene el asterisco, IMPRIME *
7. VR : subárbol de la derecha tiene por raı́z al sigmo de suma
8. Se procede a recorrer en entreorden el subárbol con raı́z al signo de suma:
9. vL : subárbol de la izquierda tiene por raı́z al número 1, IMPRIME 1
10. VC : el vértice central tiene signo de suma, IMPRIME +
11. VR : subárbol de la derecha tiene por raı́z al número 3, IMPRIME 3
12. Se regresa al punto 2 donde con el vértice del signo menos, IMPRIME -
13. Se continúa en el punto 3, IMPRIME 4
Por lo tanto la salida del recorrido del árbol de la figura 1.18 en entreorden es:
2 ∗ 1 + 3 − 4.

1.3.2. Recorrido en preorden


Se recorre el vértice vC seguido del preorden del subárbol con raı́z vL y luego el
preorden del subárbol con raı́z vR .

Example 1.3.4 Para el árbol de la figura 1.18 muestre el recorrido en preorden.


1. vL : el subárbol de la izquierda tiene por raı́z al asterisco
2. VC : el vértice central tiene el signo menos
3. VR : el subárbol de la derecha tiene por raı́z al número 4
4. El vértice central tiene al sigmo menos, IMPRIME -
5. Se procede a recorrer en preorden el subárbol con raı́z asterisco, 6. vL : el subárbol
de la izquierda tiene por raı́z al número 2
7. VC : el vértice central tiene el signo asterisco
8. VR : el subárbol de la derecha tiene por raı́z al signo suma
9. El vértice central tiene al sigmo asterisco, IMPRIME *

Introducción a la teorı́a de gráficas y a los autómatas finitos


22 Árboles

10. vL : el subárbol de la izquierda tiene por raı́z al número 2, IMPRIME 2


11. vR : el subárbol de la derecha tiene por raı́z al signo de suma
12. Se procede a recorrer en preorden el subárbol con raı́z el signo de suma 13. vL : el
subárbol de la izquierda tiene por raı́z al número 1
14. VC : el vértice central tiene el signo de suma
15. VR : el subárbol de la derecha tiene por raı́z el número 3
16. VC : el vértice central tiene el signo de suma, IMPRIME +
17. vL : el subárbol de la izquierda tiene por raı́z al número 1, IMPRIME 1
18. VR : el subárbol de la derecha tiene por raı́z el número 3, IMPRIME 3
19. Continuar en el punto 3 donde VR : el subárbol de la derecha tiene por raı́z al
número 4, IMPRIME 4

Por lo tanto la salida del recorrido del árbol de la figura 1.18 en preorden es:
− ∗ 2 + 1 3 4.

1.3.3. Recorrido en posorden


También se conoce como recorrido en forma posfija, polaca inversa o sufija.
Se recorre en posorden el subárbol con raı́z vL seguido del posorden del subárbol con
raı́z vR y luego vC .

Example 1.3.5 Para el árbol de la figura 1.18 muestre el recorrido en posorden.


1. vL : el subárbol de la izquierda tiene por raı́z al asterisco
2. VC : el vértice central tiene el signo menos
3. VR : el subárbol de la derecha tiene por raı́z al número 4
4. Se procede a recorrer en posorden el subárbol con raı́z asterisco, 5. vL : el subárbol
de la izquierda tiene por raı́z al número 2, IMPRIME 2
6. VR : el subárbol de la derecha tiene por raı́z al signo suma, y se procede a recorrerlo
en posorden
7. vL : el subárbol de la izquierda tiene por raı́z al número 1
8. VC : el vértice central tiene el signo suma
9. VR : el subárbol de la derecha tiene por raı́z al número 3
10. vL : el subárbol de la izquierda tiene por raı́z al número 1, IMPRIME 1
11. VR : el subárbol de la derecha tiene por raı́z al número 3, IMPRIME 3
12. VC : el vértice central tiene el signo suma, IMPRIME +
13. se continúa con el punto 1 donde vL es el subárbol de la izquierda tiene por raı́z al

Oscar Herrera Alcántara


1.3. Conceptos de árboles 23

asterisco, IMPRIME *
14. se continúa con el punto 3 donde vR es el subárbol de la derecha tiene por raı́z al
número 4, IMPRIME 4
15. VC : el vértice central tiene el signo menos, IMPRIME -

Por lo tanto la salida del recorrido del árbol de la figura 1.18 en posorden es:
2 1 3 + ∗ 4 −.

Introducción a la teorı́a de gráficas y a los autómatas finitos


24 Árboles

Oscar Herrera Alcántara


Finite Deterministic Automata

1.4. Finite Deterministic Automata

Goal. To understand basic concepts of finite automata.

Motivation. The automata inputs can represent events that change the current
state of the automata, such as events that change our mood.

Definition 33 Finite Deterministic Automata.


An FDA is a 5-tuple A = (Q, Σ, δ, q0 , F ) where:

Q is a finite set of states

Σ is a finite set of input symbols also called alphabet

δ a transition function

q0 ∈ Q initial state

F finite and non-empty set of final states, acceptance states

The transition function δ is often represented as a transition table δ : Q × Σ → Q.

Definition 34 String. Yuxtaposition or concatenation of input symbols.

25
26 Finite Deterministic Automata

Definition 35 String acceptance. A string is declared accepted for an AFD when


processing each symbol of the input string produces that the last state belongs to F .

Definition 36 Formal Language of an FDA. The set with all the strings that are
accepted by the FDA.

Definition 37 Regular expression. Formal notation to represent the FDA language.

Definition 38 Extended transition function δ̂. A recursive function that allows to


decide whether a string (and not only restricted to a single symbol) is accepted for the
FDA or rejected.

Recursive functions are conformed by two steps: Base step and recursive step.

Base step. Base case applyies to process an empty string  where δ̂(q0 , ) =
δ(q0 , ) = q0

Recursive step. Given a string s = s1 s2 . . . sn with n ≥ 1 it is defined recursively:


δ̂(q0 , s1 s2 . . . sn−1 sn ) = δ(δ̂(q0 , s1 s2 . . . sn−1 ), sn )

Example 1.4.1 Regular expression: 1∗ 00∗ 1(0|1)∗ represents all strings accepted by
automata of Figure 1.19

Remark. Non-binary alphabets are allowed in automatas, but it is possible to enco-


de the finite elements of a non-binary alphabet, with size n elements, by using dlog2 (n)e
bits. In other words, is possible to build an equivalente FDA with a binary alpabeth.
Moreover, binary computer are supported in on-off circuits and then it give place to
digital computers. For example for Σ = {a, b, c, d}n = 4, and is possible to assing
a = 00, b = 01, c = 10, d = 11, now we can process with transitions to intermediate
states that require ”0 − 0”, ”0 − 1”, ”1 − 0” or ”1 − 1” sequences.

Figura 1.19: Finite deterministic automata FDA

Oscar Herrera Alcántara


1.4. Finite Deterministic Automata 27

Example 1.4.2 Define formally the FDA of Figure 1.19.

Q = {q0 , q2 , q1 } = {q0 , q1 , q2 } given that sets have no ordered elements (is not
relevant).

Σ = {0, 1} is a binary alphabet.

δ a transition function: {(q0 , 0) = q2 , (q0 , 1) = q0 , (q2 , 0) = q2 , (q2 , 1) = q1 , (q1 , 0) =


q1 , (q1 , 1) = q1 }

q0 ∈ Q initial state.

F = {q1 }

Figure 1.20 shows a pictorial representation of an AFD conceived as an abstract


machine, the input string is read from the tape from left to right, and the single hand
moves from a state to other (elements of Q). After reading all the in symbols the string
is accepted if and only if the hand points to a final state.

String processing with FDA


It is possible to process strings S (of single symbols) by defining the extended delta
function δ̂ as follows:

Definition 39 Extended delta function. Let

S = s1 s2 . . . sn−1 sn

w = s1 s2 . . . sn−1
S = wsn
Then
δ̂(q, wsn ) = δ(δ̂(q, w), sn )

Example 1.4.3 Process the string S = 100101 with automata given in Figure 1.19.

δ̂(q0 , 100101) = δ(δ̂(q0 , 10010), 1) = q1

δ̂(q0 , 10010) = δ(δ̂(q0 , 1001), 0) = q1

Introducción a la teorı́a de gráficas y a los autómatas finitos


28 Finite Deterministic Automata

Figura 1.20: AFD

Oscar Herrera Alcántara


1.4. Finite Deterministic Automata 29

δ̂(q0 , 1001) = δ(δ̂(q0 , 100), 1) = q1

δ̂(q0 , 100), 0) = δ(δ̂(q0 , 10), 0) = q2

δ̂(q0 , 10) = δ(δ̂(q0 , 1), 0) = q2

δ̂(q0 , 1) = δ(δ̂(q0 , ), 1) = q0

δ̂(q0 , ) := δ(q0 , ) = q0
Alternatively:
δ̂(q0 , 1) = δ(q0 , 1) = q0

1.4.1. Non-deterministic finite automata NDFA


Definition 40 NDFA.
A NFDA is a 5-tuple A = (Q, Σ, δ, q0 , F ) where:

Q is a finite set of states

Σ is a finite set of input symbols also called alphabet

δ a transition function: P Q × 7→ P Q

q0 ∈ Q initial state

F finite and non-empty set of final states, acceptance states

[
δ̂(q, ws) = δ(δ̂(q, w), s)

[
δ̂(q0 , 00101) = δ(δ̂(q0 , 0010), 1) = δ({q0 , q1 }, 1) = δ(q0 , 1)∪δ(q1 , 1) = {q0 }∪{q2 } = {q0 , q2 }

Introducción a la teorı́a de gráficas y a los autómatas finitos


30 Finite Deterministic Automata

Figura 1.21: Non-deterministic finite automata

[ [
δ̂(q0 , 0010) = δ(δ̂(q0 , 001), 0) = δ({q0 , q2 }, 0) = δ(q0 , 0)∪δ(q2 , 0) = {q0 , q1 }∪{} = {q0 , q1 }

[ [
δ̂(q0 , 001) = δ(δ̂(q0 , 00), 1) = δ({q0 , q1 }, 1) = δ(q0 , 1)∪δ(q1 , 1) = {q0 }∪{q2 } = {q0 , q2 }

[ [
δ̂(q0 , 00), 0) = δ(δ̂(q0 , 0), 0) = δ({q0 , q1 }, 0) = δ(q0 , 0) ∪ δ(q1 , 0) = {q0 , q1 } ∪ {}

[
δ̂(q0 , 0) = δ(q0 , 0) = {q0 } ∪ {q1 } = {q0 , q1 }

Reflexion.
How do you imagine Figure 1.20 could be adapted to illustrate a non-deterministic
FDA?

1.4.2. Equivalence of L(FDA) = L(NDFA)


There exist the equivalence of L(FDA) = L(NDFA).
NDFA explores the decision of accepting a string throught a paralell searching three.
FDA explores sequentially the string, single symbol step by step.
Figure 1.22 is a deterministic version of the NFDA of Figure 1.21 (really?)
Note that for a NDFA, the extended transition function δ̂ considers the union of the
states explored simultaneously (parallelism):
[
δ̂(q, ws) = δ(δ̂(q, w), s)

Oscar Herrera Alcántara


1.4. Finite Deterministic Automata 31

Figura 1.22: FDA equivalence for a NFDA

in this case we process the String S = 00101 with the NFDA approach followed by
the deterministic approach.
Non-deterministic approach Instead of applying the extended functions, it is
illustrated a expansion-tree where the automata if Figure 1.23 explores several states
simultaneously to process the string S = 00101 (see Figure 1.23).

Figura 1.23: Processing tree for 00101 string with a NFDA

Deterministic approach. With the AFD given in Figure 1.22 (equivalent to the
NFDA of Figure 1.22:

Introducción a la teorı́a de gráficas y a los autómatas finitos


32 Finite Deterministic Automata

δ̂({q0 }, 00101) = δ(δ̂({q0 }, 0010), 1) = δ({q0 , q1 }, 1) = {q0 , q2 }

δ̂({q0 }, 0010) = δ(δ̂({q0 }, 001), 0) = δ({q0 , q2 }, 0) = {q0 , q1 }

δ̂({q0 }, 001) = δ({q0 , q1 }, 1) = {q0 , q2 }

δ̂({q0 }, 00), 0) = δ({q0 , q1 }, 0) = {q0 , q1 }

δ̂({q0 }, 0) = δ({q0 }, 0) = {q0 , q1 }

NFDA vs FDA approaches


See that in both cases, the NFDA and FDA are equivalent versions, then they take
to the same final states {q0 , q2 }.
In one hand, the NFDA approach requires several processor units at different times
illustrated as 0-0-1-0-1, and altough some states yields to error-states some other treaths
or branches of the three still processing symbols in parallel. In fact, in the previous
example two processors are used simultaneously but in general, it depends of the
current number of enabled branches.
On other hand, the FDA approach does not require several processors but requires
an exponential number of states given by P Q states. If n = |Q| = n is the cardinality
of Q (size of Q) then 2n combinations of states labeled as {}, {q0 }, {q1 }, {q2 }, {q0 , q1 },
{q0 , q2 }, {q1 , q2 }, and {q0 , q1 , q2 } can be used. Some states are not used to process the
string 00101 but in general it will require 2n states.

NFDA requires many CPUS whereas FDA requires a lot of memory space,
but they are able to process the same language (equivalence).

1.4.3. NDFA with  transitions


Definition 41 Clausure of q. C(q) corresponds to the set of states that are reacheable
with −symbol transitions and the state itself.

Oscar Herrera Alcántara


1.4. Finite Deterministic Automata 33

Figura 1.24: Non-deterministic automata with  transitions

Example 1.4.4 Consider the automata given in Figure 1.21:

C(q0 ) = {q0 , q1 } Since q1 is reachable from q0 with an  transition, and also


consider q0 itself.

C(q1 ) = {q1 }. Since there is no −transition, just q1 is considered.

C(q3 ) = {q3 , q5 }. Since there is −symbol in q3 toward q5 and also q3 is considered.

Definition 42 NDFA with  transitions.


An −NFDA is a 5-tuple A = (Q, Σ ∪ {}, δ, q0 , F ) where:

Q is a finite set of states

Σ is a finite set of input symbols also called alphabet

δ a transition function: P Q × Σ ∪ {} 7→ P Q

q0 ∈ Q initial state

F finite and non-empty set of final states, acceptance states

Note that a non-deterministic finite automata is a special case of an −NFDA where


C(qi ) = {qi }.

Introducción a la teorı́a de gráficas y a los autómatas finitos


34 Finite Deterministic Automata

Example 1.4.5
δ̂(q, ws) = δ(C{δ̂(q, w)}, s)

δ̂(q0 , 1.2) = δ(C{δ̂(q0 , 1.2)}, ) = δ(C{q3 }, ) = δ({q3 , q5 }, ) = δ(q3 , )∪δ(q5 , ) = {q5 }∪{} = {q5 }

δ̂(q0 , 1.2) = δ(C{q2 , q3 }, 2) = δ(q2 , 2) ∪ δ(q3 , 2) ∪ δ(q5 , 2) = {q3 } ∪ {q3 } = {q3 }

δ̂(q0 , 1.) = δ(C{q1 , q4 }, .) = δ(q1 , .) ∪ δ(q4 , .) = {q2 } ∪ {q3 } = {q2 , q3 }

δ̂(q0 , 1) = δ(C({q0 }), 1) = δ({q0 , q1 }, 1) = δ(q0 , 1) ∪ δ(q1 , 1) = {} ∪ {q1 , q4 }

Example 1.4.6 Figure 1.25 shows two equivalent automata, FDA and NFDA.

1.4.4. Automatas with stack = Push-down Automata


Definition 43 Push-down automata PDA.
PDA is a 6-tuple P DA = (Q, Σ ∪ {}, δ, q0 , F ) where:

Q is a finite set of states


Σ is a finite set of input symbols also called alphabet
Γ is a finite set of stack symbols
δ a transition function (p, x, s; q, y)
q0 ∈ Q initial state
F finite and non-empty set of final states, acceptance states
PDA now includes an additional memory space in LIFO format (Last In- First Out)
also called Stack. The stack has its own alphabet and includes the Σ of input symbols
and some additional symbols.
The empty symbol # is used to initialize the stack as empty.

Oscar Herrera Alcántara


1.4. Finite Deterministic Automata 35

Figura 1.25: Automata equivalence, AFD vs AFND. See Brookshear’s book p.47

Nomenclature (p, x, s; q, y) where:

p current state

x current symbols read from the input (tape position)

s symbol at the top of the stack (pop from the stack)

Introducción a la teorı́a de gráficas y a los autómatas finitos


36 Finite Deterministic Automata

q new state

y symbol to be inserted in the stack (push y in the stack)

PDA are non-deterministic. Es lamentable que la terminologı́a común no


haga hincapié en la naturaleza no determinista de los autómatas de pila.

Figura 1.26: PDA See Brookshear’s book p.77

Oscar Herrera Alcántara


1.5. Grammars 37

1.5. Grammars
Definition 44 Grammar. 4-tuple G = {V, T, P, S} where:

V is a finite set of variables or Non-terminals symbols

T is a finite set of terminal symbols

P is a finite set of rules or productions

S is a starting symbol (variable)

1.5.1. Regular grammars


Definition 45 Regular grammar. A grammar where the productions rules satisfies
the conditions:

1. Left side has a single variable

2. Right side has a terminal followed by a single variable, a single terminal or the
empty set.

Example 1.5.1 A regular grammar example with 7 productions:

P 1. Z → yX

P 2. Z → x

P 3. W → 1

P 4. S → xX

P 5. X → yY

P 6. Y → xX

P 7. Y → {}

Theorem 1.5.1 Regular languajes are acepted by AFD and there exist a regular
grammar that accept the same language.

Introducción a la teorı́a de gráficas y a los autómatas finitos


38 Finite Deterministic Automata

Figura 1.27: Automata equivalence, regular grammar vs AFD. See Brookshear’s book
p.54

Figure 1.27 illustrates a regular grammar such that its language is accepted by an
automata with states Q = {S, X, Y } that corresponds to the set of variables V of the
regular grammar.

Theorem 1.5.2 A regular language is accepted by an AFD and there exist a regu-
lar grammar that accepts the same language. L(AFD) = L(G) = Regular language
expressed as a regular expression.

Definition 46 Gramática independiente del contexto GIC. A diferencia de las gramáti-


cas regulares no tienen restricción del lado derecho de las producciones. El lado izquier-
do es una sola variable

El término independiente del contexto refleja que, como el lado izquierdo de cada

Oscar Herrera Alcántara


1.5. Grammars 39

producción únicamente tiene una variable (no está rodeada de nada), ası́ que la regla
puede aplicarse sin importar el contexto donde se encuentre dicha variable.

Theorem 1.5.3 Para cada gramática independiente del contexto GIC, existe un
autómata de pila PDA tal que L(GIC) = L(PDA).

Gramática dependiente del contexto. Una regla como xN y → xzy tiene una variable
rodeada de x por la izquierda además de y por la derecha, ası́ que sólo se puede aplicar
cuando N tenga x − y a sus lados, lo cual lo hace dependiente del contexto.

Example 1.5.2 GIC que genera cadenas de la forma zan zan bm zbm z:

S → zM N z

M → aM a

M →z

N → bN b

N →z

La cadena zazabzbz cumple con esta patrón, y la Figura 1.28 ilustra el árbol de pro-
ducciones (derivación) que la generan.

Figura 1.28: GIC que genera zazabzbz

Introducción a la teorı́a de gráficas y a los autómatas finitos


40 Finite Deterministic Automata

Example 1.5.3 GIC with two rules for variable S:


S → xSy
S → {}
Note that starting variable S has a recursive definition. Recursion requires a stack,
which is consistent with the fact that L(PDA) = L(GIC).
The next algorithm describe how to construct a PDA from a GIC:

Figura 1.29:

1.5.2. Forma Normal de Chomsky FNC para gramaticas


Una gramática independiente del contexto G = (V, T, P, S) que no genera la cadena
vacı́a, está en FNC cuando todas sus reglas son de la forma:
A → BC con A, B, C ∈ V
A → a con A, B ∈ V y a ∈ T
Toda gramática libre de contexto G = (V, T, P, S) que no genere a la cadena vacı́a
se puede transformar en una gramática libre de contexto G0 = (V 0 , T, P 0 , S 0 ) en forma
normal de Chomsky.
Pasos para la transformación de una gramática a la FNC
1. Eliminar reglas unitarias.
2. Eliminar reglas no productivas
3. Dar formato FNC.

Oscar Herrera Alcántara


1.5. Grammars 41

Figura 1.30:

Eliminamos reglas unitarias

A → Ac

A→w

Primero verificamos si en la gramática no hay reglas unitarias que obstruyan el


desarrollo de FNC. Un ejemplo de una regla unitaria seria:

A→X

X→z

Como se puede observar, un No Terminal A deriva en otro No Terminal X, que a su


vez deriva en un Terminal z, esto es redundante y por lo tanto se procede a eliminar
el No Terminal X y pasando el Terminal z al No Terminal A

Introducción a la teorı́a de gráficas y a los autómatas finitos

You might also like