CMP189 Algoritmos Geométricos

Transcription

CMP189 Algoritmos Geométricos
CMP189
Algoritmos
Geométricos
Prof. João Comba
Proximidade
Diagrama de Voronoi (1907)
Planejamento de
movimento
Encontrar o caminho mais curto sem colidir com
paredes e objetos
Sobreposição de Mapas
Sobreposição de Mapas
Algoritmos
Geométricos
Geometria Computacional:
Início na década de 70
Problemas geométricos
Meta: Buscar algoritmos e estruturas de dados com
bom desempenho quando os problemas escalam de
tamanho
Aplicações: Computação Gráfica, Processamento de
Imagens, Robótica, Sistemas Geográficos de
Informação, VLSI, CAD, etc.
Algoritmos
Geométricos
Problemas Típicos:
Entrada: Objetos Geométricos (pontos, linhas,
planos, etc)
Saída: Resultados de consulta sobre os
objetos, ou um novo objeto geométrico
Ingredientes:
Geometria, Topologia, Algoritmos, Estruturas
de dados, Análise de algoritmos, Problemas
numéricos
Algoritmos Geométricos
Limitações Comuns:
Natureza discreta: aproximações discretas de
fenômenos contínuos
Objetos planares ou lineares (aproximações de
objetos curvos)
Permite concentrar em aspectos combinatórios
dos problemas em detrimento de aspectos
numéricos
Problemas de baixa dimensão
Primordialmente 2D (fácil de visualizar) e 3D
(até certos limites)
Histórico da área
• Década de 80:
Desenvolvimento de técnicas eficientes de projeto e
análise de algoritmos
• Década de 90:
Maioria dos problemas abertos foi resolvida
Problema: distância muito grande entre teoria e prática
(muitas das soluções eram quase impossíveis de serem
implementadas ou sensíveis a casos especiais)
• Atualmente:
Simplificar algoritmos existentes, lidar com problemas
numéricos, produzir bibliotecas de procedimentos
geométricos
Projeto de algoritmos
geométricos
1. Projeto de algoritmo básico ignorando
situações especiais (casos degenerados). Ex.
Pontos colineares, segmentos de linha
verticais, etc). Assumir posição geral.
Projeto de algoritmos
geométricos
1. Projeto de algoritmo básico ignorando
situações especiais (casos degenerados). Ex.
Pontos colineares, segmentos de linha
verticais, etc). Assumir posição geral.
2. Lidar com casos degenerados
• Adicionar vários casos especiais
• Modificar o algoritmo original para integrar
casos especiais
Projeto de algoritmos
1. Projeto de algoritmo básico ignorando
situações especiais (casos degenerados).
Ex. Pontos colineares, segmentos de linha verticais, etc).
Assumir posição geral.
2. Lidar com casos degenerados
• Adicionar vários casos especiais
• Modificar o algoritmo original para integrar
casos especiais
3. Implementação
• Usar biblioteca de algoritmos geométricos
• Desenvolver suas próprias classes
Aplicações
• Computação Gráfica:
Interseções entre primitivas
Primitiva apontada pelo mouse
Subconjunto de primitivas dentro de uma região
Remoção de superfícies ocultas em 3D
Cálculos de sombras em ray-tracing e
radiosidade
Detectar colisões entre objetos
Aplicações
• Robótica:
Planejamento de movimento de robô
Planejamento de articulações de robo
Alcance do braço
Orientações das diferentes juntas
Aplicações
• Sistemas Geográficos de Informação:
Representações de dados geográficos:
Topografica, Hidrografica, Separações físicas
e políticas, estradas (mapas diversos)
Dados são muito numerosos
Extrair informações eficientemente:
Qual a média de chuva em uma dada região
Como guiar um carro e definir rotas de
navegação
Sobreposição de mapas
Aplicações
• CAD/CAM:
Placas de Circuitos, Projetos arquitetônicos
Entidades geométricas (problemas geométricos
aparecem)
Interseções e uniões de objetos
Decomposição de objetos em formas mais
simples
Visualização dos objetos projetados
Conteúdo
1. Fundamentos
2. Interseções de Segmentos de Linha
3. Particionamento de Polígonos
4. Envoltórias Convexas
5. Diagramas de Voronoy
6. Triangulações de Delaunay
7. Algoritmos de Busca Pontual e Intervalar
8. Quadtrees, BSP-trees, R-trees
9. Grafos de Visibilidade
10. Planejamento de Movimento
Conteúdo
• Técnicas de Projeto de Algoritmos
Lugares geométricos
Transformações geométricas
Dualidade
Space Sweep
Estruturas Hierárquicas
• Estruturas de Dados:
Cascadeamento Fracional
Estruturas de Dados Persistentes
Estruturas de Dados Cinéticas
Análise caso médio
Avaliação
• Trabalhos teóricos e práticos
• Trabalho Final:
Definido de comum acordo com o aluno / orientador
Alguns temas sugeridos
Sugestões por parte dos alunos são estimuladas
Preferencialmente dentro da área de pesquisa de
mestrado
Resultados esperados:
Artigo técnico mostrando os resultados obtidos (em
inglês)
Apresentação final
• Prova Final
Bibliografia
BIBLIOGRAFIA BÁSICA:
• Computational Geometry: Algorithms and Applications. M. de Berg,
M. van Kreveld, M. Overmars, O. Scwarzkopf. Springer Verlag, 1997.
BIBLIOGRAFIA COMPLEMENTAR:
• Computational Geometry in C. Joseph O’Rourke. Cambridge
•
•
University Press, 1993.
Applications of Spatial Data Structures. Hanan Samet. Academic
Press, 1990.
Ruler, Compass, and Computer: The Design and Analysis of
Geometric Algorithms. Leo Guibas, Jorge Stolfi
• Computational Geometry: Course Notes. David Mount (Univ. Of
Maryland)
• Introduction to Algorithms. Cormen, Leiserson, Rivest. McGraw
Hill.
Exemplo: Envoltória
Convexa
convexo
não convexo
Exemplo: Envoltória
Convexa
Entrada: p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11
Saída : p2,p9,p11,p4,p5,p6,p8,p2
p9
p11
p1
p2
EC é um polígono convexo
p4
p3
p7
p8
p10
p6
p5
Exemplo: Envoltória
Convexa
p9
p11
p4
p1
p2
p3
p7
p8
p10
p5
p6
Envoltória Convexa 1
p9
p11
p4
p1
p2
p3
p7
p8
p10
p6
p5
Envoltória Convexa 1
Algoritmo EC1:
Entrada: Conjunto de pontos P no plano
Saída: Uma lista de vértices da EC em ordem
1. E = ø
2. FOR todos pares (p,q) PxP (p!=q)
3.
4.
DO valido = true
FOR todos pontos r P(r!=p and r!=q)
5.
IF r está a direita da reta pq
6.
THEN valido = false
7. IF valido THEN adicione pq para E
8. Para o conjunto E de arestas, construa uma
lista de vertices classificados em ordem
cronológica
p9
p11
p4
p1
p2
p3
p7
p10
p8
p5
p6
(n2-n)
Envoltória Convexa 1
Algoritmo EC1:
Entrada: Conjunto de pontos P no plano
Saída: Uma lista de vértices da EC em ordem
1. E = ø
2. FOR todos pares (p,q) PxP (p!=q)
3.
4.
DO valido = true
FOR todos pontos r P(r!=p and r!=q)
5.
IF r está a direita da reta pq
6.
THEN valido = false
7. IF valido THEN adicione pq para E
8. Para o conjunto E de arestas, construa uma
lista de vertices classificados em ordem
cronológica
(n2-n) * (n-2) = n3-3n2+2n
p9
p11
p4
p1
p2
p3
p7
p8
p10
p6
p5
Envoltória Convexa 1
Algoritmo EC1:
Entrada: Conjunto de pontos P no plano
Saída: Uma lista de vértices da EC em ordem
1. E = ø
2. FOR todos pares (p,q) PxP (p!=q)
3.
4.
DO valido = true
FOR todos pontos r P(r!=p and r!=q)
5.
IF r está a direita da reta pq
6.
THEN valido = false
7. IF valido THEN adicione pq para E
8. Para o conjunto E de arestas, construa uma
lista de vertices classificados em ordem
cronológica
p9
p11
p4
p1
p2
p3
p7
p10
p8
p5
p6
Como implementar o passo 8 ?
Envoltória Convexa 1
Algoritmo EC1:
Entrada: Conjunto de pontos P no plano
Saída: Uma lista de vértices da EC em ordem
1. E = ø
2. FOR todos pares (p,q) PxP (p!=q)
3.
4.
DO valido = true
FOR todos pontos r P(r!=p and r!=q)
5.
IF r está a direita da reta pq
6.
THEN valido = false
7. IF valido THEN adicione pq para E
8. Para o conjunto E de arestas, construa uma
lista de vertices classificados em ordem
cronológica
n3 -3n2 + 2n + n2 = O(n3)
p9
p11
p4
p1
p2
p3
p7
p8
p10
p6
p5
Complexidade de
Algoritmos
•Modelo: máquina de acesso randômico
instruções sequenciais, sem ops. concorrentes
•Tamanho da entrada
•Tempo de execução:
número de operações
•
•
•
•
Linear (a*n+b)
Quadrático (a*n2+b*n+c)
Cúbico (a*n3+b*n2+c*n+d)
Logarítmico: a * log n
•Tamanho da saída
Complexidade de
Algoritmos
c2 g(n)
c g(n)
f(n)
f(n)
f(n)
c g(n)
c1 g(n)
n0
f(n) = !(g(n))
n0
n0
f(n) = O(g(n))
f(n) = "(g(n))
Primitivas Geométricas
Como testar se um ponto esta a esquerda ou a
direita de uma linha ?
Ex. Ponto (5,7) e linha conectando pontos (2,3)e
(3,8)
Ex. ponto (5,7) e linha 2x + 3y = 5
292
13. Geometry
Primitivas Geométricas
points (x1 , y1 ) and (x2 , y2 ) which lie on it. Lines are also completely described
by equations such as y = mx + b, where m is the slope of the line and b is the
y-intercept, i.e., the unique point (0, b) where it crosses the x-axis. The line l has
Linhas;
slope m = ∆y/∆x = (y1 − y2 )/(x1 − x2 ) and intercept b = y1 − mx1 .
Vertical lines cannot be described by such equations, however, because dividy
= ∆x
mxmeans
+ b dividing by zero. The equation x = c denotes a vertical line that
ing by
crosses the x-axis at the point (c, 0). This special case, or degeneracy, requires
extra attention when doing geometric programming. We use the more general
ax + by + c = 0
formula ax + by + c = 0 as the foundation of our line type because it covers all
possible lines in the plane:
typedef struct
double
double
double
} line;
{
a;
b;
c;
/* x-coefficient */
/* y-coefficient */
/* constant term */
Multiplying these coefficients by any non-zero constant yields an alternate repreMaterial
“Programming
Challenges.
Skienarepresentation
e Revilla
sentation
forde
any
line. We establish
a canonical
by insisting that
the y-coefficient equal 1 if it is non-zero. Otherwise, we set the x-coefficient to 1:
points_to_line(point p1, point p2, line *l)
{
typedef double
struct a;
{
/* x-coefficient */
double
a;
/* y-coefficient
x-coefficient */
*/
double b;
/*
double
b;
/*
y-coefficient
*/
double c;
/* constant term */
/* constant term */
} line; double c;
} line;
Multiplying these coefficients by any non-zero constant yields an alternate repreMultiplying
coefficients
by anya non-zero
yields an
sentation
for these
any line.
We establish
canonicalconstant
representation
byalternate
insisting reprethat
sentation
for any
line.1 We
a canonical
representation
by insistingtothat
the
y-coefficient
equal
if itestablish
is non-zero.
Otherwise,
we set the x-coefficient
1:
the y-coefficient equal 1 if it is non-zero. Otherwise, we set the x-coefficient to 1:
points_to_line(point p1, point p2, line *l)
{points_to_line(point p1, point p2, line *l)
{
if (p1[X] == p2[X]) {
if (p1[X]
== =p2[X])
{
l->a
1;
representação canônica
l->a
=
1;
l->b = 0;
l->b == -p1[X];
0;
l->c
l->c
=
-p1[X];
} else {
} else {l->b = 1;
l->b == -(p1[Y]-p2[Y])/(p1[X]-p2[X]);
1;
l->a
l->a == -(l->a
-(p1[Y]-p2[Y])/(p1[X]-p2[X]);
l->c
* p1[X]) - (l->b * p1[Y]);
l->c
=
-(l->a * p1[X]) - (l->b * p1[Y]);
}
}
}
}
Primitivas Geométricas
point_and_slope_to_line(point p, double m, line *l)
{point_and_slope_to_line(point p, double m, line *l)
{
l->a = -m;
l->a == 1;
-m;
l->b
l->b == -((l->a*p[X])
1;
l->c
+ (l->b*p[Y]));
l->c
=
-((l->a*p[X]) + (l->b*p[Y]));
}
}
• Intersection — Two distinct lines have one intersection point unless they are
• parallel;
Intersection
— Two
lines
have
one intersection
unlessslope
theybut
are
in which
case distinct
they have
none.
Parallel
lines share point
the same
parallel;
in which
case they
have
none. Parallel
lines share the same slope but
have
different
intercepts
and by
definition
never cross.
have different intercepts and by definition never cross.
Primitivas Geométricas
13.1. Lines
293
bool parallelQ(line l1, line l2)
{
return ( (fabs(l1.a-l2.a) <= EPSILON) &&
(fabs(l1.b-l2.b) <= EPSILON) );
}
bool same_lineQ(line l1, line l2)
{
return ( parallelQ(l1,l2) && (fabs(l1.c-l2.c) <= EPSILON) );
}
A point (x! , y ! ) lies on a line l : y = mx + b if plugging x! into the formula for x
yields y ! . The intersection point of lines l1 : y = m1 x + b1 and l2 : y2 = m2 x + b2
is the point where they are equal, namely,
x=
b 2 − b1
,
m1 − m 2
y = m1
b2 − b1
+ b1
m1 − m 2
intersection_point(line l1, line l2, point p)
{
if (same_lineQ(l1,l2)) {
printf("Warning: Identical lines, all points intersect.\n");
(fabs(l1.b-l2.b) <= EPSILON) );
}
bool same_lineQ(line l1, line l2)
{
return ( parallelQ(l1,l2) && (fabs(l1.c-l2.c) <= EPSILON) );
}
Primitivas Geométricas
A point (x! , y ! ) lies on a line l : y = mx + b if plugging x! into the formula for x
yields y ! . The intersection point of lines l1 : y = m1 x + b1 and l2 : y2 = m2 x + b2
is the point where they are equal, namely,
Interseção entre duas linhas
x=
b 2 − b1
,
m1 − m 2
y = m1
b2 − b1
+ b1
m1 − m 2
intersection_point(line l1, line l2, point p)
{
if (same_lineQ(l1,l2)) {
printf("Warning: Identical lines, all points intersect.\n");
13.2. 13.2.
Triangles
and Trigonometry
297
Triangles
and Trigonometry
297
p[X] = p[Y] = 0.0;
return;
}
Solving triangles is the art of deriving the unknown angles and edge lengths of a
Solving
triangles
is the
artmeasurements.
of ==deriving
the problems
unknownfallangles
and
edge lengths of a
triangle given
a subset
of such
into two
categories:
if (parallelQ(l1,l2)
TRUE) {Such
triangle given a printf("Error:
subset of such Distinct
measurements.
Such
problems
fall into two categories:
parallel
lines
do not intersect.\n");
• Given tworeturn;
angles and side, find the rest — Finding the third angle is easy, since
}
the three
angles must sum to 180o = π radians. The Law of Sines then gives us a
• Given
two angles and side, find the rest — Finding the third angle is easy, since
way to find the missing edge lengths.o
p[X]angles
= (l2.b*l1.c
- l1.b*l2.c)
- l1.a*l2.b);
radians. The
Law of Sines then gives us a
the three
must sum
to 180 = /π (l2.a*l1.b
way
to find
the missing
edgefind
lengths.
• Given
sides
and an> angle,
the rest/*—test
If the
angle
lies between
iftwo
(fabs(l1.b)
EPSILON)
for
vertical
line the
*/ two
edges, the Lawp[Y]
of Cosines
gives* us
the way
to find/ the
remaining edge length.
= - (l1.a
(p[X])
+ l1.c)
l1.b;
The
Law
of
Sines
then
enables
us
to
mop
up
the
unknown
angles.
Otherwise,
we
• Given else
two sides and an angle, find the rest — If the
angle
lies between
the two
can use the Law
of
Sines
and
the
angle
sum
property
to
determine
all
angles,
and
p[Y]
= - (l2.agives
* (p[X])
+ l2.c)
/ l2.b;
edges,
the
Law
of
Cosines
us
the
way
to
find
the
remaining
edge
length.
}then the Law of Sines to get the remaining edge length.
The Law of Sines then enables us to mop up the unknown angles. Otherwise, we
and
useA(T
theAny
ofnon-parallel
Sines
the
angle
property
all
•can
Angles
—
lines
each
otherwhere
at a to
given
angle.
Lines
The
area
) Law
of atwo
triangle
T isand
given
byintersect
A(T ) =sum
(1/2)ab,
a isdetermine
the
altitude
andangles,
l
:
a
x
+
b
y
+
c
=
0
and
l
:
a
x
+
b
y
+
c
=
0,
written
in
the
general
form,
1
1
1
1
2
2
2
2
the ofLaw
Sines The
to get
remaining
b isthen
the base
the of
triangle.
basethe
is any
one of theedge
sideslength.
while the altitude is the
intersect
thethird
anglevertex
θ given
distance
from at
the
to by:
this base, as shown in Figure 13.2(r). This altitude
can be easily calculated via trigonometry or the Pythagorean theorem, depending on
a1 b2 − a2 b1
The
A(T )about
of a the
triangle
T is
tangiven
θ = by A(T ) = (1/2)ab, where a is the altitude and
whatarea
is known
triangle.
a1 a2 + b1 b2
b is the
base approach
of the triangle.
Thethe
base
one ofis the
sides
while
the altitude is the
Another
to computing
areaisofany
a triangle
directly
from
its coordinate
For
lines the
inUsing
slope-intercept
form
this
reduces
θ=
(mbe
m1 )/(m
1). This altitude
2−
1 mthe
2 + signed
representation.
linear
algebra
it
can
shown
that
distance
from
third
vertex
toand
thisdeterminants,
base, toastan
shown
in
Figure
13.2(r).
area
A(T
)
of
triangle
T
=
(a,
b,
c)
is
can be easily calculated via trigonometry or the Pythagorean theorem, depending on
what is known about! the triangle.
!
! ax ay 1 !
!
Another approach!! to
computing
the area of a triangle is directly from its coordinate
2 · A(T ) = ! bx by 1 !! = ax by − ay bx + ay cx − ax cy + bx cy − cx by
representation.
Using
linear
algebra
and determinants, it can be shown that the signed
! cx cy 1 !
area A(T
) of triangleonde
T = (a,Tb,é
c) definido
is
AREA(T),
por pontos a, b, c
Área de um triângulo
This formula generalizes
nicely to !compute d! times the volume of a simplex in d
!
! ax ay 1 !
dimensions.
! areas can be! negative, so we must take the absolute value to
Note2that
the) =
signed
! bx by 1 ! = ax by − ay bx + ay cx − ax cy + bx cy − cx by
· A(T
!
compute the actual !!area. This is a feature,
not a bug. We will see how to use the sign
!
c
c
1
x
y
of this area to build important primitives for computational geometry in Section 14.1.
296
This
formula
generalizes nicely to compute
theGeometry
volume of a simplex in d
double
signed_triangle_area(point
a, point d!
b, times
point13.
c)
{
dimensions.
(a[X]*b[Y]
- a[Y]*b[X]
+ a[Y]*c[X]
Note thatreturn(
the signed
areas can
be negative,
so we must take the absolute value to
- a[X]*c[Y] + b[X]*c[Y] - c[X]*b[Y]) / 2.0 );
compute
the
actual
area.
This
is
a
feature,
not
a bug. We will see how to Cuse the sign
}
of this area to build important primitives for computational geometry
in Section 14.1.
b
double triangle_area(point a, point b, point c)
{
double signed_triangle_area(point
a, point b, point c)
return( fabs(signed_triangle_area(a,b,c)) );
A
{ }
return( (a[X]*b[Y] - a[Y]*b[X] + a[Y]*c[X]
c
- a[X]*c[Y] + b[X]*c[Y] - c[X]*b[Y]) / 2.0 );
a
B
}
double triangle_area(point a, point b, point c)
{
Figure 13.2. Notation for solving triangles (l) and
return( fabs(signed_triangle_area(a,b,c)) );
}
Propriedades de Triângulos
ortocentro:
Ponto
de interseção das alturas
Baricentro:
Ponto
de interseção das medianas
Circumcentro:
Centro
da circunferência circunscrita
Incentro:
Ponto de
interseção das 3 bissetrizes
Primitivas Geométricas
O que acontece se os pontos estiverem sobre as
linhas ?
casos degenerados
Uma aresta pq é uma aresta da envoltória
convexa se e somente se todos os outros
pontos da entrada estão estritamente a
direita da linha dirigida entre p e q, ou
eles se ele estão sobre a aresta pq
Primitivas Geométricas
O que acontece se os pontos estiverem sobre as
linhas ?
casos degenerados
q
r
• r está a direita de pq
• p está a direita de rq
• q está a direita de pq
p
Uma aresta pq é uma aresta da envoltória
convexa se e somente se todos os outros
pontos da entrada estão estritamente a
direita da linha dirigida entre p e q, ou
eles se ele estão sobre a aresta pq
Primitivas Geométricas
O que acontece se os pontos estiverem sobre as
linhas ?
casos degenerados
q
r
• r está a direita de pq
• p está a direita de rq
• q está a direita de pq
p
Uma aresta pq é uma aresta da envoltória
convexa se e somente se todos os outros
pontos da entrada estão estritamente a
direita da linha dirigida entre p e q, ou
eles se ele estão sobre a aresta pq
q
r
p
• r está a esquerda de pq
• p está a esquerda de rq
• q está a esquerda de pq
Envoltória Convexa
Incremental
• Abordagem incremental: Adicionar pontos
um por um e atualizar a solucao
p9
p11
•
p4
p1
p2
p3
p7
p10
p8
p5
p6
Envoltória Convexa
Incremental
• Abordagem incremental: Adicionar pontos
um por um e atualizar a solucao
• Classificar os pontos em x, obtendo uma
sequencia ordenada p1, p2, ..., pn
• Calcular a EC superior percorrendo a lista
acima da esquerda para a direita
• Calcular a EC inferior percorrendo a lista
acima da direita para a esquerda
p9
p11
p4
p1
p2
p3
p7
p8
p10
p6
p5
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
p6
p2
p11
p7
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p2
p6
p7
p11
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
p6
p2
p11
p7
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
p2
p6
p7
p11
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p6
p2
p11
p7
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p2
p6
p7
p11
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
p6
p2
p11
p7
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
p2
p6
p7
p11
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p6
p2
p11
p7
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p2
p6
p7
p11
Envoltória Convexa
Incremental
p8
p3
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p6
p2
p11
p7
Envoltória Convexa
Incremental
p3
p8
p10
p5
p1
p9
p4
p2
p6
p7
p11
Envoltória Convexa
Incremental
p3
p8
p10
p5
p1
p9
p4
p6
p2
p11
p7
Envoltória Convexa
Incremental
p3
p8
p10
p5
p1
p9
p4
VIRADA P/ ESQ
p2
p6
p7
p11
Envoltória Convexa
p3
p8
p10
p5
p1
p9
p4
p6
p2
p11
p7
Envoltória Convexa
Incremental
p3
p8
p10
p5
p1
p9
p4
p2
p6
p7
p11
Envoltória Convexa
Incremental
p3
p8
p10
p5
p1
p9
p4
p2
p6
p11
p7
Envoltória Convexa 2
(Grahan's Scan 1972)
Algoritmo EC_GS:
Entrada: Conjunto de pontos P no plano
Saída: Uma lista de vértices da EC em ordem
1. Classificar os pontos pela coordenada x (p1 .. pn)
2. Colocar p1 e p2 na lista L_SUP
3. FOR i:=3 TO n
4. DO Adicionar pi a L_SUP
5.
WHILE L_SUP > 2 pontos e últimos!três fazem uma virada para esquerda
6.
DO delete o penultimo ponto de L_SUP
7. Coloque os pontos pn e pn-1 na lista L_INF
8. FOR i: n-2 DOWNTO 1
9. Repita passos 4-6 com L_INF no lugar de L_SUP10.
10. Remover o primeiro e ultimo pontos de L_SUP e L_INF
11. RETURN Concatenacao de L_SUP e L_INF
Envoltória Convexa 2
Algoritmo EC_GS:
Entrada: Conjunto de pontos P no plano
Saída: Uma lista de vértices da EC em ordem
1. Classificar os pontos pela coordenada x (p1 .. pn)
2. Colocar p1 e p2 na lista L_SUP
3. FOR i:=3 TO n
4. DO Adicionar pi a L_SUP
5.
WHILE L_SUP > 2 pontos e últimos!três fazem uma virada para esquerda
6.
DO delete o penultimo ponto de L_SUP
7. Coloque os pontos pn e pn-1 na lista L_INF
8. FOR i: n-2 DOWNTO 1
9. Repita passos 4-6 com L_INF no lugar de L_SUP10.
10. Remover o primeiro e ultimo pontos de L_SUP e L_INF
11. RETURN Concatenacao de L_SUP e L_INF
O(nlogn) + O(n) = O(nlogn)
Casos Degenerados
O que acontece se 2 pontos possuem a mesma
coordenada x ?
A ordenação na coordenada x é incorreta
p1
p2
p2
p1
O que acontece se 3 pontos são colineares ?
p1
p2
não aparece na envoltória convexa
p3
Problema 1
Resolver Ex. 681: Convex Hull Finding
http://acm.uva.es/p/v6/681.html
Data 18/3 (Mandar e-mail com aceitação Em
Valladolid
Gift Wrapping
p3
p8
p10
p5
p1
p9
p4
p2
p6
p7
p11
Gift Wrapping
1.
Find point with smallest y
coordinate
p3
p8
p10
p5
p1
p9
p4
p6
p2
p11
p7
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p3
p8
p10
p5
p1
p9
p4
3. Repeat until reach last vertex
p2
p6
p7
p11
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p3
p8
p10
p5
p1
p9
p4
3. Repeat until reach last vertex
p6
p2
p11
p7
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p8
p3
p10
p5
p1
p9
p4
3. Repeat until reach last vertex
p2
p6
p7
p11
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p3
p8
p10
p5
p1
p9
p4
3. Repeat until reach last vertex
p6
p2
p11
p7
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p3
p8
p10
p5
p1
p9
p4
3. Repeat until reach last vertex
p2
p6
p7
p11
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p3
p1
p8
p10
p5
p9
p4
3. Repeat until reach last vertex
p6
p2
p11
p7
Gift Wrapping
1. Find point with smallest y
coordinate
2. Find edge that minimizes
counter-clockwise angle with
respect to supporting line
p3
p1
p10
p5
p9
p4
3. Repeat until reach last vertex
p2
O(n2)
p8
p6
p7
p11
Quickhull
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
1.
2.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
Quickhull
1.
2.
3.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
1.
2.
3.
4.
5.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p10
p5
p9
p4
p6
p2
p11
p7
a
Quickhull
1.
p8
B
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
T(n) = O(n) + T(a) + T(b)
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
Quickhull
T(n) = O(n) + T(a) + T(b)
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
T(n) = O(n) + 2T(n/2)
Quickhull
T(n) = O(n) + T(a) + T(b)
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
T(n) = O(n) + 2T(n/2) -> O(nlogn)
Quickhull
T(n) = O(n) + T(a) + T(b)
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p6
p2
p11
p7
T(n) = O(n) + 2T(n/2) -> O(nlogn)
T(n) = O(n) + T(n-1)
Quickhull
T(n) = O(n) + T(a) + T(b)
1.
2.
3.
4.
5.
6.
Find extreme points above,
below, left and right
Define a quadrilateral
connecting extreme points,
discard internal points
Process 4 triangles
recursively
For each triangle, find
vertex with greater distance
from the triangle baseline.
Define another triangle and
discard internal triangles
Process 2 triangles
recursively
p3
p1
p8
p10
p5
p9
p4
p2
p6
p7
p11
T(n) = O(n) + 2T(n/2) -> O(nlogn)
T(n) = O(n) + T(n-1) ->O(n2)
Divide-and-Conquer
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p10
p8
p5
p6
Divide-and-Conquer
1.
2.
3.
4.
•
•
•
•
Sort points in X
Divide points in two sets A
and B with similar number of
elements
Compute Convex Hull of A
and B recursively
Merge A and B to define
convex hull
Find lower tangent common
to A and B
Find rightmost point a of A
and leftmost point b of B
While ab is not lower
tangent to a, decrease a
While ab is not lower
tangent of b, decrease b
p9
p11
p4
p1
p3
p7
p8
p10
p5
p6
3
4
2
1
5
6
11
12
13
14
10
9
17
15
16
7
8
Left ch
Right ch
e1
e2
e7
e13
e3
e8
e12
e9
e4
e10
e6
e5
e11
1
2
3
4
5
6
7
8
10
9
11
12
13
14
15