Lecture Notes CMSC M

CMSC M Computer Graphics

Spring

DaveMount

Lecture Intro duction

Tuesday Sep

What is Computational geometry is a term claimed bya number

of dierent groups The term was coined p erhaps rst by Marvin Minsky in his b o ok Percep

trons whichwas ab out pattern recognition and has b een used often to describ e

solidmo deling But its most widely recognized use is to describ e the subeld of

theory that involves the design and analysis of ecient algorithms for problems involving geo

metric inputs primarily in or p erhaps consant dimensional spaces It primarily involves

straight or at ob jects lines line segments p olygons planes and p olyhedra as opp osed to

curves and surfaces It is this latter sense of the term that we will b e covering in this course

The eld develop ed rapidly in the late s and through the s and s and it still continues

to develop Because of the area from which it grew discrete algorithm design the eld of

computational geometry has always emphasized problems of a discrete mathematic nature For

most problems in computational geometry the input is a nite set of p oints or other geometric

ob jects and the output is a typically some sort of structure consisting of a nite set of p oints

or line segments

Here is an example of a typical problem called the shortest path problemGiven a set p olygonal

obstacles in the plane nd the shortest obstacleavoiding path from some given start p oint

toagiven goal p oint Although it is p ossible to reduce this to a shortest path problem on a

graph called the visibility graphwhichwe will discuss later this semester and then apply a

nongeometric algorithm such as Dijkstras algorithm it seems that by solving the problem in

its geometric domain it should b e p ossible to devise more ecient solutions This is one of the

main reasons for the growth of interest in geometric algorithms

s t s t

Figure Shortest path problem

The measure of the quality of an algorithm in computational geometry has traditionally b een

its asymptotic worstcase running timeThus an algorithm running in O n time is b etter than

one running in O n log n time which is b etter than one running in O n time This particular

problem can b e solved in O n log ntimeby a fairly simple algorithm and in O n log nby

avery complex algorithm In some cases average case running time is considered instead

Copyright David M Mount Dept of Computer Science University of Maryland College Park MD

These lecture notes were prepared byDavid Mount for the course CMSC Computational Geometryat

the University of Maryland College Park Permission to use copymodify and distribute these notes for educational

purp oses and without fee is hereby granted provided that this copyright notice app ear in all copies

Lecture Notes CMSC M

However for manytyp es of geometric inputs it is dicult to dene input distributions that

are b oth easy to analyze and representativeoftypical inputs

There are many elds of computer science that deal with solving problems of a geometric

nature These include computer graphics computer vision and image pro cessing rob otics

computeraided design and manufacturing computational uiddynamics and geographic in

formation systems to name a few One of the goals of computational geometry is to provide

the basic geometric to ols needed from which application areas can then build their programs

There has b een signicant progress made towards this goal but it is still far from b eing fully

realized

Limitations of Computational Geometry There are some fairly natural reasons why compu

tational geometry maynever fully address the needs of all these applications areas and these

limitations should b e understo o d b efore undertaking this course One is the discrete naturea

of computational geometry In some sense any problem that is solved on digital computers

must b e expressed in a discrete form but many applications areas deal with discrete approx

imations to continuous phenomenon For example in image pro cessing the image maybea

discretization of a continuous dimensional grayscale function and in rob otics issues of vibra

tion oscillation in dynamic control systems are of a continuous nature Nonetheless there are

many applications in which ob jects are of a very discrete nature For example in geographic

information systems road networks are discretized into collections of line segments

The other limitation is the fact that computational geometry deals primarily with straightor

at ob jects To a large extent this is a result of the fact that computational geometers were

not trained in geometry but in discrete algorithm design So they chose problems for which

geometry and numerical computation plays a fairly small role Much of solid mo deling uid

dynamics and rob otics deals with ob jects that are mo deled with curved surfaces However it

is p ossible to approximate curved ob jects with piecewise planar p olygons or p olyhedra This

assumption has freed computational geometry to deal with the combinatorial elements of most

of the problems as opp osed to dealing with numerical issues This is one of the things that

makes computational geometry fun to studyy ou do not have to learn a lot of analytic or

dierential geometry to do it But it do es limit the applications of computational geometry

One more limitation is that computational geometry has fo cused primarily on dimensional

problems and dimensional problems to a limited extent The nice thing ab out dimensional

problems is that they are easy to visualize and easy to understand But many of the daunting

applications problems reside in dimensional and higher dimensional spaces Furthmore issues

related to top ology are much cleaner in and dimensional spaces than in higher dimensional

spaces

Trends in CG in the s and s In spite of these limitations there is still a remarkable array

of interesting problems that computational geometry has succeeded in addressing Throughout

the s the eld develop ed many techniques for the design of ecient geometric algorithms

These include wellknown metho ds such as divideandconquer and

along with a numb er of newly discovered metho ds that seem to b e particularly well suited

to geometric algorithm These include planesweep randomized incremental constructions

dualitytransformations and fractional cascading

One of the ma jor fo cuses of this course will b e on understanding technique for designing

ecient geometric algorithms A ma jor part of the assignments in this class will consist of

designing andor analyzing the eciency of problems of a discrete geometric nature

However throughout the s there a nagging gap was growing b etween the theory and

practice of designing geometric algorithms The s and early s sawmany of the op en

problems of computational geometry solved in the sense that theretically optimal algorithms

Lecture Notes CMSC M

were develop ed for them However many of these algorithms were nightmares to implement

b ecause of the complexity of the algorithms and the data structures that they required Fur

thermore implementations that did exist were often sensitive to geometric degeneracies that

caused them to pro duce erroneous results or ab ort For example a programmer designing

an algorithm that computes the intersections of a set of line segments may not consider the

situation when three line segments intersect in a single p oint In this rare situation the data

structure b eing used may b e corrupted and the algorithm ab orts

Much of the recentwork in computational geometry has dealt with trying to make the the

oretical results of computational geometry accessible to practioners This has b een done by

simplifying existing algorithms dealing with geometric degeneracies and pro ducing libraries

of geometric pro cedures This pro cess is still underway Whenever p ossible we will discuss the

simplest known algorithm for solving a problem Often these algorithms will b e randomized

algorithms We will also discuss hop efully without getting to o b ogged down in details some

of the techniques for dealing with degenerate situations in order to pro duce clean and yet

robust geometric software

A Grand Overview Here are some of the topics that we will discuss this semester

Convex Hulls Convexityisavery imp ortant geometric prop erty A geometric set is convex

if for every two p oints in the set the line segment joining them is also in the set One of

the rst problems identied in the eld of computational geometry is that of computing

the smallest convex shap e called the convex hul l that encloses a set of p oints

Convex hull Polygon triangulation

Figure Convex hulls and p olygon triangulation

Intersections One of the most basic geometric problems is that of determining when two sets

of ob jects intersect one another Determining whether complex ob jects intersect often

reduces to determining which individual pairs of primitiveentities eg line segments

intersect We will discuss ecient algorithms for computing the intersections of a set of

line segments

Triangulation and Partitioning Triangulation is a catchword for the more general prob

lem of sub dividing a complex domain into a disjoint collection of simple ob jects The

simplest region into which one can decomp ose a planar ob ject is a triangle a tetrahedron

in d and simplex in general We will discuss how to sub divide a p olygon into triangles

and later in the semester discuss more general sub divisions into trap ezoids

Lowdimensional Linear Programming Many optimization problems in computational

geometry can b e stated in the form of a linear programming problem namely nd the

extreme p oints eg highest or lowest that satises a collection of linear inequalities

Linear programming is an imp ortant problem in the combinatorial optimization and

p eople often need to solvesuch problems in hundred to p erhaps thousand dimensional

spaces However there are manyinteresting problems eg nd the smallest disc enclosing

a set of p oints that can b e p osed as low dimensional linear programming problems In

lowdimensional spaces very simple ecient solutions exist

Lecture Notes CMSC M

Line arrangements and duality Perhaps one of the most imp ortant mathematical struc

tures in computational geometry is that of an arrangement of lines or generally the

arrangement of curves and surfaces Given n lines in the plane an arrangement is just

the graph formed by considering the intersection p oints as vertices and line segments join

ing them as edges We will show that such a structure can b e constructed in O n time

These reason that this structure is so imp ortantisthatmany problems involving p oints

can b e transformed into problems involving lines by a metho d of dualityFor example

supp ose that you want to determine whether any three p oints of a planar p oint set are

collinear This could b e determines in O n time by bruteforce checking of each triple

However if the p oints are dualized into lines then as we will see later this semester

this reduces to the question of whether there is a vertex of degree greater than in the

arrangement

Voronoi Diagrams and DelaunayTriangulations Given a set S of p oints in space one

of the most imp ortant problems is the nearest neighb or problem Given a p ointthatisnot

in S whic p ointofS is closest to it One of the techniques used for solving this problem

is to sub divide space into regions according to whichpoint is closest This gives rise to a

geometric partition of space called a This geometric structure arises in

many applications of geometry The dual structure called a Delaunay triangulation also

has manyinteresting prop erties

Figure Voronoi diagram and Delaunay triangulation

Search Geometric search problems are of the following general form Given a data set eg

points lines p olygons which will not change prepro cess this data set into a data struc

ture so that some typ e of query can b e answered as eciently as p ossible For example

a nearest neighbor search query is determine the p oint of the data set that is closest to a

given query p oint A range query is determine the set of p oints or countthenumber of

points from the data set that lie within a given region The region may b e a rectangle

disc or p olygonal shap e like a triangle

Course Texts The text for this course is the excellent new b o ok Computational Geometry

Algorithms and Applications bydeBergvan Kreveld Overmars and Schwarzkopf Many

of the algorithms notations denitions and gures will b e b orrowed from their presen

tation Well refer to their b o ok by their initials BKOS Well also refer to the excellent

algorithms textb o ok Introduction to Algorithms by Cormen Leiserson and Rivest for

basic algorithms and data structures

Lecture Geometric Background and Convex Hulls

Thursday Sep

Up dated pm Sep

Reading Chapter in BKOS deBerg vanKreveld Overmars and Schwarzkopf

Lecture Notes CMSC M

Ane space We will usually b e rather informal in our presentation of geometry but it is go o d to

start things o on a somewhat formal fo oting We b egin with some background on Euclidean

geometry which is not presented in the text

There are a numb er of dierent geometric systems that one can work under This semester

wewillbeworking almost exclusively with Euclidean geometry although wemayintro duce a

few concepts from pro jective geometry later in the semester We b egin with a short review of

geometry Our approach will b e dierent from what is done in most math texts and most com

putational geometry texts The standard approach in math texts is to b egin by assuming that

everything is a tuple of real numb ers But this approach do es lend itself to ob jectoriented

programming b ecause it blurs the distinction b etween dierent geometric elements The ap

proach in computational geometry texts is to say nothing ab out geometric representations but

to rely up on an intuitive understanding of geometric concepts

Rather than dening Euclidean geometry we will rst dene a somewhat more basic geome

try called ane geometry Later we will add one op eration called an inner pro duct which

dierentiates Euclidean from ane geometry

An ane geometry consists of a set of scalars the real numb ers a set of points and a set

of freevectors or simply vectors Points are used to sp ecify p osition Free vectors are used

to sp ecify direction and magnitude but have no xed p osition in space This is in contrast

to linear algebra where there is no real distinction b etween p oints and vectors However this

distinction is useful since the two are really quite dierent

The following are the op erations that can b e p erformed on scalars p oints and vectors Vector

op erations are just the familiar ones from linear algebra It is p ossible to subtract two p oints

The dierence p q of twopoints results in a free vector directed from q to p It is also

p ossible to add a p ointtoavector In p ointvector addition p v results in the p ointwhich

is translated by v from p The following are the legal op erations

S V V scalarvector multiplication

V V V vector addition

P P V p oint subtraction

P V P pointvector addition

u+v q u p+v p-q p v p v

vector addition point subtraction point-vector addition

Figure Ane op erations

Anumb er of op erations can b e derived from these For example we can dene the subtraction

of twovectors u v as u v or scalarvector division v as v provided There

is one sp ecial vector called the zerovector which has no magnitude suchthatv v

Note that it is not p ossible to multiply a p oint times a scalar or to add twopoints together

However there is a sp ecial op eration that combines these two elements called an ane combi

nation Given any scalar and twopoints p and p dene the ane combination A p p

Lecture Notes CMSC M

to b e

p p p p p

Note that the lefthand side of this equation is not legal given our list of op erations But

this is how the ane combination is typically expressed namely as the weighted average of

two p oints The righthand side which is easily seen to b e algebraically equivalent is legal

An imp ortant observation is that if p p then the p ointAp p lies on the line

connecting p and p and generallyas varies from to it traces out all the p oints

on this line Aff(p,q,-1/2) Aff(p,q,0) Aff(p,q,1/2) p Aff(p,q,1)

q

Figure Ane combination

In the sp ecial case where A p p isapoint that sub divides the line segment

p p into two subsegments of relative sizes to When is in this range the op eration is

called a convex combination and the set of all convex combinations traces out the line segment

p p

Homogeneous Co ordinates In order to assign co ordinates to p oints and vectors we assume that

there is a designated standardcoordinate system whichisspeciedbyanoriginpoint and d

orthogonal unit vectors In many applications such as computer graphics and solid mo deling

it is often convenient to dene other lo cal co ordinate systems Wewillnothavemuch need of

this though

To representvectors and p oints in ane space we use homogeneous coordinates Supp ose that

we are working in ddimensional ane space It is common to represent b oth free vectors and

p oints as d tuples of real numbers To represent a free vector wetake its standard dtuple

of co ordinates an prep end an additional to the b eginning To representapointwetake its

dtuple and prep end an additional In many application areas graphics and solidmo deling

in particular it is common to app end the or to the end of the tuple In principal there

is no reason that one representation is b etter than the other but b eware that the concept of

orientation dened b elowisreversed in o dd dimensions in this case

This may sound rather adho c but it has some very nice algebraic prop erties For example

if you take the dierence of twopoints which results in a free vector observethatby simply

subtracting their homogeneous co ordinate tuples comp onentby comp onen t you will get the

prop er representation of this free vector since the rst two co ordinates will cancel each other

giving We will sometimes b e sloppy When it is clear that we are dealing with p oints we

may drop the homogenizing co ordinate

Orientation So far all of the op erations map numerical geometric entities into other numerical

entities In order to make discrete decisions we need a geometric op eration that is somewhat

analogous to the relational op erations with numb ers There do es not seem to b e

any natural intrinsic waytocomparetwo p oints in ddimensional space but there is a natural

relation b etween ordered d tuples of p oints in dspace which extends the notion of

relations in space called orientation

Lecture Notes CMSC M

v: (0, 2, 1) v p p : (1, 2, 2) p-q q : (1, 3, 0) p-q : (1-1, 2-3, 2-0) = (0, -1, 2)

q

Figure Homogeneous co ordinates

Given an ordered triple of three p oints hp q r i in the plane wesay that they have positive

orientation if they dene a counterclo ckwise oriented triangle negative orientation if they

dene a clo ckwise oriented triangle and zero orientation if they are collinear Note that

orientation dep ends on the order in whichthepoints are given In general given an ordered

tuple p oints in space we can also dene their orientation as b eing either p ositive forming a

righthanded screw negative a lefthanded screw or zero coplanar This can b e generalized

to any ordered d tuple p oints in dspace r q q q r

p p p r

positive zero negative

Figure Orientations of the ordered triple p q r

Orientation is formally dened as the sign of the determinant of the p oints given in homoge

neous co ordinates For example in the plane wehave

p p

x y

A

Orientp q r det q q

x y

r r

x y

Observe that in the dimensional case Orientp q isjust q p Hence it is p ositiveifpq

zero if p q and negativeifp qThus orientation generalized in dimensional

space

Convexity Now that wehave discussed some of the basics let us consider an initial problem The

computation of convex hulls is among the most basic problems in computational geometryAn

O n log n algorithm for computing convex hulls was one of the earliest results in computational

geometry due to Ron Graham

The convex hull can b e dened intuitively by surrounding a collection of p oints with a rubb er

band and letting the rubb er band snap tightly around the p oints There are a n umber of

reasons that the convex hull of a p oint set is an imp ortant geometric structure One is that it

is one of the simplest shap e approximations for a set of p oints Also many algorithms compute

the convex hull as an initial stage in their execution b ecause convex p olygons are often easier

to deal with than p oint sets For example in order to nd the smallest rectangle or triangle

that encloses a set of p oints it suces to rst compute the convex hull of the p oints and then

nd the smallest rectangle or triangle enclosing the hull

Lecture Notes CMSC M

Convexity Aset S is convex if given anypoints p q S anyconvex combination of p and q

is in S or equivalently the line segment pq S

Convex hull The convex hul l of any set S is the intersection of all convex sets that contains

S ormoreintuitively the smallest convex set that contains S Following our b o oks

notation we will denote this CHS

An equivalent denition of convex hull is the set of p oints that can b e expressed as convex

combinations of the p oints in S A pro of can b e found in any book on convexitytheory A

convex combination of three or more p oints is an linear combination of the p oints in which the

co ecients sum to and all the co ecients are in the interval

In general convex sets mayhave either straight or curved b oundaries may b e b ounded or

unb ounded eg an innite cone is convex and may b e top ologically op en or closed that

is they mayormay not contain their b oundary The convex hull of a nite set of p oints is

necessarily a b ounded closed convex p olygon

Convex hull problem The planar convex hul l problem is given a set of n points P in the plane

output the vertices of the convex hull Normally p olygons are presented in counterclo ckise

order For some reason our b o ok outputs the hull in clo ckwise order but obviouslyitisa

trivial matter to convert from one to the other The hull should consist only of extreme points

in the sense that if three p oints lie on an edge of the convex hull then the middle p oint should

not b e output as part of the hull

The b o ok intro duces a simple O n convex hull algorithm whichoperatesby considering each

ordered pair of p oints p q and the determining whether all the remaining p oints of the set

lie within the halfplane lying to the right of the directed line from p to q Observe that this

can b e tested using the orientation test The question is can we do b etter

Grahams scan We will presentanO n log n algorithm for convex hulls It is a simple variation

of a famous algorithm for convex hulls called Grahams scan This algorithm dates backtothe

early s The algorithm is based on an approach called incremental constructioninwhich

p oints are added one at a time and the hull is up dated with each new insertion If wewere to

add p oints in some arbitrary order wewould need some metho d of testing whether p oints are

inside the existing hull or not Toavoid the need for this test we will add p oints in increasing

order of xco ordinate thus guaranteeing that each newly added p oint is outside the current

hull It is not clear that this is necessarily a go o d thing to do After all if a p oint is inside

the convex hull then no up date need b e made Perhaps a b etter algorithm should seek to add

p oints in suchaway that most of the p oints that are not on the hull are eliminated quickly

from consideration Nonetheless Grahams scan is easy to implement and is optimal in the

worst case so it is not a bad algorithm byany means

Since weareworking from left to right it would b e convenient if the convex hull vertices were

also ordered from left to right The convex hull is a cyclically ordered sets Cyclically ordered

sets are somewhat messier to work with than simple linearly ordered sets so we will break the

hull into twohulls an upper hul l and lower hul l The break p oints common to b oth hulls will

b e the leftmost and rightmost vertices of the convex hull After building b oth the twohulls

are merged into a single cyclic list

Let us consider the upp er hull since the lower hullissymmetricLet hp p p i denote

n

the set of p oints sorted by increase xco ordinates As wewalk around the upp er hull from left

to right observe that each consecutive triple along the hull makes a righthand turn That

is if p q r are consecutivepoints along the upp er hull then Orientp q r When a new

p oint p is added to the currenthull this may violate the righthand turn invariant So we

i

check the last three p oints on the upp er hull including p They fail to form a righthand turn

i

Lecture Notes CMSC M

Upper hull p i

p n p 1

Lower hull

Figure Convex hulls and Grahams scan

then we delete the p oint prior to p This is rep eated until the numberofpoints on the upp er

i

hull including p is less than three or the righthand turn condition is reestablished See the

i

text for a complete description of the co de Wehave ignored a numb er of sp ecial cases We

will consider these next time

Analysis Let us prove the main result ab out the running time of Grahams scan

Theorem Grahams scan runs in O n log ntime

Pro of Sorting the p oints according to xco ordinates can b e done byany ecient sorting

algorithm in O n log n time For each p oint added the amount of time sp ent is clearly

O D where D is the numberofpoints deleted in the pro cess of adding p oint p

i i i

The reason is that each orientation test takes constant time and wemust p erform one

orientation test for eachpoint deleted p erhaps along with one extra one for the last p oint

P

n

which is not deleted Thus the total running time is prop ortional to D

i

i

P P

n

D How large is D Observe that once a p oint is deleted it can never b e n

i i

i i

P

deleted again Since eachofn points can b e deleted at most once D nThus after

i

i

sorting the total running time is O n Since this is true for the lower hull as well the

total time is O n O n

Lecture More Convex Hulls

Tuesday Sep

Reading Chapter in BKOS

Degeneracies Last time we presented the Grahams scan algorithm for computing convex hulls

Recall that the algorithm computes just the upp er and lower hulls of a set of n points each

in O n log n time The metho d is an incremental algorithm that adds p oints to the hull in

increasing order of xco ordinate

One of the issues that we neglected to deal with was that of degenerate inputs A degeneracy

is somewhat hard to dene formallybuta working denition is that a degeneracy is any

sp ecial conguration of p oints lines etc that will b e broken with very high probability

if the ob jects dening co ordinates are randomly p erturb ed F or example three p oints form

a degeneracy in all dimensions strictly higher than since any p erturbation of any their

co ordinates will cause the orientation test to b ecome nonzero

Of course we are only interested in degeneracies that aect the algorithm of interest A

functional denition of degeneracy is any conguration of p oints that causes a sign test based

on real values such as the orientation test to return a zero value

Let us b egin by assuming that we p erform all sign tests using exact arithmetic There are two

places in Grahams algorithm where degeneracies might arise The rst is that in sorting the

Lecture Notes CMSC M

p oints by their xco ordinates there maybetwopoints with the same xco ordinate The second

is when adding a p oint p and testing the last three consecutive p oints for the righthand turn

i

condition the three p oints may b e collinear

For the case of equal xco ordinates there is a very simple metho d for dealing with this that is

well worth rememb ering We will imagine that an innitesimal p erturbation has b een applied

to the p oints Such a p erturbation should have the prop erty of destroying degeneracies but

creating no new degeneracies For example to break ties in xco ordinates we could apply a small rotation of the plane

Before perturbation After perturbation

Figure Perturbation to eliminate degeneracies

If we rotate to o much we might create a new tie among xco ordinates How small is small

enough Howmuchnumerical precision is needed The trick is that we do not actually

compute the p erturbation numerically Instead we p erform the computation on the original

exact inputs but make all decisions as if this rotation had b een applied This technique of

simulating a p erturbation is called symbolic perturbation

For example supp ose that we rotate all the p oints innitesimally clo ckwise ab out the origin

of the co ordinate system If twopoints had the same xco ordinate prior to the rotation then

the one with the larger y co ordinate will have the larger xco ordinate after the rotation Since

the rotation is innitesimal innitely small then no new ties amongst xco ordinates will b e

created Tosimulate the p erturbation we simply sort the p oints lexicographical ly rst by

xco ordinate and then amongst p oints with the same xco ordinate by y co ordinate They

key is that the p oints have not actually b een rotated numerically but the algorithm b ehaves

as if they had b een

We could have p erturb ed the p oints byacounterclo ckwise rotation as well either would b e

ne This p erturbation also takes care of the question of where the upp er hull ends and the

lo wer hull b egins if there are ties for the leftmost and rightmost p oints

To deal with three collinear p oints observe that since the p oints are sorted by xco ordinate

as we visit them the middle p ointofanysuch triple should not b e considered as lying on

the hull So when implementing the righthand turn condition we should require that it is a

strict righthand turn otherwise the middle p oint is deleted

If wewere to use oating p oint arithmetic the b est we could hop e for is an approximation

to the convex hull in the sense that if that the hull weoutputwould b e the correct hull for

some small p erturbation of the input When dealing with oating p oint computation the

most imp ortant goal is that numerical errors should never cause the program to pro duce an

output that is structurally unsound For convex hulls this is not to o complex However for

other geometric problems it may b e quite hard to devise an algorithm that insensitive to small

numerical errors

Lecture Notes CMSC M

Quickhull Toshow that there is not just one way to compute planar convex hulls let us consider

some other approaches The rst is called quickhul l and can b e viewed as a dimensional

generalization of quicksort

Likequicksort this algorithm runs in O n log n time for favorable inputs but can take as long

as O n time for unfavorable inputs However unlikequicksort there is no obvious wayto

convert it into a randomized algorithm with O n log n exp ected running time Nonetheless

quickhull tends to p erform very well in practice

The intuition is that in many applications most of the p oints lie in the interiorofthehull For

example if the p oints are uniformly distributed in a unit square then the exp ected number of

p oints on the convex hull is O log n Here is a pro of

Theorem Supp ose that n points are uniformly distributed in a unit square The exp ected

number of points on the convex hull is O log n

Pro of First we will break the hull into four parts the upp erleft upp erright lowerleft and

lowerrighthulls This is done by breaking the hull at its leftmost rightmost topmost

and b ottommost p oints We will show that eachhasO log n p oints By symmetrywe

may consider one say the upp errighthull

Rather than b ounding the numberofpoints on the hull we will b ound a larger quantity

A p oint p x y issaidtobe dominated by another p oint p if x x and y y

i i i j j i j i

The maxima of a p ointset P are the p oints that are not dominated byany other p oint

in P Intuitively the maxima form a staircase along the upp erright side of the p oint set

Observe that the set of maxima is a sup erset of the p oints on the upp errighthull so an

upp er b ound on the numb er of maxima is an upp er b ound on the numb er of p oints in

the upp errighthull

Upper-right hull

Maxima

Figure Upp errighthull and maxima

Supp ose that the p oints are sorted in decreasing order of xco ordinate We will assume

that all p oints have distinct co ordinates to simplify things Clearly p is a maximum if

i

and only if p has the largest y co ordinate among the subset fp p p g What is

i i

the probability that this is true The y co ordinates of these p oints are indep endent from

each other Therefore the probability that p has the largest y co ordinate is just i

i

Thus each p oint p is a maxima with probabilityi The exp ected numb er of maxima

i

is

n

X

ln n O log n E

n

i

i

The sum is the harmonic series see Cormen Leiserson and Rivest if you havent seen

this From the comments made earlier it follows that the exp ected number of points on

all the hulls is at most times this quantity whichisO log n

Lecture Notes CMSC M

The idea b ehind quickhull is to discard p oints that are not on the hull as quickly as p ossi

ble QuickHull b egins by computing the p oints with the maximum and minimum x and

y co ordinates Clearly these p oints must b e on the hull Horizontal and vertical lines passing

through these p oints are supp ort lines for the hull and so dene a b ounding rectangle within

which the hull is contained Furthermore the convex quadrilateral dened by these four p oints

lies within the convex hull so the p oints lying within this quadrilateral can b e eliminated from

further consideration All of this can b e done in O n time

discard these

Figure Quickhulls initial quadrilateral

To continue the algorithm we classify the remaining p oints into the four corner triangles

that remain In general as this algorithm executes we will have an inner convex p olygon

and asso ciated with eachedgewehave a set of p oints that lie outside of that edge More

formally these p oints are witnesses to the fact that this edge is not on the convex hull b ecause

they lie outside the halfplane dened by this edge When this set of p oints is empty the edge

isanaledgeofthehull Consider some edge ab Assume that the p oints that lie outside

of this hull edge have b een placed in a bucket that is asso ciated with ab Our job is to nd

apoint c among these p oints that lies on the hull discard the p oints in the triangle abc and

split the remaining p oints into two subsets those that lie outside ac and those than lie outside

of cbWe can classify each p ointby making two orientation tests c b b

discard these

a a

Figure Quickhull elimination pro cedure

How should c b e selected There are a numb er of p ossible selection criteria that one might

think of The suggested metho d is that c be the point that maximizes the p erp endicular

distance from the line ab Another p ossible choice mightbethepoint that maximizes the

angle cba or cab It turns out that these are p o or choices b ecause they do not pro duce even

splits of the remaining p oints We replace the edge ab with the two edges ac and cb and

classify the p oints as lying in one of three groups those that lie in the triangle abcwhich are

discarded those that lie outside of ac and those that lie outside of cbWe put these p oints in

buckets for these edges and recurse We claim that it is not hard to classify each p oint pby

computing the orientations of the triples acp and cbp

The running time of quickhull as with quicksort dep ends on howevenly the p oints are split

at each stage Let T n denote the running time on the algorithm assuming that n p oints

remain outside of some edge In O n time we can select a candidate splitting p oint c and

classify the p oints in the bucket in O n time Let n and n denote the numb er of remaining

Lecture Notes CMSC M

p oints Then the running time is given by the recurrence

T

T n T n T n n

To solve the recurrence it would b e necessary to determine the exp ected values of n n

whichwould dep end on the p oint distribution If we assume that the p oints are evenly dis

tributed in the sense that maxn n n for some constant then by applying the

same analysis as that used in quicksort see Cormen Leiserson Rivest the running time will

solveto O n log n where the constant factor dep ends on

Do es quickhull outp erform Grahams scan This dep ends to a great extent on the distribution

of the p oint set There are variations of quickhull that are designed for sp ecic p oint distribu

tions eg p oints uniformly distributed in a square and their authors claim that they manage

to eliminate almost all of the p oints in a matter of only a few iterations

Other convex hull algorithms There are still other convex hull algorithms A natural question

In fact it is p ossible to show that to ask is whether it is p ossible to improveon O n log n

any algorithm for convex hulls must at least sort the p oints along the hull Well leave this as

an exercise In the worst case the hull has n p oints and so this implies an n log nlower

b ound

Butifyou know or exp ect fewer p oints on the hull then you maybeabletodomuch b etter

For example if your inputs consist of p oints uniformly distributed in a square then you exp ect

the numb er of p oints on the hull to b e only O log n Is it p ossible to nd a b etter algorithm

in this case An algorithm that takes into consideration b oth the input and output size is

called an output sensitive algorithm Let n denote the number of input points and h denote

the numb er of edges on the convex hull

There is an algorithm called Jarviss march which builds the hull in O nh time by a pro cess

called giftwrapping In O n time it is p ossible to nd the next edge on the hull and

this algorithm op erates bywalking around the hull one edge at a time But this gives no

improvement for the case of uniformly distributed p oints in the square Nonetheless manyof

the most practical higher dimensional convex hull algorithms are based on this approac h

There exists an O n log h time algorithm for the convex hull problem and it can b e shown

that this algorithm is optimal with resp ect to output sensitive algorithms The st algorithm

with this complexitywas discovered back in the mid s But recentlyinamuch

simpler algorithm was discovered

Lecture Line SegmentIntersection

Thursday Sep

Revised Sept Fixed the analysis

Reading Chapter in BKOS

Geometric intersections One of the most basic problems in computational geometry is that of

computing intersections Intersection computation is basic to manydierent application areas

In solid mo deling p eople often build up complex shap es by applying various b o olean

op erations intersection union and dierence to simple primitive shap es The pro cess

in called constructive solid geometry CSG In order to p erform these op erations the most

basic step is determining the p oints where the b oundaries of the two ob jects intersect

Lecture Notes CMSC M

In rob otics and motion planning it is imp ortanttoknowwhentwo ob jects intersect for

collision detection and collision avoidance

In geographic information systems it is often useful to overlaytwo sub divisions eg a

road network and county b oundaries to determine where road maintenance resp onsibilities

lie Since these networks are formed from collections of line segments this generates a

problem of determining intersections of line segments

Another example comes from computer graphics The clipping problem involves deter

mining what parts of a set of p olygons are visible through a rectangular window This

involves determining the intersection of the p olygons and the window and then clipping

the p olygons at these p oints

Line segmentintersection The problem that we will consider is given n line segments in the

plane rep ort all p oints where a pair of line segments intersect We assume that each line

segment is represented by giving the co ordinates of its twoendpoints

n

Observe that n line segments can intersect in as few as and as manyas O n

dierentintersection p oints We could settle for an O n algorithm claiming that it is worst

case asymptotically optimal but it would not b e v ery useful in practice since in many instances

of intersection problems intersections may b e rare Therefore it seems reasonable to lo ok for

an output sensitive algorithm that is one whose running time should b e ecient b oth with

resp ect to input and output size

We will let I denote the number of intersections How should wecount I in the degenerate

conguration where three or more lines intersect in a single p oint If k lines intersect in a

single p oint one might think of this as a single intersection p oint or one mightinterpret

k

k k pairwise intersections The former interpretation would lead to this as

faster running times and so would b e the goal of a careful implementation And indeed the

implementation in the book achieves this On the other hand one might argue that such

degeneracies are rare in practice and so it is not worth worrying ab out Wewilltake the

latter sloppier attitude and refer to the text for a more careful implementation

Complexity We will present a not quite optimal O n log n I log n time algorithm for the line

segmentintersection problem A natural question is whether this is optimal

time The b est that one might hop e for is O n log n I time algorithm Clearly we need O I

to output the intersection p oints What is not so obvious is that O n log n time is needed

This results from the fact that the following problem is known to require n log n time

Element uniqueness Given a list of n numb ers do es anynumb er app ear at least twice in

the list

Note that element uniqueness can b e solved in O n log n time by sorting and checking whether

adjacent elements are equal Given this lower b ound even determining whether the same

endp ointisusedintwo dierent line segments would require n log n time and hence this

is a lower b ound for determining even the existence of a single intersection

Note that this lowerb ound result assumes the algebraic decision treemodel of computation

in which all decisions are made by comparisons made based on exact algebraic op erations

applied to numeric inputs Although this encompasses most of what one would

consider to b e normal geometric computations there are alternative mo dels of computation

For example by taking mo ds o ors or ceilings you would b e able to implement hashing

This is a data access metho d taught in most data structures and algorithms courses See

Cormen Leiserson and Rivest for example With hashing it is p ossible to solv e the element

uniqueness in exp ected O n time Unfortunatelyeven in this more p owerful computational

Lecture Notes CMSC M

mo del no one knowhow to determine whether anytwo line segments intersect in faster than

O n log n I time in the worst case

Later in the semester we will discuss an optimal O n log n I time algorithm for this problem

Line segmentintersection In rather typical computational geometry fashion our b o ok do es not

discuss the issue of how to determine the intersection p ointoftwo line segments Let ab and

cd be two line segments given by their endp oints It is an easy exercise to determine whether

these line segments intersect simply by applying an appropriate combination of orientation

tests

To determine the co ordinates of the intersect p ointinvolves solving a small system of equations

The most natural way to set up this computation is to intro duce the notion of a parametric

representation of the line segment Recall that anypoint on the line segment ab can b e written

as a convex combination involving a real parameter s

ps sa sb for s

Similarly for cd wemayintro duct a parameter t

q t tc td for s

An intersection o ccurs if and only if we can nd s and t suchthatpspt Thus we get

the two equations

sa sb tc td

x x x x

sa sb tc td

y y y y

The co ordinates of the p oints are all known so it is just a simple exercise in linear algebra

to solve for s and t The computation of s and t will involve a division If the divisor is

this corresp onds to the case where the line segments are parallel and p ossibly collinear

These sp ecial cases should b e dealt with carefully If the divisor is nonzero then we get values

for s and t as rational numb ers the ratio of twointegers We can approximate them as

oating p ointnumbers or if wewant to p erform exact computations it is p ossible to simulate

rational numb er algebra exactly using highprecision integers and multiplying through by

least common multiples Once the values of s and t have b een computed all that is needed is

to check that b oth are in the interval

Plane Sweep Algorithm Let S fs s s g denote the line segments whose intersections

n

we wish to compute The metho d is called plane sweep Here are the main elements of any

plane sweep algorithm and howwe will apply them to this problem

Sweep line We will simulate the sweeping of a vertical line called the sweep line from left

to right Our text uses a horizontal line but there is obviously no signicant dierence

We will maintain the line segments that intersect the sweep line in sorted order say from

top to b ottom

Even ts Although we might think of the sweep line as moving continuouslywe only need to

up date data structures at p oints of some signicantchange in the sweepline contents

called event points

Dierent applications of plane sweep will have dierent notions of what event p oints

are For this application eventpoints will corresp ond to instances where the sweep line

encounters an endp oints of a line segment which are all known in advance and when the

sweep line encounters an intersection p ointoftwo line segments which will b e discovered

as the algorithm executes

Lecture Notes CMSC M

Event up dates When an eventisencountered wemust up date the data structures asso ci

ated with the event It is a go o d idea to b e careful in sp ecifying exactly what invariants

you intend to maintain For example when we encounter an intersect p oint wemust

interchange the order of the intersecting line segments along the sweep line

There are a great numb er of nasty sp ecial cases that complicate the algorithm and obscure the

main p oints We will makeanumb er of simplifying assumptions for now

No line segmentisvertical Easily xed through a symb olic p erturbation

If two segments intersect then they intersect in a single p oint that is they are not

collinear

No three lines intersect in a common p oints

future event points

intersections detected

l

Figure Plane sweep

Detecting intersections Wementioned that endp ointevents are all known in advance But how

do we detect intersection events It is imp ortantthateachevent b e detected b efore the actual

event o ccurs Our strategy will b e as follows Whenever two line segments b ecome adjacent

along the sweep line wewillcheck whether they haveanintersection o ccuring to the rightof

the sweep line If so we will add this new event

A natural question is whether this is sucient In particular if two line segments do intersect

is there necessarily some prior placementofthesweep line such that they are adjacent Happily

this is the case but it requires a pro of

Lemma Given two segments s and s whichintersect in a single p oint p and assuming no

i j

other line segment passes through this p oint there is a placementofthesweep line prior

to this event such that s and s are adjacent along the sweep line and hence will b e

i j

tested for intersection

Pro of Consider such a pair of segments and assume that prior to this all intersections

have b een correctly handled by the algorithm thus the sweep line order prior to their

intersection is correct Consider the contents of the sweep line immediately prior to this

event We claim that at this time there could b e no segment s between s and s along

k i j

the sweep line If there were then either there would have to b e endp ointofs prior to

k

the intersection implying this was not the event immediately prior to the intersection or

that s intersects either s or s again implying the existence of an intermediate event

k i j

Data structures In order to p erform the sweep we will need two data structures

Lecture Notes CMSC M

si

sk

sj

l

Figure Correctness of plane sweep

Event queue This holds the set of future events sorted according to increasing xco ordinate

Eacheventcontains the auxiliary information of what typ e of eventthisissegment

endp ointorintersection and which segments are involved The op erations that this

should supp ort are inserting an event if it is not already present in the

queue and extracting the minimum event

It seems like a data structure would b e ideal for this since it supp orts insertions

and extractmin in O log M time where M is the number of entries in the queue See

Cormen Leiserson and Rivest for details However a heap cannot supp ort the op eration

of checking for duplicate events

There are twoways to handle this One is to use a more sophisticated data structure such

as a balanced binary or skiplist This adds a small constant factor but can check

that there are no duplicates easily The second is use the heap but when an extraction

is p erformed you mayhave to p erform many extractions to deal with multiple instances

of the same event Our b o ok recommends the prior solution

If events have the same xco ordinate then we can handle this easily through a symb olic

p erturbation by sorting them lexicographically byx y This has the same eect as

imagining that the sweep line is rotated innitesimally counterclo ckwise

Sweep line status To store the sweep line status wemaintain a balanced binary tree or

p erhaps a skiplist whose entries are p ointers to the line segments stored in decreasing

order of y co ordinate along the currentsweep line

Normally when storing items in a tree the key values are constants Since the sweep

line varies we need variable keys To do this let us assume that each line segment

computes a line equation y mx b as part of its representation The key value in

each no de of the tree is a p ointer to a line segment To compute the y co ordinate of some

segment at the lo cation of the currentsweep line we simply take the current xco ordinate

of the sweep line and plug it into the line equation for this line

The op erations that we need to supp ort are those of deleting a line segment inserting a

line segment swapping the p osition of two line segments and determining the immediate

predecessor and successor of any item Assuming any balanced binary tree or a skiplist

these op erations can b e p erformed in O log n time each

The Complete Algorithm We can now present the complete planesweep algorithm

Initiallywe insert all of the line segment endp oints into the event queue The initial

sweep status is empty

While the event queue is nonempty extract the next event in the queue There are three

yp e of event cases dep ending on the t

Lecture Notes CMSC M

Segment left endp oint Insert this line segmentinto the sweep line status based on the

y co ordinate of this endp ointandthey co ordinates of the other segments currently

along the sweep line Test for intersections with the segment immediately ab ove and

b elow

Segment right endp oint Delete this line segmentfromthesweep line status For the

entries immediately preceding and succeeding this entry test them for intersections

Intersection p oint Swap the two line segments in order along the sweep line For the

new upp er segment test it against its predecessor for an intersection For the new

lower segment test it against its successor for an intersection

Analysis The work done by the algorithm is dominated by the time sp ent up dating the various

data structures since otherwise we sp end only constant time p er sweep event We need to

counttwo things the numb er of op erations applied to each data structure and the amountof

time needed to pro cess each op eration

For the sweep line status there are at most n elements intersecting the sweep line at any time

and therefore the time needed to p erform any single op eration is O log n from standard

results on balanced binary trees

Since we do not allo w duplicate events to exist in the event queue the total numb er of elements

in the queue at any time is at most n I Since we use a balanced binary tree to store the

event queue each op eration takes time at most logarithmic in the size of the queue whichis

O logn I Since I n this is at most O log n O log n O log n time

Eacheventinvolves a constantnumb er of accesses or op erations to the sweep status or the

event queue and since each such op eration takes O log n time from the previous paragraph

it follows that the total time sp ent pro cessing all the events from the sweep line is

O n I log n O n I logn O n log n I log n

Thus this is the total running time of the plane sweep algorithm

Lecture DCELs and Sub division Intersection

Tuesday Sep

Revised Sep Augmented Figure with alternative view

Reading Chapter in BKOS

Top ological Information In most applications of segmentintersection problems we are not in

terested in just a listing of the segmentintersections but wanttoknowhow the segments are

connected together Typically the plane has b een sub divided into regions and wewantto

store these regions in a way that allows us to reason ab out their prop erties eciently

This leads to the concept of a planar subdivision or what might b e called a cel l complex in

top ology A planar sub division is dened by a graph with straightline edges emb edded in

the plane so that no two edges intersect except p ossibly at their endp oints The condition

that the edges b e straight line segments may b e relaxed to allow curved segments but we

will assume line segments here This naturally sub divides the plane into regions The

dimensional vertices dimensional edges and dimensional facesWe consider these three

typ es of ob jects to b e disjoint implying each edge is top ologically op en it do es not include it

endp oints and that eachfaceisopenitdoesnotincludeitsboundaryThereisalways one

unb ounded face that stretches to innity Note that the underlying planar graph need not b e

a connected graph In particular faces maycontain holes and these holes maycon tain other

holes

Lecture Notes CMSC M

vertex edge

face

Figure Planar straightline sub division

Planar sub divisions will form the basic ob jects of many dierent structures that we will discuss

later this semester triangulations and Voronoi diagrams in particular so this is a go o d time to

consider them in greater detail The rst question is how should we represent such structures

so that they are easy to manipulate and reason ab out For example at a minimum wewould

like to b e able to list the edges that b ound each face of the sub division in cyclic order and we

would like to b e able to list the edges that surround eachvertex

Planar graphs There are a numberofimportant facts ab out planar graphs that we should discuss

Generally sp eaking an undirected graph is just a nite set of vertices and collection of

unordered pairs of distinct vertices called edges A graph is planar if it can b e drawn in the

plane the edges need not b e straight lines so that no two distinct edges cross eachotherAn

embedding of a planar graph is anysuchdrawing In fact in sp ecifying an emb edding it is

sucient just to sp ecify the counterclo ckwise cyclic list of the edges that are incident to each

vertex Since we are interested in geometric graphs our emb eddings will contain complete

geometric information co ordinates of vertices in particular

There is an imp ortant relationship b etween the number of vertices edges and faces in a planar

graph or more generally an emb edding of any graph on a top ological manifold but we will

stick to the plane Let V denote the number of vertices E the numb er of edgs F the number

of faces in a connected planar graph Eulers form ula states that

V E F

If weallow the graph to b e disconnected and let C denote the numb er of connected comp o

nents then wehave the more general formula

V E F C

In our example ab ovewehave V E F and C which clearly satises this

formula An imp ortant fact ab out planar graphs follows from this

Theorem Astraightline planar graph with n vertices has O n edges and O n faces

Pro of Since the graph is a straightline graph there cannot b e multiple edges b etween the

same pair of vertices and there cannot b e selflo op edges Wewillprove the theorem in

the more general setting of planar graphs without these typ es of edges

First we will mo dify the graph in a way that it is still planar but no more edges can

b e added This mo dication will only increase the numb er of edges and faces If the

graph is disconnected then add an edge b etween vertices in two dierent comp onents

thus reducing the numb er of connected comp onents by one and p ossibly increasing the

b er faces eachby one Rep eat until the graph is numb er of edges and p ossibly the num

connected

Lecture Notes CMSC M

Next if any face has more than three edges then add an edge through this face thus

increasing the numb er of edges and faces eachby one This cannot generally b e done

without adding curved lines unless if there are more than three vertices on the convex

hull of the vertex set But since we are not requiring that this b e a straightline planar

graph this is not an issue

Figure Mo died planar graph

Let E E and F F denote the numb er edges and faces in the mo died graph

The resulting graph has the prop erty that it has one connected comp onent every face is

b ounded by exactly three edges and each edge has a dierent face on either side of it

The last claim involves a little thought

If we countthenumb er of faces and multiply by then every edge will b e counted exactly

twice once by the face on either side of the edge Thus F E Eulers formula states

that V E F Using the fact that E F wehave

F

F F F V V

and using the face that F E wehave

E

V E E E V

Thus the numb er of faces is at most V and the numb er of edges is at most V

There are a numb er of reasonable representations that are used in practice The most widely

used on is the wingededge data structure Unfortunately it is probably also the messiest

There is another called the quadedge data structure which is quite elegant and has the nice

prop erty of b eing selfdual We will discuss duality later in the semester We discuss a simple

and relatively elegant data structure called a doublyconnectededge list or DCEL

Doublyconnected Edge List Like most representations for planar graphs the DCEL is an edge

based representation but vertex and face information is also included for whatever geometric

application is using the data structure There are three sets of records whichmayberep

resented either as arrays or linked lists as you prefer a set of vertex records a set of edge

records and a set of facerecordsEach undirected edge is represented bytwo directed edges

whic h our book calls half edges Here is what each record contains for the data structure

We will make a simplifying assumption that faces do not have holes inside of them This

assumption can b e satised byintro ducing some number of dummy edge joining each hole

either to the outer b oundary of the face or to some other hole that has b een connected to

the outer b oundary in this way Our text do es not make this assumption and so presents a

somewhat more general data structure How to add these dummy edges is left as an exercise

With this assumption it may b e assumed that the edges b ounding each face form a single

cyclic list

Lecture Notes CMSC M

Vertex Eachvertex stores its co ordinates along with a p ointer to any incident directed edge

that has this vertex as its origin vinc edge

Edge Each undirected edge is represented as two directed edges Each edge has a p ointer

to the opp ositely directed edge called its twin Each directed edge has an origin and

destination vertex Each directed edge is asso ciate with two faces one to its left and one

to its right

We store a p ointer to the origin vertex eorg we can access the destination as the origin

of the twin edge We store a p ointer to the face to the left of the edge eleft we can

access the face to the rightfromthetwin edge This is called the incident faceWe also

store the next and previous directed edges in counterclo ckwise order ab out the incident

face enext and eprev resp ectively

Face Each face f stores a p ointer to a single edge for which this face is the incident face

finc edge See the text for the more general case of dealing with holes

e.twin e e.org

e.next e.prev e.left

DCEL Alternative view

Figure Doublyconnected edge list

The gure shows twoways of visualizing the DCEL One is in terms of a collection of doubled

up directed edges An alternativeway of viewing the data structure that gives a b etter sense

of the connectivity structure is based on covering eachedgewithatwoelementblock one for

e and the other for its twin The next and prev p ointers provide links around each face of

the p olygon The next p ointers are directed counterclo ckwise around each face and the prev

p ointers are directed clo ckwise

Of course in addition the data structure may b e enhanced with whatever application data is

relevant In some applications it is not necessary to know either the face or vertex information

or b oth at all and if so these records may b e deleted See the b o ok for a complete example

For example supp ose that wewanted to enumerate the vertices that lie on some face f Here

is the co de

Vertex enumeration using DCEL

enumerateverticesFace f

Edge start fincedge

Edge e start

do

output eorg

e enext

while e start

Lecture Notes CMSC M

Merging sub divisions Let us return to the applications problem that lead to the segmentinter

section problem Supp ose that wehavetwo planar sub divisions S and S andwewantto

compute their overlay In particular this is a sub division whose vertices are the union of the

vertices of each sub division and the p oints of intersection of the line segments in the sub divi

sion Because we assume that each sub division is a planar graph the only new vertices that

could arise will arise from the intersection of two edges one from S and the other from S

Supp ose that each sub division is represented using a DCEL Can we adapt the planesweep

algorithm to generate the DCEL of the overlaid sub division

The answer is yes Furthermore if we will not b e needing the original sub divisions it is

p ossible to do this by mo difying the existing sub divisions If not then the pro cess b egins by

making a copy of each The rst part of the problem is straightforward but p erhaps a little

tedious This part consists of building the edge and vertex records for the new sub division The

second part involves building the face records It is more complicated b ecause it is generally

not p ossible to know the face structure at the momentthatthesweep is advancing without

lo oking into the future of the sweep to see whether regions will merge You mighttryto

convince yourself of this The entire sub division is built rst and then the face information

is constructed and added later We will skip the part of up dating the face information see

the text

For the rst part the most illustrative case arises when the sweep is pro cessing an intersection

event In this case the segments come from the tw o dierent sub divisions The pro cess involves

the following steps and is illustrated in the gure

Create a new vertex v at the intersection p oint

Let a and b denote the edges that intersect oriented from left to right across the sweep

line We split eachofthetwointersecting edges byaddingavertex at the intersection

point Let a and b b e the new edge pieces They are created by the calls Splita

a and Splitb b where the pro cedure is given b elow This pro cedure creates the

new edge links it into place and then returns the newly created edge After this the

edges have b een split but they are not linked to each other The edge constructor is

given the origin and destination of the new edge We will not give the details Also note

that the destination of a that is the origin of a s twin must b e up dated whichwehave

omitted

This pro cedure creates b oth the new edge and its twin The pro cedure adest returns

the destination of a which is equivalentto atwinorg

Splitedge a edge a a is returned

a new edgev adest create edge vadest

anext anext anextprev a

anext a aprev a

at atwin at atwin the twins

atprev atprev atprevnext at

atprev at atnext at

Link the four edges together

Spliceedgeaedgeaedgebedgeb

at atwin at atwin find the twins

bt btwin bt btwin

anext b bprev a link the edges together

btnext a aprev bt

atnext bt btprev at

Lecture Notes CMSC M

bnext at atprev b

a1 a1 b2

a1t split a1t b2t a2 b1 b1

b1t b1t a2t

splice

a1 b2

a1t b2t a2 b1

b1t a2t

Figure Up dating the DCEL

Lecture Polygon Triangulation

Thursday Sep

Revised Sep Moved last section to Lecture

Reading Chapter in BKOS

Simple Polygons Todaywe b egin study of the problem of triangulating p olygons Weintro duce

this problem byway of a cute example in the eld of combinatorial geometry

We b egin with some denitions A polygonal curve is a nite sequence of line segments

called edges joined endtoend The endp oints of the edges are vertices For example let

v v v denote the set of n vertices and let e e e denote a sequence of n

n n

edges where e v v A p olygonal curveisclosed if the last endp oint equals the rst

i i i

v v A p olygonal curveissimple if it is not selfintersecting More precisely this means

n

that each edge e do es not intersect any other edge except for the endp oints it shares with its

i

adjacent edges

The famous Jordan curve theorem states that every simple closed plane curve divides the plane

into two regions the interior and the exterior Although the theorem seems intuitively

obvious it is quite dicult to prove We dene a polygon to b e the region of the plane

b ounded by a simple closed p olygonal curve The term simple polygon is also often used to

emphasize the simplicity of the p olygonal curve We will assume that the vertices are listed in

counterclo ckwise order around the b oundary of the p olygon

Lecture Notes CMSC M

v6 v2 v0 v3

v1 v4 v5

polygonal curve closed but not simple simple polygon

Figure Polygonal curves

Art Gallery Problem Wesaythattwopoints x and y in a simple p olygon can see each other

or x and y are visible if the op en line segment xy lies entirely within the interior of P

If we think of a p olygon as the o or plan of an art gallery consider the problem of where to

place guards and howmany guards to place so that every p oint of the gallery can b e seen

by some guard Victor Klee p osed the following question Supp ose wehave an art gallery

whose o or plan can b e mo deled as a p olygon with n vertices As a function of n what is

the minimum numb er of guards that suce to guard such a gallery Observe that are you are

told ab out the p olygon is the numb er of sides not its actual structure Wewanttoknow the

fewest numb er of guards that suce to guard al l p olygons with n sides

A guarding set A polygon requiring n/3 guards.

Figure Guarding sets

Before getting into a solution lets consider some basic facts Could there b e p olygons for

which no nite numb er of guards suce It turns out that the answer is no but the pro of is

not immediately obvious You might consider placing a guard at eachofthevertices Sucha

set of guards will suce in the plane But to showhow counterintuitive geometry can b e it is

interesting to not that there are simple nonconvex p olyhedra in space suchthateven if you

place a guard at every vertex there would still b e p oints in the p olygon that are not visible to

any guard As a challenge try to come up with one with the fewest numberofvertices

An interesting question in combinatorial geometry is howdoesthenumb er of guards needed

to guard any simple p olygon with n sides grow as a function of nIfyou play around with

the problem for a while trying p olygons with n sides for example you will

eventually come to the conclusion that bnc is the rightvalue The gure ab ove shows

aworstcase example where bnc guards are required A cute result from combinatorial

geometry is that this number always suces The pro of is based on three concepts p olygon

triangulation dual graphs and graph coloring The remarkably clever and simple pro of was

discovered by Fisk

Theorem The ArtGallery Theorem Given a simple p olygon with n vertices there exists

a guarding set with at most bnc guards

Lecture Notes CMSC M

Before giving the pro of we explore some asp ects of p olygon triangulations We b egin by

intro ducing a triangulation of P Atriangulation of a simple p olygon is a planar sub division

of the interior of P whose vertices are the vertices of P and whose faces are all triangles An

imp ortant concept in p olygon triangulation is the notion of a diagonal that is a line segment

between twovertices of P that are visible to one another A triangulation can b e viewed as

the union of the edges of P and a maximal set of noncrossing diagonals

Lemma Every simple p olygon with n vertices has a triangulation consisting of n diagonals

and n triangles

Well refer you to the text for a pro of The pro of is based on the fact that given any n

vertex p olygon with n it has a diagonal This may seem utterly trivial but actually

takes a little bit of work to prove For example it fails to hold in space The addition

of the diagonal breaks the p olygon into two p olygons of say m and m vertices such that

m m n since b oth share the vertices of the diagonal Thus by induction there are

m m n n triangles total A similar argument holds for the case

of diagonals

It is a well known fact from graph theory that any planar graph can b e colored with colors

The famous color theorem This means that we can assign a color to eachofthevertices

of the graph from a collection of dierent colors so that no two adjacentvertices have the

same color However we can do even b etter for the graph wehave just describ ed

3 1 3 1 2 1 2 3 2

1 2 1 1 3 3 1

2 3 2

Figure Polygon triangulation and a coloring

Lemma Let T b e the triangulation graph of a triangulation of a simple p olygon Then T is

colorable

Pro of For every planar graph G there is another planar graph G called its dual The dual

G is the graph whose vertices are the faces of Gandtwovertices of G are connected

by an edge if the two corresp onding faces of G share a common edge

Since a triangulation is a planar graph it has a dual shown in the gure b elow We

do not include the external face in the dual Because each diagonal of the triangulation

splits the p olygon into two it follows that each edge of the dual graph is a cut edge

meaning that its deletion would disconnect the graph As a result it is easy to see that

the dual graph is a freetree that is a connected acyclic graph and its maximum degree

is This would not b e true if the p olygon had holes

The coloring will b e p erformed inductively If the p olygon consists of a single triangle

then just assign any colors to its vertices An imp ortant fact ab out any free tree is that

it has at least one leaf in fact it has at least two Remove this leaf from the tree This

corresp onds to removing a triangle that is connected to the rest triangulation by a single

edge Such a triangle is called an ear By induction color the remaining triangulation

Lecture Notes CMSC M

an ear

Figure Dual graph of triangulation

When you add back the deleted triangle twoofitsvertices have already b een colored

and the remaining vertex is adjacent to only these twovertices Give it the remaining

color In this waytheentire triangulation will b e colored

We can now give the simple pro of of the guarding theorem

Pro of of the ArtGallery Theorem Consider any coloring of the vertices of the p olygon

At least one color o ccurs at most bnc time Otherwise we immediately get there are

more than n vertices a contradiction Place a guard at eachvertex with this color We

use at most b nc guards Observethatevery triangle has at least one vertex of each

of the tree colors since you cannot use the same color twice on a triangle Thus every

pointintheinterior of this triangle is guarded implying that the interior of P is guarded

A somewhat messy detail is whether you allow guards placed at a vertex to see along the

wall However it is not a dicult matter to push each guard innitesimally out from his

vertex and so guard the entire p olygon

Lecture More Polygon Triangulation

Tuesday Sep

Reading Chapter in BKOS

The Polygon Triangulation Problem The artgallery exercise was intended as motivation for

the problem of triangulating a simple p olygon This op eration is used in many other applica

tions where complex shap es are to b e decomp osed into a set of disjoint simpler shap es There

are many applications in which the shap es of the triangles is an imp ortant issue eg skinny

triangles should b e avoided but there are equally manyinwhich the shap e of the triangle is

unimp ortant We will consider the problem of given an arbitrary simple p olygon compute

any triangulation for the p olygon

This problem has b een the fo cus of computational geometry for manyyears There is a simple

naive p olynomialtime algorithm based on adding successive diagonals but it is not partic

ularly ecient There are very simple O n log n algorithms for this problem that have b een

known for manyyears A longstanding op en problem was whether there exists an O n time

algorithm The problem was solved by Chazelle in but the algorithm is so amazingly

intricate it could never comp ete with the practical but asymptotically slower O n log nal

gorithms In fact there is no known algorithm that runs in less than O n log n time that is

really practical enough to replace the standard O n log n algorithm whichwe will discuss

We will present one of many known O n log n algorithms The approachwe presenttoday

isatwostep pro cess although with a little cleverness b oth steps can b e combined into one

algorithm The rst is to consider the sp ecial case of triangulating a monotone polygon After

Lecture Notes CMSC M

this we consider howtoconvert an arbitrary p olygon into a collection of disjoint monotone

p olygons Then we will apply the rst algorithm to each of the monotone pieces The former

algorithm runs in O n time The latter algorithm runs in O n log n time

Monotone Polygons A p olygonal chain C is said to b e strictly monotone with resp ect to a given

line Lifany line that is orthogonal to L intersects C in at most one p oint Achain C

is monotone with resp ect to L if each line that is orthogonal to L intersects C in a single

connected comp onent Thus it mayintersect not at all at a single p oint or along a single

line segment A p olygon P is said to b e monotone with resp ect to a line L if its b oundary

P can b e split into twochains each of which is monotone with resp ect to L

x-monotone polygon Monotone decomposition

Figure Monotonicity

Henceforth let us consider monotonicity with resp ect to the xaxis We will call these p olygons

horizontal ly monotone It is easy to test whether a p olygon is horizontally monotne How

a Find the leftmost and rightmost vertices min and max xco ordinate in O n time

b These vertices split the p olygons b oundary into twochains an upper chain and a lower

chain Walk from left to right along eachchain verifying that the xco ordinates are

nondecreasing This takes O n time

As a challenge consider the problem of determining whether a p olygon is monotone in any

unsp ecied direction This can b e done in O n time but is quite a bit harder

Triangulation of Monotone Polygons We can triangulate a monotone p olygon by a simple

variation of planesweep metho d We b egin with the assumption that the vertices of the p oly

gon have b een sorted in increasing order of their xco ordinates For simplicitywe assume no

duplicate xco ordinates Otherwise break ties b etween the upp er and lower chains arbitrarily

and within a chain break ties so that the chain order is preserved Observe that this do es not

require sorting We can simply extract the upp er and lower chain and merge them as done

in mergesort in O n time

erything The idea b ehind the triangulation algorithm is quite simple Try to triangulate ev

you can to the left the currentvertex by adding diagonals and then remove the triangulated

region from further consideration

In the example there is obviously nothing to do until wehaveatleastvertices With vertex

it is p ossible to add the diagonal to vertex and so we do this In adding vertex we can

add the diagonal to vertex However vertices and are not visible to any other nonadjacent

vertices so no new diagonals can b e added When we get to vertex it can b e connected to

and The pro cess continues until reaching the nal vertex

The imp ortant thing that makes the algorithm ecient is the fact that when wearriveata

vertex the untriangulatedregion that lies to the left of this vertex alwayshasavery simple

structure This structure allows us to determine in constant time whether it is p ossible to

add another diagonal And in general we can add each additional diagonal in constant time

Lecture Notes CMSC M

2 2

1 3 1 3 4

7 7 2 2

1 3 4 1 3 4 5 5 8 6 13 6

12 12 11 11 7 7 2 2 10 10 1 3 4 1 3 4 9 9 5 8 5 8

6 6 13

Figure Triangulating a monotone p olygon

Since any triangulation consists of n diagonals the pro cess runs in O n total time This

structure is describ ed in the lemma b elow

Lemma Main Invariant For i let v be the vertex just pro cessed by the triangulation

i

algorithm The untriangulated region lying to the left of v consists of two xmonotone

i

chains a lower chain and an upp er chain eachcontaining at least one edge If the chain

from v to u has two or more edges then these edges form a reex chain that is a sequence

i

of vertices with interior angles all at least degrees The other chain consists of a

single edge whose left endp ointisu and whose right endp oint lies to the rightofv

i

We will provetheinvariantby induction As the basis case consider the case of v Here

u v and one chain consists of the single edge v v and the other chain consists of the other

edge adjacenttov

To prove the main invariant we will give a case analysis of how to handle the next event

involving v assuming that the invariant holds at v and see that the invariant is satised

i i

after eachevent has b een pro cessed There are the following cases that the algorithm needs

to deal with

Case v lies on the opp osite chain from v In this case we add diagonals joining v to all

i i i

the vertices on the reex chain from v back to but not including u Now u v

i i

and the reex chain consists of the single edge v v

i i

Case v is on the same chain as v Wewalk back along the reex chain adding diagonals

i

joining v to prior vertices until we nd the rst that is not visible to v whichmay mean

i i

that we add no diagonals

As can b e seen in the gure this mayin volve connecting v to one or more vertices a

i

or it mayinvolve connecting v to no additional vertices b dep ending on whether the

i

Lecture Notes CMSC M

u

vi-1 Initial invariant

vi

u u u vi vi-1 v i-1 vi-1

Case 1 Case 2a Case 2b vi

Figure Triangulation cases

rst angle is less or greater than degrees In either case the vertices that were cut o

by diagonals are no longer in the chain and v b ecomes the new endp ointtothechain

i

Note that when we are done analogous to Grahams scan the remaining chain from v

i

to u isareexchain

How is this implemented The vertices on the reex chain can b e stored in a stack Wekeep

a ag indicating whether the stackisontheupperchain or lower chain and assume that

with each new vertex we knowwhichchain of the p olygon it is on Note that decisions ab out

visibility can b e based simply on orientation tests involving v andthetoptwoentries on the

i

stack When we connect v by a diagonal we just p op the stack

i

Analysis We claim that this algorithm runs in O n time As wementioned earlier the sorted list

of vertices can b e constructed in O n time through merging The reex chain is stored on a

stack In O time p er diagonal we can p erform an orientation test to determine whether to

add the diagonal and assuming a DCEL the diagonal can b e added in constant time Since

the numb er of diagonals is n the total time is O n

Monotone Sub division In order to run the ab ove triangulation algorithm we rst need to sub di

vide an arbitrary simple p olygon into monotone p olygons This is also done by a planesweep

approach We will add a set of nonintersecting diagonals that partition the p olygon into

monotone pieces

Observe that the absence of xmonotonicity o ccurs only at vertices in which in which the

interior angle is greater than degrees and b oth edges lie either to the left of the vertex or

b oth to the right Following the b o oks notation we call the rst typ e a merge vertex since

as the sweep passes over this vertex the edges seem to b e merging and the latter typ e a split

vertex

Lets discuss split vertices rst b oth edges lie to the right of the vertex When a split vertex

is encountered in the sweep there will b e an edge e of the p olygon lying ab ove and an edge

j

e lying b elow We might consider attaching the split vertex to left endp oint of one of these

k

two edges but it might b e that neither endp oint is visible to the split vertex But this would

imply that there is a closer vertex lying b etween e and e We will attach the split vertex to

j k

the closest vertex to the left of the sweep line whichliesbetween e and e Call this vertex

j k

the helper e We could have just as easily asso ciated the help er with e it do esnt really

j k

Lecture Notes CMSC M

helper(e1)

e1

e2

e3 helper(e3)

e4 e5

e6

helper(e5)

Figure Split vertices merge vertices and help ers

matter If there is no vertex b etween these edges then helper e is dened to b e the left

j

endp ointofe or e that lies closer to the sweep line See the gure

j k

Note that helper e is dened with resp ect to the current lo cation of the sweep line As the

j

sweep line moves its value changes Also it is only dened when the sweep line intersects e

j

One way to visualize helper e is to imagine a trap ezoid with vertical sides and b ounded ab ove

j

and b elowby e and e sweeping to the left of the currentsweep line The rst vertex this

j k

sweeping trap ezoid hits is the help er These trap ezoids are illustrated in the gure ab ove

Here are basic elements of the plane sweep algorithm to x the split vertices We consider

merge vertices later

Events The endp oints of the edges of the p olygon These are sorted by increasing order of

xco ordinates Since no new events are generated the events may b e stored in a simple

sorted list ie no priority queue is needed

Sweep status The sweep line status consists of the list of edges that intersect the sweep line

sorted from top to b ottom Our b o ok notes that we actually only need to store edges

such that the p olygon lies just b elow this edge since these are the only edges that we

evaluate helper from

These edges are stored in a dictionary eg a balanced binary tree or a skip list so

that the op erations of insert delete nd predecessor and successor can b e evaluated in

O log n time each

Event pro cessing There are eventtyp es based on a case analysis of the lo cal structure of

edges around eachvertex Let v b e the currentvertex encountered bythesweep

Split vertex Searchthesweep line status to nd the edge e lying immediately ab ove

v Add a diagonal connecting v to helper e Add the two edges incidenttov in the

sweep line status and make v the help er of the lower of these two edges and make v

the new help er of e

Merge vertex Find the two edges incidenttothisvertex in the sweep line status they

must b e adjacent Delete them b oth Let e b e the edge lying immediately ab ove

them Make v the new help er of e

Lecture Notes CMSC M

Start vertex Both edges lie to the rightofv but the interior angle is less than

degrees Insert this vertex and its edges into the sweep line status Set the help er

of the upp er edge to v

End vertex Both edges lie to the left of v but the interior angle is less than

degrees Delete b oth edges from the sweep line status

Upp erchain vertex One edge is to the left and one to the right and the p olygon

interior is b elow Replace the left edge with the right edge in the sweep line status

Make v the help er of the new edge

Lowerchain vertex One edge is to the left and one to the right and the p olygon

interior is ab ove Replace the left edge with the right edge in the sweep line status

Let e b e the edge lying ab ove here Make v the help er of e

e e e v v v v v v

Split Merge Start End Upper Lower

Figure Plane sweep cases

This only inserts diagonals to x the split vertices What ab out the merge vertices This

could b e handled by applying essentially the same algorithm using a reverse right to left

sweep It can b e shown that this will never intro duce crossing diagonals but it might attempt

to insert the same diagonal twice However the b o ok suggests a simpler approach Whenever

wechange a help er vertex check whether the original help er vertex is a merge vertex If so

the new help er vertex is then connected to the merge vertex by a new diagonal It is not hard

to show that this essentially has the same eect as a reverse sweep and it is easier to detect

the p ossibility of a duplicate insertion in case the new vertex happ ens to b e a split vertex

There are many sp ecial cases what a pain but each one is fairly easy to deal with so the

algorithm is quite ecient As with previous plane sweep algorithms it is not hard to show

that the running time is O log n times the number of events In this case there is one event

per vertex so the total time is O n log n This gives us an O n log n algorithm for p olygon

triangulation

Lecture Intersection of Halfplanes

Thursday Sep

Revised Sept xed the clo ckwise bug in the last lemma

Reading Chapter in BKOS with some elements from Section and Section

Halfplane Intersection Todaywe b egin studying another very fundamental topic in geometric

computing and along the waywe will show a rather surprising connection b etween this topic

the topic of convex hulls whichwe discussed earlier

Any line in the plane splits the plane into two regions called halfplane one lying on either side

of the line Wemay refer to a halfplane as b eing either closed or open dep ending on whether

it contains the line itself For this lecture wewillbeinterested in closed halfplanes

Lecture Notes CMSC M

Howdowe represent lines and halfplanes Wemay assume each halfplane is expressed byan

inequality of the form

ax by c

and the halfplane is represented by the three co ecients a b c The line b ounding the

halfplane is ax by cNotethatifwemultiply a bandc by the same nonzero scalar

value then the line equation do es not change Thus we can think of this triple as a form of

homogeneous co ordinates for lines For example if c thenwe can divide the equation

through by c yielding an equation of the form acx bcy which can b e expressed by

the homogeneous co ordinates ac bc

If the scalar multiple is negative then the sense of the inequalitywillbereversed Thus we

do not need a separate inequality of the form ax by c since we can just negate all three

co ecients to get the same eect

Halfplane intersection problem The halfplane intersection problem is given a set of n closed

halfplanes H fh h h g compute their intersection A halfplane closed or op en is

n

a convex set and hence the intersection of anynumb er of halfplanes is also a convex set

Unlike the convex hull problem the intersection of n halfplanes may generally b e emptyor

even unb ounded A reasonable output representation might b e to list the lines b ounding the

intersection in counterclo ckwise order p erhaps along with some annotation as to whether the

nal gure is b ounded or unb ounded

Figure Halfplane intersection

How many sides can b ound the intersection of n halfplanes in the worst case Observe that

byconvexity each of the halfplanes can app ear only once as a side and hence the maximum

numb er of sides is n How fast can we compute the intersection of halfspaces As with

the convex hull problem it can b e shown through a suitable reduction from sorting that the

problem has a lower b ound of n log n

Who cares ab out this problem Our b o oks discusses a rather fanciful application in the

area of casting More realistically halfplane intersection and halfspace intersection in higher

dimensions are used as a metho d for generating convex shap e approximations In computer

graphics for example a b ounding b ox is often used to approximate a complex multisided

p olyhedral shap e If the b ounding b ox is not visible from a given viewp oint then the ob ject

within it is certainly not visible Testing the visibility of a sided b ounding b oxismuch

easier than a multisided nonconvex p olyhedron and so this can b e used as a lter for a

more costly test A b ounding b ox is just the intersection of axisaligned halfspace in

space If more accurate but still convex approximations are desired then wemay compute

the intersection of a larger numb er of tight b ounding halfspaces in various orientations as the

nal approximation

Solving the halfspace intersection problem in higher dimensions is quite a bit more challenging

than in the plane For example just storing the output as a cyclic sequence of b ounding planes

is not sucient In general some sort of adjacency structure ala DCELs is needed

Lecture Notes CMSC M

We will discuss two algorithms for the halfplane intersection problem The rst is given in

the text For the other we will consider somewhat simpler problem of computing something

called the lower envelope of a set of lines and show that it is closely related to the convex hull

problem

DivideandConquer Algorithm We b egin bysketching a divideandconquer algorithm for

computing the intersection of halfplanes The basic approachisvery simple

If n then just return this halfplane as the answer

Split the n halfplanes of H into subsets H and H of sizes b nc and d ne resp ectively

Compute the intersection of H and H eachby calling this pro cedure recursively Let

C and C b e the results

Intersect the convex p olygons C and C which mightbeunb ounded into a single convex

p olygon C and return C

The running time of the resulting algorithm is most easily describ ed using a recurrence that

is a recursively dened equation If we ignore constant factors and assume for simplicity that

n is a p ower of then the running time can b e describ ed as

if n

T n

T n S n if n

where S n is the time required to compute the intersection of twoconvex p olygons whose total

complexityis nIfwe can showthatS nO n then by standard results in recurrence s

it will follow that the overall running time T nisO n log n See Cormen Leiserson and

Rivest for a pro of

Intersecting Two Convex Polygons The only nontrivial part of the pro cess is implementing an

algorithm that intersects two convex p olygons C and C into a single convex p olygon Note

that these are somewhat sp ecial con vex p olygons b ecause they maybeemptyorunb ounded

We know that it is p ossible to compute the intersection of line segments in O n I log n

time where I is the number of intersecting pairs Twoconvex p olygons cannot intersect in

more than I O n pairs This follows from the observation that each edge of one p olygon

can intersect at most two edges of the other p olygon byconvexity This would given O n log n

algorithm for computing the intersection and an O n log n solution for T n which is not as

good as wewould like

However there is a very simple planesweep approach to solving this problem Supp ose that

we p erform a lefttoright plane sweep to compute the intersection Observethatbyconvexity

the sweep line intersects each C in at most two p oints Therefore there are at most four

i

ts in the sweep line status at any time Thus we do not need a fancy dictionary for storing p oin

the sweep line status All the op erations can b e p erformed in constant time Furthermore you

do not need a priority queue for the events The only twoevents that are imp ortant are the

leftmost p oints of C and C note that they might stretchbackto To determine the

next event p oint you just need to check the four current edges for intersections and check the

four edges for their next endp oints Since there are only a constantnumb er of p ossibilities

eachevent can b e handled in O time

Lower Envelop es and Duality Next we consider a slightvariant of this problem to demonstrate

some connections with convex hulls These connections are very imp ortant to an understanding

of computational geometryandwe see more ab out them in the future These connections have

to do with a convex called pointline duality Inanutshell there is a remarkable similarity

Lecture Notes CMSC M

potential next event

Figure Convex p olygon intersection

between how p oints interact with each other an how lines interact with each other Sometimes

it is p ossible to take a problem involving p oints and map it to an equivalent problem involving

lines and vice versa In the pro cess new insights to the problem may b ecome apparent

The problem to consider is called the lower envelope problem and it is a sp ecial case of the

halfplane intersection problem We are given a set of n lines L f g where is of

n i

the form y a x b Think of these lines as dening n halfplanes y a x b each lying

i i i i

below one of the lines The lower envelope of L is the b oundary of the intersection of these

half planes There is also an upp er envelop e formed by considering the intersection of the

halfplanes lying ab ove the lines

Upper envelope

Lower envelope

Figure Lower and upp er envelop es

The lower envelop e problem is a restriction of the halfplane intersection problem but it an

interesting restriction Notice that any halfplane intersection problem that do es not involve

anyvertical lines can b e rephrased as the intersection of twoenvelop es a lower envelop e dened

bythelower halfplanes and an upp er envelop e dened bytheupward halfplanes

I will show that solving the lower envelop e problem is essentially equivalent to solving the

upp er convex hull problem In fact they are so equivalent that exactly the same algorithm

will solve b oth problems without changing even a single character of co de All that changes

is the wayinwhichyou view the two problems

Duality Let us b egin by considering lines in the plane Each line can b e represented in a number

of ways but for now let us assume the representation y ax b for some scalar values a and

bWe cannot representvertical lines in this way and for nowwe will just ignore them Later

Lecture Notes CMSC M

in the semester we will x this up Why did we subtract bWell see later that this is just a

convenience

Therefore in order to describ e a line in the plane you need only give its two co ordinates a b

In some sense lines in the plane can b e thoughtofaspoints in a new plane in which the

co ordinate axes are lab eled a b rather than x y Thus the line y x corresp onds

to the p oint in this new plane Eachpoint in this new plane of lines corresp onds to

a nonvertical line in the original plane We will call the original x y plane the primal plane

and the new a bplane the dual plane

What is the equation of a line in the dual plane Since the co ordinate system uses a and b

wemight write a line in a symmetrical form for example b a where the values and

could b e replaced byany scalar values

Consider a particular p oint p p p in the primal plane and consider the set of all

x y

nonvertical lines passing through this p oint Anysuch line must satisfy the equation p

y

ap b The images of all these lines in the dual plane is a set of p oints

x

j p ap bg L fa b

y x

fa b j b p a p g

x y

Notice that this set is just the set of p oints that lie on a line in the dual a bplane And

this is whywe negated b Thus not only do lines in the primal plane map to p oints in the

dual plane but there is a sense in whicha point in the primal plane corresp onds to a line in

the dual plane

Tomake this all more formal we can dene a function that maps p oints in the primal plane

to lines in the dual plane and lines in the primal plane to p oints in the dual plane We denote

it using a asterisk as a sup erscript Thus given p oint p p p and line y ax b

x y

in the primal plane wedene and p to b e a p oint and line resp ectively in the dual plane

dened by

a b

p b p a p

x y

r*:(b=-2a+1)

y b p:(-2,2) s*:(b=a+1) q*:(b=-a-1) q:(-1,1) L*:(0,1) x a

L:(y=0x-1) r:(-2,-1) s:(1,-1)

p*:(b=-2a-2)

Primal plane Dual plane

Figure Dual transformation

We can dene the same mapping from dual to primal as well Dualityhasa number of

interesting prop erties each of which is easy to verify by substituting the denition and a little

algebra

Lecture Notes CMSC M

Self Inverse p p

Order reversing Point p lies ab oveonb elow line in the primal plane if and only if line

p passes b elowonab ove p oint in the dual plane resp ectively

Intersection preserving Lines and intersect at p oint p if and only if line p passes

through p oints and in the dual plane

CollinearityCoincidence Three p oints are collinear in the primal plane if and only if their

dual lines intersect in a common p oint

To nish things up weneedtomake the connection b etween the upp er convex hull of a set of

p oints and the lower envelop e of a set of lines

Lemma Let P b e a set of p oints in the plane The counterclo ckwise order of the p oints along

ex hull of P is equal to the lefttoright order of the sequence of the upp er lower conv

lines on the lower upp er envelop e of the dual P

Pro of We will prove the result just for the upp er hull and lower envelop e since the other case

is symmetrical For simplicity let us assume that no three p oints are collinear Observe

that a necessary and sucient condition for a pair of p oints p p to form an edge on the

i j

upp er convex hull is that the line that passes through b oth of these p oints has every

ij

other p ointinP strictly b eneath it

A necessary and sucient condition that these lines and p Consider the dual lines p

j i

are adjacentonthelower envelop e is that the dual p ointatwhich they meet lies

ij

b eneath all of the other dual lines in P

The order reversing condition of duality assures us that the primal condition o ccurs if and

only if the dual condition o ccurs Therefore the sequence of edges on the upp er convex

hull is identical to the sequence of vertices along the lower envelop e

As wemovecounterclo ckwise along the upp er hull observe that the slop es of the edges

increase monotonically Since the slop e of a line in the primal plane is the a co ordinate

of the dual p oint it follows that as wemove counterclo ckwise along the upp er hull we

visit the lower envelop e from left to right

One rather cryptical feature of this pro of is that although the upp er and lower hulls app ear

to b e connected the upp er and lower envelop es of a set of lines app ears to consist of two

disconnected sets To make sense of this we should interpret the primal and dual planes from

the p ersp ective of pro jective geometry and think of the rightmost line of the lower envelop e as

wrapping around to the leftmost line of the upp er envelop e and vice versa We will discuss

pro jective geometry later in the semester

Another interesting question is that of orientation We know the the orientation of three p oints

is p ositive if the p oints have a counterclo ckwise orientation What do es it mean for three lines

to have a p ositiveorientation The denition of line orientation is exactly the same in terms

of a determinant of the co ecients of the lines

Lecture Linear Programming

Tuesday Sep

Reading Chapter in BKOS

Linear Programming Last time we considered the problem of computing the intersection of n

halfplanes and presented in optimal O n log n algorithm for this problem In many applica

tions it is not imp ortant to knowtheentire p olygon or generally the entire p olytop e in higher

dimensions but only to nd the p oin t that that is extreme in some given direction

Lecture Notes CMSC M

One particularly imp ortant application is that of linear programming In linear programming

LP we are given a set of linear inequalities or contraints whichwemay think of as dening

a p ossibly empty p ossibly unb ounded p olyhedron in space called the feasible region and

we are given a linear objective functionwhichistobeminimized or maximized sub ject to the

given constraints A typical description of a ddimensional linear programming problem might

be

Maximize c x c x c x

d d

Sub ject to a x a x b

d d

a x a x b

d d

x a x b a

nd d n n

where a c and b are given real numbers

ij i i

From a geometric p ersp ective the feasible region is the intersection of halfspaces and hence

is a convex p olyhedron We can think of the ob jective function as a vector c and the problem

is to nd the p oint of the feasible region that is furthest in the direction c called the optimal

vertexInmany of our examples we will imagine that the vector c is p ointing down and hence

the problem is just that of nding the lowest p oint of the feasible region

Linear programming is a very imp ortant technique used in solving large optimization problems

Typical instances mayinvolvehundreds to thousands of contraints in very high dimensional

space It is without doubt one of the most imp ortantformulations of general optimization

problems

We will restrict ourselves to low dimensional instances of linear programming There are

anumber of interesting optimization problems that can p osed as a lowdimensional linear

programming problem or as closely related optimization problems One whichwe will see

later is the problem of nding a minimum radius circle that encloses a given set of n points

Normally this extreme p ointwillbeavertex of the feasible region p olyhedron but there

some other p ossibilities as well The feasible region ma ybeempty in which case the linear

programming problem is said to b e infeasible and there is no solution It maybeunb ounded

and if c p oints in the direction of the unb ounded part of the p olyhedron then there may

solutions with innitely large values of the ob jective function In this case there is no nite

solution and the LP problem is said to b e unbounded Finally observe that in degenerate

situations it is p ossible to have an innite numb er of nite optimum solutions b ecause an

edge or face of the feasible region is p erp endicular to the ob jective function vector In such

instances it is common to break ties by requiring that the solution b e lexicographically maximal

eg among all maximal solutions take the one with the lexicographically maximum vector

This is exactly analogous to a applying a symb olic p erturbation by rotating space

dimensional LP The principal metho ds used for solving high dimensional linear programming

problems are the simplex algorithm and various interior point methods The simplex algo

rithm works by nding a vertex on the feasible p olyhedron then then walking edge by edge

downwards until reaching a lo cal minimumByconvexitythelocalminimum is the global

minimum It has b een long known that there are instances where the simplex algorithm runs

in exp onential time The question of whether linear programming was even solvable in p oly

nomial time was op en until a little over years ago when Karamarkar showed a p olynomial

time algorithm based on moving through the interior of the feasible region It should b e men

tioned that the metho d is p olynomial in the number of numberofconstraints the dimension

and the numb er of bits of precision in the numb ers Although this is go o d enough for prac

tice one of the ma jor op en problems left in the area is whether there is a strongly polynomial

time algorithm that is p olynomial without the assumption that the numb ers are of b ounded

precision

Lecture Notes CMSC M

Let us consider the problem just in the plane Here weknow that there is an O n log n

algorithm based on just computing the feasible p olyhedron and nding its lowest vertex

However since we are only interested in one p oint on the p olyhedron it seems that we might

hop e to do b etter We will show that dimensional LP problems can b e solved in O n time

and in fact more generallyany xed dimensional linear programming can b e solved in O n

time The problem with using such an algorithm in practice is that the constant factors grow

very rapidly with the dimension faster than p olynomial time We will discuss one simple

one later whose running time is O dn Thus these algorithms are only acceptable for relative

small dimensional problems

Incremental Construction The algorithms that we will discuss for linear programming are very

simple and are based on a metho d called incremental construction Planesweep and incre

mental construction are the two pillars of computational geometry and so this is another

interesting reason for studying the linear programming problem

Assume that we are given a set of n linear inequalities halfplanes h h of the form

n

a x a y b

ix iy i

and a nonzero ob jective function giv en byvector c c c The problem is to nd p

x y

p p that is feasible and maximizes the dot pro duct c p c p In our illustrations we

x y x x y y

will assume that c is p ointing downwards eg c This is our b o oks convention

It is a bit confusing b ecause note that as you decrease the y co ordinate of a p oint you

increase the ob jective function

Let us supp ose for simplicity that the LP problem is b ounded and furthermore we can nd

two halfplanes whose intersection a cone is b ounded with resp ect to the ob jective function

Let us assume that the halfplanes are renumb ered so that these are h and h and let v

denote this rst optimum vertex

We will then add halfplanes one byone h h and with each addition we will up date

the current optimum vertex After the addition of fh h h g let C denote the current

i i

feasible region their common intersection and let v denote the current feasible vertex Our

i

job is to up date v with each new addition Note that we will not compute the C s explicitly

i i

since doing so would require O n log n time but it is handy to think ab out their existence

for the purp oses of proving things Notice that with each new constraint the feasible region

b ecomes smaller and hence the value of the ob jective function at optimum vertex can only

decrease

There are two cases that can arise when h is added The rst is that v is already satises

i i

constraint h that is it lies within this halfplane If so then it is easy to see that the optimum

i

vertex do es not change that is v v On the other hand if v violates constraint h

i i i i

then we need to nd a new optimum vertex Where shall we lo ok for it

The imp ortant observation is that assuming that the feasible region is not empty the new

optimum vertex must lie on the line that b ounds h Call this line The b o ok proves this

i i

formallyIntuitively if the new optimum v ertex did not lie on thendraw a line segment

i

from v to the new optimum Observe that as you walk along this segment the value

i

of the ob jective function is decreasing monotonically by linearity and that this segment

must cross b ecause it go es from b eing infeasible with resp ect to h to b eing feasible Thus

i i

it is maximized at the crossing p oint which lies on Convexity a linearity are b oth very

i

imp ortant for the pro of

So this leaves the question Howdowe nd the optimum vertex lying on line Thisturns

i

out to b e a dimensional LP problem Simply intersect each of the halfplanes with this line

Eachintersection will take the form of a ray that lies on the line We canthinkofeachray

Lecture Notes CMSC M

as representing an interval unb ounded to either the left or to the right All we need to do is

to intersect these intervals and nd the p oint that maximizes the ob jective function that is

the lowest p oint Computing the intersection of a collection of intervals is very easy and can

b e solved in linear time We just need to nd the smallest upp er b ound and the largest lower

b ound

Lecture More Linear Programming

Thursday Oct

Reading Chapter in BKOS

Recap Last time we presented a simple incremental algorithm for linear programming in the plane

We are given a set of n halfspaces h h h and an ob jective function describ ed bya

n

vector c The goal is to nd the p oint p that has the maximum dot pro duct with c that is is

furthest in direction c sub ject to the constraint that it lies in the intersection of the halfspaces

the convex feasible region

Let us recall the algorithm last time from the p ersp ective of linear programming in d

dimensional space We are given a set of halfspaces and wewant to nd the p oint that

lies in the intersection of the halfspaces and is most extreme in some direction We start by

nding an initial set of d halfspaces that dene an initial b ounded solution We renumb er the

halfspaces so that these are the rst d halfspaces Let v b e the initial optimum vertex Then

d

we add halfspaces one at a time On adding the h we test whether v is feasible with resp ect

i i

to h Ifsowe set v v Otherwise we claim that the new optimum must lie on the

i i i

hyp erplane that b ounds h Weintersect all the previous i halfspaces with this hyp erplane

i

thus reducing the dimension of the problem by pro ject the ob jective function vector onto

this hyp erplane and then recursively solve the resulting d dimensional LP problem The

recursion b ottoms out when we get down to a dimensional LP problem which is just the

problem of intersecting a collection of intervals Thus wesolveaddimensional problem by

rep eatedly reducing it to a d dimensional problem until wegetdown to a dimensional

problem which is trivial to solve

Analysis What is the worstcase running time of this algorithm in the planar case There are

roughly n halfspace insertions In step iwemay either nd that the current optimum vertex

is feasible in which case the pro cessing time is constant On the other hand if the current

optimum vertex is infeasible then wem ust solve a dimensional linear program with i

constraints In the worst case this second step o ccurs all the time and the overall running

time is given by the summation

n n

X X

nn

i O n i

i i

from standard results on summations see Cormen et al

Randomized Algorithm The O n time is not very encouraging considering that we could

compute the entire feasible region in O n log n time But we presented it b ecause it leads to

avery elegant randomized O n time algorithm The algorithm op erates in exactly the same

way but we insert the halfplanes in random order This is called a randomizedincremental

algorithmFor example just prior to calling the algorithm given last time we call a pro cedure

for randomly p ermuting the initial input list Our text gives an example

We analyze the running time in the exp ected case where weaverage over all np ossible p erm u

tations It is imp ortant to observe that the analysis makes no assumptions ab out the nature

Lecture Notes CMSC M

of the input only on the random p ermutation used In other words there are no bad inputs

only bad random p ermutations The fact that the rst two halfplanes were chosen sp ecially

adds a confusing element to this To b e correct we should think of them as b eing xed and

we randomize over the n p erm utations of the remaining halfplanes However well try

to ignore this complicating factor b elow

To analyze the algorithm we use an interesting technique called backward analysis Before

discussing backward analysis think of howa typical probabilistic analysis eg the one used

for quicksort works At each stage the algorithm has a set of random choices that might

b e made For example in quicksort the choice is which element to select as the pivot

Eachchoice has a certain probability of o ccuring Typically all choices are equally likely

We analyze the eect of eachchoice on the running time and then multiply each times it

probability of o ccuring and sum everything up to get the exp ected running time

The diculty of applying this to a problem like the linear programming problem is that at the

next stage it is very dicult to predict what is going to happ en since it dep ends heavily on

what has gone on up to this p oint In a backwards analysis rather than asking what is the

eect of the next random choice on the running time we ask what was the eect of the previous

random choice This may sound just like like a semantical distinction but the remarkable fact

is that it really makes things much easier to analyze The reason is that wehavefullknowledge

of the past

Consider the example shown b elow Wehave i random halfplanes that have b een added

so far and v v is the current optimum vertex see the gure Rather than consider which

i

halfplane will b e added next lets consider whichonewas added last For example if h was

the last to b e added then imagine the picture without h Prior to this v would have b een the

optimum vertex Therefore if h was added last then it would have b een added with O

cost This applies to all the other halfplanes as well except those that dene v namelyh and

h For example if h was added last then prior to its addition wewould have had a dierent

optimum vertex namely v Thus if h or h were added last then it would incur the higher

running time of O i to solve the dimensional LP problem

h5

h13 c

h4

v h8 v’

h15 h

11 h3

Figure Backward analysis

What is the probabilityofeach of these events o ccuring The imp ortant observation here is

that the order in which halfplanes are inserted in completely indep endent of the geometric

structure Among the halfplanes in the diagram so far fh h h h h h h g there are

an equal number of permutations of these ending with h as there are ending with h as there

Lecture Notes CMSC M

are with any of them in particular Here w e are ignoring the two initial halfplanes which

are xed Imagine that they lie outside of the p ortion shown in the gure Thus each halfplane

has an equal probabilityofi of b eing the last halfplane to b e added Among the i halfplanes

present two of them the two that b ound the currentoptimum vertex would incur a cost of

O i on the running time and the other i would incur a cost of O Thus there is

ai chance of incuring time O i and a i i chance of incuring time O Thus the

exp ected time for the ith stage is

i

O i O O

i i

If we sum this up over all n stages wejustgetO n as the total exp ected running time by

the linearity of exp ectation

This may all seem like a bit of probabilistic magic If you nd it unb elievable you are

encouraged to draw a set of halfplanes and exp eriment with dierent orders to convince yourself

at least at an intuitivelevel of the soundness of this technique We will b e applying it on

other randomized algorithms this semester

Unb ounded LPs We b egan by assuming that we could always nd two or generally d initial

halfplanes to provide us with an initial b ounded optimal vertex Wenever dealt with this

issue but we claim that it is always p ossible to determine either that the LP is unb ounded

or to determine a pair of halfplanes that b ound the feasible region in O n time Our b o ok

presents an algorithm for doing this in the plane This algorithm has the nice feature that it

generalizes to higher dimensions although they leave the generalization as an exercise

In the planar case there is a much simpler algorithm than this Consider the outward p oint

ing normal vectors for the various halfplanes imagine they are scaled to unit length They

partition the unit circle into n angular sectors Now consider the angular sector that contains

the ob jectivevector c Consider the two halfplanes lying immediates clo ckwise and counter

clo ckwise from c If the angle b etween these two normals is less than degrees then the no

matter how far apart they are these two halfplanes will converge at a p oint p and the feasible

set if it is nonempty will lie in the cone b ounded by these halfplanes

c

Figure Boundedness test

Intersecting with a hyp erplane Our b o ok do es not talk ab out howwegoaboutintersecting

given set of halfspaces with a hyp erplane Suce it to say that it is a geometric primitive

that can b e evaluated in O d time p er hyp erplane For completeness lets consider how this

might b e done

Supp ose that the halfspace that we just added was given by the inequality

h a x a x a x b

i i i id d i

The corresp onding hyp erplane is given by the equation

a x a x a x b

i i i id d i

Lecture Notes CMSC M

We can express this more succinctly in matrix notation Let A denote the d vector

i

consisting of the ith rowoftheA matrix A a a a The inequalitymaybe

i i i id

written A x b where x is a d vector and b is a scalar

i i i

Wewanttointersect the other halfspaces with this hyp erplane Furthermore wewould like

to represent the result as a LP in d dimensional problem Observe that after intersection

the hyp erplane still resides in d space

The idea is to apply one step of Gauss elimination using the equation of to eliminate a

i

variable from all the other inequalities Let us assume that a if not select a dimension

i

k such that a andswap with the rst Consider an arbitrary constraint h that we

ik j

wish to intersect with

i

h A x b

j j j

To eliminate the rst dimension from h wemultiply A bya a and subtract from A

j i j i j

do the same for b and b

i j

a

j

A A A

i j

j

a

i

a

j

b b b

j i

j

a

i

To see that this works supp ose that x is a p oint on the hyp erplane implying that A x b

i i i

Supp ose that x satised constraint h Thenwehave

j

a

j

A x x A A

i j

j

a

i

a

j

A x A x

j i

a

i

a

j

b b b

i j

j

a

i

Thus every p ointonthehyp erplane satises the mo died constraint if and only if it satises

the original constraint A similar elimination can b e p erformed to the ob jectivevector cIt

is also easy to show that as is standard in Guass elimination the rst term of each equation

vanishes so we are left with a d dimensional problem Reversing the pro cess allows us to

pro ject the d dimensional solution backinto dspace

Lecture Orthogonal Range Searching

Tuesday Oct

Chapter in BKOS

Range Queries We shift our fo cus from algorithm problems to data structures for the next few

lectures In general we consider the question given a collection of ob jects prepro cess them

storing the results in a data structure of some variety so that queries of a particular form

can b e answered eciently Generally we measure data structures in terms of two quantities

the time needed to answer a query and the amount of space needed by the data structure

Often there is a tradeo b etween these twoquantities but most of the structures that we will

be interested in will have either linear or near linear space Prepro cessing time is an issue of

secondary imp ortance but most of the algorithms we will consider will have either linear of

O n log n prepro cessing time

Lecture Notes CMSC M

Range queries are queries of the general form given a set P of p oints list or count or compute

some commutative function of the subset of P lying within a given region Regions maybe

rectangles triangles halfspaces circles etc There are many data structures for pro cessing

range queries dep ending on the typ e of region

An imp ortant concept b ehind all geometric range searching is that the subsets that can b e

formed by simple geometric ranges is much smaller than the set of p ossible subsets called the

power set of P Given a particular class of ranges a range space can b e describ ed abstractly as

apairP R consisting of the p oints P and the collection R of all subsets of P that b e formed

by ranges of this class For example the following gure shows the range space assuming

rectangular ranges for a set of p oints in the plane In particular note that the sets f g and

f g cannot b e formed by rectangular ranges

R = { {}, {1}, {2}, {3}, {4}, 2 {1,2}, {1,3}, {2,3},{2,4},{3,4}, 1 {1,2,3}, {1,3,4}, {2,3,4} , {1,2,3,4} } 3

4

Figure Rectangular range space

Todaywe consider orthogonal rectangular range queries that is ranges dened by rectangles

whose sides are aligned with the co ordinate axes One of the nice thing ab out rectangular

ranges is that they can b e decomp osed into a collection dimensional searches

Onedimensional range queries Before consider how to solve general range queries let us con

sider how to answer dimension range queries or interval queriesWe are given a set of

p oints P fp p p g on the line and given an interval x x rep ort all the p oints

n lo hi

lying within the interval Our goal is to nd a data structure that can answer these queries

in O log n k time where k is the numb er of p oints rep orted an output sensitive result

Range counting queries can b e answered in O log n time with minor mo dications

Clearly one way to do this is to simply sort the p oints and apply binary search to nd the

rst p ointofP that is greater than or equal to x and less than or equal to x and then

lo hi

list all the p oints b etween However this will not generalize to higher dimensions

A basic approach to solving almost all range queries is to represent P as a collection of canonical

subsets fS S S g each S S where k is generally a function of n and the typ e of

k i

ranges such that the answer to any query can b e expressed as a disjoint union of a small

numb er of canonical subsets Note that these subsets mayoverlap each other The trickto

solving a range searching problem is to identify a collection of canonical subsets having these

prop erties and then nding the prop er subsets for a given range

Supp ose that the p oints of P are sorted in increasing order and then stored in the leaves of a

balanced binary tree We can asso ciate each no de of this tree with the canonical subset of

p oint stored in the leaves that are descendents of this no de This gives rise to O n canonical

subsets Further we claim that the canonical subsets corresp onding to any range can b e

computed in O log ntime

Given anyinterval x x we search the tree to nd the leaf whose key is greater than or

lo hi

equal to x and the leaf whose key is less than or equal to x Then wetake all of the

lo hi

Lecture Notes CMSC M

maximal subtrees lying b etween these two search paths In particular the two search paths

will generally travel along some common subpath until reaching a no de v where the two

split

paths split After this each search path go es its own way When the left path to x travels

lo

along a left edge of the tree then the right subtree lies entirely within the interval Similarly

when the right path to x travels along a right edge then the left subtree lies entirely within

hi

the interval The leaves of these maximal subtrees are the desired canonical subsets whose

disjoint union is the answer to the range queryToanswer a range rep orting querywe simply

traverse these subtrees rep orting the p oints of their leaves Toanswer a range counting query

we store the total number of points in each subtree and sum all of these counts

Since the search paths are of length at most log nitfollows that there are O log n total

canonical subsets Thus the range counting query can b e answered in O log n time For

rep orting queries since the leaves of each subtree can b e listed in time that is prop ortional to

the number of leaves in the tree a basic fact ab out binary trees it follows that the total time

in the searchisO log n k where k is the number of points rep orted

1,31

17,31 1,15 {9,12,14,15} {17,20,22,23}

9,15 17,23 25,31 1,7 {4,5} {25,27}

4,7 9,12 14,15 17,20 22,23 25,27 29,31 1,3 {3}

13 4 7 9 1214 1517 2022 232527 2931

xlo=2 xhi=28

Figure Canonical sets for interval queries

Thus dimensional range queries can b e answered in O log n time using O n storage How

can we extend this to higher dimensional range queries

Kdtrees The natural question is how to extend dimensional range searching to higher dimen

sions First we will consider kdtrees This data structure is easy to implement and quite

practical and useful for many dierenttyp es of searching problems nearest neighb or search

ing for example However it is not the asymptotically most ecient solution for the orthogonal

range searching as we will see later

The idea b ehind a kdtree is to extend the notion of a one dimension tree but alternate is

using the xory co ordinates to split on In general dimension the kdtree cycles among the

various p ossible splitting dimensions

Eachinternal no de of the kdtree is asso ciated with twoquantities a splitting dimension either

x or y and a splitting value sIthastwo subtrees Since the splitting dimension alternates

between x and y some implementations do not store this explicitly but keep track of it while

traversing the tree If the splitting dimension is x then all p oints whose xco ordinates are less

than or equal to s are stored in the left subtree and p oints whose xco ordinates are greater

than or equal to s are stored in the right subtree If a p oints co ordinate is equal to sthenwe

reserve the right to store it on either side This is done to allow us to balance the number of

p oints in the left and right subtrees When a single p oint or more generally a small constant

numberofpoints remains we store it in a leaf

How is the splitting value chosen To guarantee that the tree is balanced the most common

metho d is to let the splitting value b e the median splitting co ordinate The resulting tree will

Lecture Notes CMSC M

have O log nheight

It is p ossible to build a kdtree in O n log n time by a simple recursive pro cedure The most

costly step of the pro cess is determining the median co ordinate However if we presort the

p oints into two crossreferenced lists one sorted by x and the other sorted by y thenitis

an easy matter to nd the median at each step The two lists can then b e split in O n

time each where n is the numb er of remaining p oints This leads to a recurrence of the form

T nT n n which solves to O n log n

Searching the kdtree Toanswer an orthogonal range query we pro ceed as follows Let R denote

the query rectangle Assume that the current splitting line is vertical The horizontal case

is similar Let v denote the current no de in the tree Observe that each no de of the tree is

naturally asso ciated with a rectangular region of space Call this regv The search pro ceeds

as follows If v is a leaf then wecheckthepoin ts stored in v as to whether it lies in RIf

so we rep ortcount them If v is an internal no de then we rst consider the left subtree If

its region lies entirely within R then we call a dierent routine to enumerate all the p oints in

this subtree or for a counting query we return a precomputed count of the numb er of p oints

in this subtree If the left childs region partially overlaps R then we search it recursively If

the left childs region do es not overlap R at all then we ignore it We do the same for the

rightchild of v

p

n Howmany no des do es this metho d visit altogether We claim that the total number is O

k where k is the numb er of p oints rep orted

Theorem The times needed to answer an orthogonal range query using kdtree with n p oints

p

in O n k where k is the numb er of rep orted p oints

Pro of First observe that for each subtree with m points we can enumerate the p oints of this

subtree in O m time by a simple traversal Thus it suces to b ound the number of

no des visited in the search not counting subtree enumeration

Tocount the numb er of no des visited rst observe that if we visit a no de then its

asso ciated region must intersect one of the four sides of the rectangle range Otherwise

it lies entirely inside or outside and so is not visited We will do this separately for each

of the four sides and multiply the result byfour

Rather than consider the line segment dening a side of the range rectangle we consider

the numb er of no des visited if we had applied an orthogonal range query to the entire

line on which this side lies This will only overestimate the numb er of no des visited

Because the kdtree pro cesses even and o dd levels dierentlyitwillbeimportantto

analyze twolevels at a time or generally d levels at a time for dimension d Let Qn

denote the query time for visiting a no de v that has n p oints descended from it Consider

any orthogonal line that intersects the region asso ciated with v Thekey observation

tersect at most two of the four subregions is that any horizontal or vertical line can in

asso ciated with the grandchildren of v The other two will either b e entirely contained

within the halfspace or lie entirely outside the halfspace In either case the algorithm will

not make a recursive call on them Since eachchild has half as manypoints b ecause

we split at the median the numberofpoints in each grandchild is roughly n Thus

we make at most two recursive calls on subtrees of size n This gives the following

recurrence

if n

Qn

Qn otherwise

p

n It is an easy pro cess to expand this recursion and derive the fact that it solves to O

p

Including the factor of four we still haveanO n b ound on the total number of nodes

p

visited and adding the enumeration time the total time is O n k as desired

Lecture Notes CMSC M

Lecture More Orthogonal Range Searching

Thursday Oct

Read Chapter in BKOS

Orthogonal Range Trees Last time wesaw that kdtrees could b e used to answer orthogonal

p

range queries in the plane in O n k time Todaywe consider a b etter data structure

called orthogonal range trees

d

An orthogonal range tree is a data structure which in all dimensions d uses O n log n

d

space and can answer orthogonal rectangular range queries in O log n k time where k

is the numb er of p oints rep orted Prepro cessing time is the same as the space b ound Thus in

the plane we can answer range queries in time O log n and space O n log n We will present

the data structure in two parts the rst is a version that can answer queries in O log n time

in the plane and then we will showhowtoimprove this in order to strip o a factor of log n

from the query time

The data structure is based on the concept of leveling a complex multidimensional searchinto

a constantnumb er of simpler range searches In this case we will reduce a ddimensional range

search to a series of dimensional range searches

Supp ose you hav e a query which can b e stated as the intersection of a small numb er of simpler

queries For example a range query in the plane can b e stated as two range queries Find all

the p oints whose xco ordinates are in the range x x and all the p oints whose y co ordinates

lo hi

are in the range y y Let us consider how to do this for dimensional range queries and

lo hi

then consider how to generalize the pro cess First build a range tree for the rst range query

which in this case is just a dimensional range tree for the xrange Recall that this is just

a balanced binary tree on these p oints sorted by xco ordinates Also recall that eachnodeof

this binary tree is implicitly asso ciated with a canonical subset of p oints These are the p oints

lying in the subtree ro oted at this no de The answer to any dimensional range query can

b e represented as the disjoint union of a small collection of m O log n canonical subsets

fS S S g where each subset corresp onds to a no de in the search This constitutes the

m

rst level of the search tree For the second level for eachnode v in this xrange tree we build

an auxiliary tree each of whichisay co ordinate range tree whichcontains all the p oints in

the canonical subset asso ciated with v

h that each no de p oints to auxiliary Thus the data structure consists of a xrange tree suc

y range tree This notion of a tree of trees is basic to solving range queries by leveling For

example for ddimensional range trees wewillhave dlevels of trees

To answer a querywe determine the canonical sets that satisfy the rst query there will b e

O log n of them Each of these sets is just represented as a no de in the range tree Weknow

that that these sets are disjoint and that every p oint in these sets lies within the range of

xco ordinates Thus to answer the querywe just need to nd out which p oints from each

canonical subset lies within the range of y co ordinates Todothisforeach canonical subset

we access the auxiliary tree for this no de and p erform a dimensional range search on the

y range This pro cess is illustrated in the following gure

What is the query time for a range tree Recall that it takes O log ntimetolocatethenodes

representing the canonical subsets for the dimensional range queryFor each weinvokea

dimensional range search Thus there O log n canonical sets eachinvoking an O log n

range search for a total time of O log n As b efore listing the elements of these sets can b e

p erformed in additional k time by just traversing the trees Counting queries can b e answered

b y precomputing the subtree sizes and then just adding them up

d

The space used by the data structure is O n log n in the plane and O n log nindi

mension d The reason comes by summing the sizes of the two data structures The tree for

Lecture Notes CMSC M

x-range tree

xlo xhi y hi Level 2 canonical sets.

ylo

Level 1 canonical sets.

Figure Range tree search

the xco ordinates requires only O n storage But we claim that the total storage in all the

auxiliary trees is O n log n Wewanttocount the total sizes of all these trees The number of

no des in a tree is prop ortional to the numberofleaves and hence the numb er of p oints stored

in this tree Rather than countthenumberofpoints in each tree separately instead let us

countthenumb er of trees in whicheachpoint app ears This will give the same total Observe

that a p oint app ears in the auxiliary trees of each of its ancestors Since the tree is balanced

eachpointhasO log n ancestors and hence eachpoint app ears in O log n auxiliary trees

It follows that the total size of all the auxiliary trees is O n log n

By the way observe that b ecause the auxiliary trees are just dimensional trees we could

just store them as a sorted array

We claim that it is p ossible to construct a dimensional range tree in O n log n time Con

structing the dimensional range tree for the xco ordinates is easy to do in O n log n time

However w e need to b e careful in constructing the auxiliary trees b ecause if wewere to sort

each list of y co ordinates separately the running time would b e O n log n Instead the trick

is to construct the auxiliary trees in a b ottomup manner The leaves whichcontain a single

p oint are trivially sorted Then we simply merge the two sorted lists for eachchild to form

the sorted list for the parent Since sorted lists can b e merged in linear time the set of all

auxiliary trees can b e constructed in time that is linear in their total since or O n log n Once

the lists have b een sorted then building a tree from the sorted list can b e done in linear time

Summarizing here is the basic idea to this and many other query problems based on leveled

searches Let S R denote the range space consisting of p oints S and range sets R Con

struct a data structure which represents S by a collection of canonical sets fS S S g

m

For each canonical subset construct a data structure for answering the second typ e of range

query and so on The main prop erty of the canonical subsets is that for any range query

we can eciently determine a small numb er of canonical sets whose disjoint union is equal to

the answer to the query in our case this was O log n subsets Furthermore this collection

of canonical subsets can b e determined eciently in our case in O log n time Toansw er a

range querywesolve the rst range query resulting in a collection of canonical subsets whose

Lecture Notes CMSC M

union is the answer to this queryWe then invoke the second range query problem on eachof

these subsets and so on Finally we take the union of all the answers to all these queries

Fractional Cascading Can we improveonthe O log n query time Wewould like to reduce

the query time to O log n As we descend the searchthe xinterval tree for eachnodewe

visit weneedtosearch the corresp onding y interval tree It is this combination that leads

to the squaring of the logarithms If we could searcheach y interval in O time then we

could eliminate this second log factor The trick to doing this is used in a numb er of places in

computational geometry and is generally a nice idea to remember We are rep eatedly searching

dierent lists but always with the same key The idea is to merge all the dierent lists into

a single massive list do one search in this list in O log n time and then use the information

ab out the lo cation of the key to answer all the remaining queries in O time each This is a

simplication of a more general searchtechnique called fractional cascading

In our case the massive list on whichwe will do one searchistheentire of p oints sorted by

y co ordinate In particular rather than store these p oints in a balanced binary tree let us

assume that they are just stored as sorted arrays The idea works for either trees or arrays

but the arrays are a little easier to visualize Call these the auxiliary listsWe will do one

exp ensive search on the auxiliary list for the ro ot which takes O log n time However after

this we claim that wecankeep track of the p osition of the y range in each auxiliary list in

constant time as we descend the tree of xco ordinates

Here is howwe do this Let v b e an arbitrary internal no de in the range tree of xco ordinates

and let v and v b e its left and rightchildren Let A b e the sorted auxiliary list for v and

L R v

let A and A b e the sorted auxiliary lists for its resp ectivechildren ObservethatA is the

L R v

disjoint union of A and A assuming no duplicate y co ordinates For each elementinA

L R v

we store twopointers one to the item of equal or larger value in A and the other to the item

L

of equal or larger value in A If there is no larger item the p ointer is null Observe that

R

once weknow the p osition of an item in A then we can determine its p osition in either A

v L

or A in O additional time

R

Here is a quick illustration of the general idea Let v denote a no de of the xtree and let v

L

and v denote its left and rightchildren Supp ose that in b ottom to top order the asso ciated

R

no des within this range are hp p p p p p i and supp ose that in v we store the p oints

L

hp p p i and in v we store hp p p i Thisisshown b elow For each p oint in the auxiliary

R

list for v we store a p ointer to the lists v and v to the p osition this elementwould b e

L R

y values That is we store a p ointer to the inserted in the other list assuming sorted by

largest element whose y value is less than or equal to this p oint

p6 v p5 p4 p3 p1 p2 p3 p4 p5 p6 vLRv p2

p2 p3 p5 p1 p4 p6

p1

Figure Cascaded search in range trees

At the ro ot of the tree we need to p erform a binary search against all the y values to determine

which p oints lie within this interval for all subsequentlevels once weknow where the y interval

falls with resp ect to the order p oints here we can drop down to the next level in O time

Lecture Notes CMSC M

Thus as with fractional cascading the running time is O log n rather than O log n It

turns out that this trick can only b e applied to the last level of the search structure b ecause

all other levels need the full tree search to compute canonical sets

d

Theorem Given a set of n p oints in R orthogonal rectangular range queries can b e answered

d d

in O log n k time from a data structure of size O n log nwhichcanbe

d

constructed in O n log ntime

Lecture Planar Point Lo cation

Tuesday Oct

Todays material is not covered in our text

Point Lo cation Todaywe consider is the problem The problem in space is

given a p olygonal sub division of the plane with n vertices prepro cess this sub division so that

h face of the sub division contains q given a query p oint q we can eciently determine whic

Wemay assume that each face has some identifying lab el which is to b e returned We also

assume that the sub division is represented in any reasonable form eg as a DCEL

In general q may coincide with an edge or vertex To simplify matters we will assume that q

do es not lie on an edge or vertex but these sp ecial cases are not hard to handle Our b o ok

discusses how to handle degeneracies As usual this is done bycho osing a careful way to break

ties

It is remarkable that although this seems likesuch a simple and natural problem it to ok quite

a long time to discover an query timespace optimal solution It has long b een known that

there are data structures that can p erform these searches reasonably well eg quadtrees

and kdtrees but for which no go o d theoretical b ounds could b e proved There were data

structures of with O log n query time but O n log n space and O n space but O log n

query time

The rst construction to achievebothO n space and O log n query time was a remarkably

clever construction due to Kirkpatrick It turns out that Kirkpatricks idea has some large

emb edded constant factors that make it less attractive practically but the idea is so clever

that it is worth discussing nonetheless Later we will discuss a more practical randomized

metho d that is presented in our text

Kirkpatricks Algorithm Kirkpatricks idea starts with the assumption that the planar sub divi

sion is a triangulation and further that the outer face is a triangle If this assumption is not

met then we b egin by triangulating all the faces of the sub division The lab el asso ciated with

each triangular face is the same as a lab el for the original face that contained it For the outer

face is not a triangle rst compute the convex hull of the p olygonal sub division triangulate

everything inside the convex hull Then surround this convex p olygon with a large triangle

call the vertices a bandc and then add edges from the convex hull to the vertices of the

convex hull It may sound likewe are adding a lot of new edges to the sub division but recall

from earlier in the semester that the numb er of edges and faces in any straightline planar

sub division is prop ortional to n the number of vertices Thus the addition only increases the

size of the structure by a constant factor

Note that once we nd the triangle containing the query p oint in the augmented graph then

we will know the original face that contains the query p oint The triangulation pro cess can b e

p erformed in O n log n time byaplanesweep of the graph or in O n time if you wantto

use sophisticated metho ds like the linear time p olygon triangulation algorithm In practice

Lecture Notes CMSC M

a b

c

Figure Triangulation of a planar sub division

many straightline sub divisions may already haveconvex faces and these can b e triangulated

easily in O n time

Let T denote the initial triangulation What Kirkpatricks metho d do es is to pro duce a

sequence of triangulations T T T T where k O log n suchthatT consists only of

k k

a single triangle the exterior face of T and each triangle in T overlaps a constantnumber

i

of triangles in T

i

We will see how to use such a structure for p oint lo cation queries later but for now let us

concentrate on how to build such a sequence of triangulations Assuming that wehave T we

i

wish to compute T In order to guarantee that this pro cess will terminate after O log n

i

stages we will wanttomake sure that the number of vertices in T decreases by some

i

constant factor from the n umber of vertices in T In particular this will b e done by carefully

i

selecting a subset of vertices of T and deleting them and along with them all the edges

i

attached to them After these vertices have b een deleted we need retriangulate the resulting

graph to form T The question is Howdowe select the vertices of T to delete so that

i i

each triangle of T overlaps only a constantnumb er of triangles in T

i i

There are two things that Kirkpatrick observed at this p oint that make the whole scheme

work

Constant degree We will make sure that eachofthevertices that we delete have constant

d degree that is each is adjacenttoatmostd edges Note that the when we

delete suchavertex the resulting hole will consist of at most d triangles When we

retriangulate each of the new triangles can overlap at most d triangles in the previous

triangulation

Indep endent set We will makesurethatnotwoofthevertices that are deleted are adjacent

to each other that is the vertices to b e deleted form an independent set in the current

planar graph T This will make retriangulation easier b ecause when we remove m

i

indep endentvertices and their incident edges we create m indep endent holes non

triangular faces in the sub division whichwewillhave to retriangulate However each

of these holes can b e triangulated indep endently of one another Since each hole contains

a constantnumber of vertices we can use any stupid triangulation algorithm since the

running time will b e O anyway

The big question is whether such a subset exists That is given any triangulation can wealways

nd a indep endentsubsetofvertices of b ounded degree whose size is at least a constant fraction

of the size of the whole vertex set Fortunately the answer is yes and in fact it is quite

easy to nd such a subset Part of the trickistopickthevalue of d to b e large enough to o

small and there may not b e enough of them It turns out that d is go o d enough

Theorem Given a planar graph with n vertices there is an indep endent set consisting of

vertices of degree at most with at least n vertices This indep endent set can b e

constructed in O n time

Lecture Notes CMSC M

Wow The numb er is probably smaller in practice but this is the b est b ound that this

pro of generates However the size of this constant is one of the reasons that Kirkpatricks

algorithm is not used in practice But the construction is quite clever nonetheless and once

a simple solution is known to a problem it is often not long b efore a practical solution

follows

Before proving this theorem we rst complete the description of the p oint lo cation algorithm

We start with T and rep eatedly select an indep endent set of vertices of degree at most

However never include the three vertices a bandc forming the outer face in suchan

indep endent set We delete these vertices from the graph and retriangulate the resulting

holes Observe that each triangle in the new triangulation can overlap at most triangles in

the old triangulation Since we can eliminate a constant fraction of vertices with each stage

after O log n stages wewillbedowntothelastvertices

The constant factors here are not so great With each stage the numberofvertices falls bya

k

factor of To reduce to the nal vertices implies that n or that

k log n lg n

It can b e shown that byalways selecting the vertex of smallest degree this can b e reduced to

a more palatable lgn

Point lo cation algorithm Now to p erform p oint lo cation we create a tree The ro ot of the tree

is the single triangle of T The no des at the next lower level are the triangles of T followed

k k

by T until wereach the leaves which are the triangles of our initial triangulation T Each

k

no de for a triangle in triangulation T stores p ointers to all the triangles it overlaps in T

i i

there are at most of these

Tolocateapoint we start with the ro ot T If the query p oint do es not lie within this single

k

triangle then we are done it lies in the exterior face Otherwise we searcheach of the at

most triangles in T that overlap this triangle When we nd the correct one we search

k

each of the triangles in T that overlap this triangles and so forth Eventually we will nd

k

the triangle containing the query p oint in the last triangulation T and this is the desired

output

es a constant amountoftimeto The tree has O log n levels one for each triangulation it tak

move from one level to the next at most p ointintriangle tests thus the total query time

is O log n The size of the data structure is the sum of sizes of the triangulations Since the

numb er of triangles in a triangulation is prop ortional to the numberofvertices it follows that

the size is prop ortional to

n n

using standard formulas for geometric series Thus the data structure size is O n again

with a pretty hefty constant

Construction and Analysis The last thing that remains is to showhow to construct the inde

p endent set of the appropriate size We rst present the algorithm for nding the indep endent

set and then prove the b ound on its size

Mark all no des of degree

While there exists an unmarked no de do the following

a Cho ose an unmarked vertex v

b Add v to the indep endent set

c Mark v and all of its neighb ors

Lecture Notes CMSC M

ko z n y m x T j h g T v t 0 l i 1 w u a cd p f q r s b e

G J F T3 T2 E D H I A B C

T4 (not shown) Triangulation Refinement.

K T0

HI J T1

AB C D EFG T2

p qrstuvwxyzT3

abc def gh ijklmno T4

Final Point Location Tree.

Figure Kirkpatricks p oint lo cation algorithm

Lecture Notes CMSC M

It is easy to see that the algorithm runs in O n time eg bykeeping unmarked vertices in

astack and representing the triangulation so that neighb ors can b e found quickly

Intuitively the argument that there exists a large indep endent set of low degree is based on

the following simple observations First b ecause the average degree in a planar graph is less

than there must b e a lot of vertices of degree at most otherwise the average would b e

unattainable Second whenever we add one of these vertices to our indep endent set only

other vertices b ecome ineligible for inclusion in the indep endent set

Here is the rigorous argument Recall from Eulers formula that if a planar graph is fully

triangulated then the numb er of edges e satises e n If we sum the degrees of all the

vertices then each edge is counted twice Thus the average degree of the graph is

X

deg v e n n

v

Next we claim that there must b e at least nvertices of degree or less To see whysuppose

to the contrary that there were more than nvertices of degree or greater The remaining

vertices must have degree at least with the p ossible exception of the vertices on the outer

face and thus the sum of all degrees in the graph w ould have to b e at least as large as

n n

n

whichcontradicts the equation ab ove

Now when the ab ove algorithm starts execution at least nvertices are initially unmarked

Whenever we select suchavertex b ecause its degree is or fewer we mark at most new

vertices this no de and at most of its neighb ors Thus this step can b e rep eated at least

nn times b efore we run out of unmarked vertices This completes the pro of

Lecture More Planar PointLocation

Thursday Oct

Read Chapt of BKOS

More Point Lo cation Last time we presented Kirkpatricks p oint lo cation algorithm Todaywe

will consider another asymptotically optimal algorithm for p oint lo cation but the interesting

element of this algorithm is that it is randomized and in particular it is based on a randomized

incremental construction We will show that the size prepro cessing time and query time are

O n O n log n and O log n resp ectively in the exp ected case Here the exp ectation is

indep endent of the choice of the p olygonal sub division or the query p oint It dep ends only on

the order in which the ob jects are inserted

Trap ezoidal Map The algorithm is based on a construction called a trapezoidal map which also

go es under many other names in the computational geometry literature Although we nor

mally think of the input to a p oint lo cation algorithm as b eing a planar sub division we will

dene the algorithm under the assumption that the input is just a collection of line segments

S fs s s gsuch that these line segments do not intersect except p ossibly at their

n

endp oints To construct a trap ezoidal map imagine sho oting a bullet vertically upwards and

downwards from eachvertex in the p olygonal sub division For simplicitywe will assume that

there are no vertical segments in the initial sub division and no twosegments have the same

xco ordinate Both of these are easy to handle with an appropriate symb olic p erturbation

The bullet travels until it hits another line segmentofS The resulting bullet paths together

with the initial line segments dene the trap ezoidal map Toavoid innite bullet paths at the

Lecture Notes CMSC M

Figure Trap ezoidal map

top and b ottom of the sub division wemay assume that the initial sub division is contained

entirely within a large b ounding rectangle An example is shown in the gure b elow

First observe that all the faces of the resulting sub division are trap ezoids with vertical sides

The left or right side might degenerate to a line segment of length zero implying that the

resulting trap ezoid degenerates to a triangle We claim that the pro cess of converting an

arbitrary p olygonal sub division into a trap ezoidal decomp osition increases its size byatmost

a constant factor The nal trap ezoidal map will b e given as a sub division represented say

using a DCEL

Claim Given a p olygonal sub division with n segments the resulting trap ezoidal map has at

most n vertices and n trap ezoids

Pro of To prove the b ound on the number of vertices observethateachvertex sho ots two

bullet paths each of which will result in the creation of a new vertex Thus each original

vertex gives rise to three vertices in the nal map Since each segment has twovertices

this implies at most n vertices

To b ound the numb er of trap ezoids observe that for each trap ezoid in the nal map its

left side and its rightaswell is b ounded byavertex of the original p olygonal sub division

The left endp ointofeach line segment can serve as the left b ounding vertex for two

trap ezoids one ab ove the line segment and the other b elow and the right endp ointofa

line segment can serve as the left b ounding vertex for one trap ezoid Thus each segment

of the original sub division gives rise to at most three trap ezoids for a total of n The

last trap ezoid is the one b ounded by the left side of the b ounding b ox

An imp ortant fact to observe ab out each trap ezoid is that it is dened by exactly four entities

from the original sub division a segmentontopasegment on the b ottom a b ounding vertex

on the left and a b ounding vertex on the right This simple observation will play an imp ortant

role in the analysis

Trap ezoidal decomp ositions like triangulations are interesting data structures in their own

right It is another example of the idea of converting a complex shap e into a disjoint collection

of simpler ob jects The fact that the sides are vertical makes trap ezoids simpler than arbitrary

quadrilaterals Finally observe that the trap ezoidal decomp osition is a renement of the orig

inal p olygonal sub division and so once we knowwhich face of the trap ezoidal map a query

p oint lies in we will knowwhich face of the original sub division it lies in either implicitlyor

b ecause we lab el each face of the trap ezoidal map in this way

Construction We could construct the trap ezoidal map easily by plane sweep Hop efully this

is an easy exercise by this p oint but think ab out howyou would do it We will build the

trap ezoidal map by a randomized incremental algorithm b ecause the p oint lo cation algorithm

is based on this construction In fact historically this algorithm arose as a metho d for

Lecture Notes CMSC M

computing the trap ezoidal decomp osition of a collection of intersecting line segments and the

p oint lo cation algorithm arose as an artifact that was needed in the construction

The incremental algorithm starts with the initial b ounding rectangle that is one trap ezoid

and then we add the segments of the p olygonal sub division one by one in random order As

each segment is added we up date the trap ezoidal map Let S denote the subset consisting of

i

the rst i random segments and let T denote the resulting trap ezoidal map

i

To p erform the up date this we need to knowwhich trap ezoid the left endp oint of the segment

lies in We will let this question go until later since it will b e answered by the p oint lo ca

tion algorithm itself Then we trace the line segment from left to right determining which

trap ezoids it intersects Finallywe go back to these trap ezoids and x them up There are

two things that are involved in xing First the left and right endp oints of the new segment

need to have bullets red from them Second one of the earlier bullet paths might hit this

line segment When that happ ens the bullet path must b e trimmed back Weknowwhich

vertices are from the original sub division vertices so weknow which side of the bullet path to

trim The pro cess is illustrated in the gure b elow

Figure Incremental up date

Observe that the structure of the trap ezoidal decomp osition do es not dep end on the order

in which the segments are added This observation will b e imp ortant for the probabilistic

analysis The following is also imp ortant to the analysis

Claim Ignoring the time sp ent to lo cate the left endp oint of an segment the time that it

takes to insert the ith segment and up date the trap ezoidal map is O k where k is the

i i

numb er of newly created trap ezoids

Pro of Consider the insertion of the ith segment and let K denote the numb er of bullet paths

that this segmentintersects We need to sho ot four bullets two from eachendpoint and

then trim eachofthe K bullet paths for a total of K op erations that need to b e

p erformed If the new segment did not cross any of the bullet paths then wewould get

exactly four new trap ezoids For eachoftheK bullet paths we cross we add one more to

the numb er of newly created trap ezoids for a total of K Thus letting k K be

i

the numb er of trap ezoids created the numb er of up date op erations is exactly k Each

i

of these op erations can b e p erformed in O time given any reasonable representation of

the trap ezoidal map eg a DCEL

Analysis We left one detail out whichishowwe lo cate the left endp oin tofeach new segment that

we add But ignoring the time for this whichwe will see will b e O log n time on average

we will show that the exp ected time to add each segmentisO Since there are n insertions

this will lead to a total exp ected time complexityof O n log n O n log n

We know that the size of the nal trap ezoidal map is O n It turns out that the total size of

the p oint lo cation data structure will actually b e prop ortional to the numb er of new trap ezoids

that are created with each insertion In the worst case when we add the ith segment it might

Lecture Notes CMSC M

cut through a large fraction of the existing O i trap ezoids and this would lead to a total

P

n

i n However the magic of the incremental construction is that size prop ortional to

i

this do es not happ en We will showthatonaverage each insertion results in only a constant

numb er of trap ezoids b eing created

You might stop to think ab out this for a moment b ecause it is rather surprising at rst

Clearly if the segments are short then each segment might not intersect very many trap ezoids

But what if all the segments are long It seems as though it might b e p ossible to construct a

counterexample Give it a try b efore you read this

Lemma Consider the randomized incremental construction of a trap ezoidal map and let

k denote the numb er of new trap ezoids created when the ith segment is added Then

i

E k O where the exp ectation is taken over all p ermutations of the segments

i

Pro of The analysis will b e based on a backwards analysis Let T denote the trap ezoidal map

i

after the insertion of the ith segment Because we are averaging over all p ermutations

among the i segments that are presentinT each one has an equal probability i of

i

b eing the last one to have b een added For each of the segments s wewant to count the

number of trapezoids that would have b een created had s been the last segment to be

added Lets say that a trap ezoid depends on an segment sifs would have caused

to b e created had s b een added last Wewant to countthenumb er of trap ezoids

that dep end on eachsegment and then compute the average over all segments If we let

s if segment s dep ends on and otherwise then the exp ected complexityis

X X

E k s

i

i

T sS

i i

Some segments mighthave resulted in the creation of lots of trap ezoids and other very few

Howdowe get a handle on this quantity The trick is rather than countthenumber

of trap ezoids that dep end on each segment we count the numb er segments that each

trap ezoid dep ends on The old combinatorial trick of reversing the order of summation

In other words wewant to compute

X X

E k s

i

i

T sS

i i

s

The segments that the trapezoid

The trapezoids that depend on s depends on.

Figure Trap ezoidsegment dep endencies

This is much easier to determine In particular each trap ezoid is b ounded by four sides

The top and b ottom sides are each determined byasegmentofS and clearly if either of

i

these was the last to b e added then this trap ezoid would have come into existence as a

Lecture Notes CMSC M

result The left and right sides are each determined by a endp ointofasegmentinS and

i

clearly if either of these was the last to b e added then this trap ezoid would have come

into existence Thus each trap ezoid is dep endent onatmostfoursegments implying

P

that s Since T consists of O i trap ezoids wehave

i

sS

i

X

jT j O iO E k

i i

i i i

T

i

Lecture Point Lo cation in Trap ezoidal Maps

Tuesday Oct

Read Chapt of BKOS

Point Lo cation Last time we presented a randomized incremental algorithm for constructing a

trap ezoidal map in the plane Todaywe consider how to mo dify this algorithm to answer

p oint lo cation queries The prepro cessing time will b e O n log n in the exp ected case as was

the time to construct the trap ezoidal map and the space and query time will b e O n and

O log n resp ectively in the exp ected case

Recall from last time that we are treating the input as a set of segments S fs s g

n

p ermuted randomly that S denotes the subset consisting of the rst i segments of S and T

i i

denotes the trap ezoidal map of S One imp ortantelement of the analysis to rememb er from

i

last time is that each time we add a new line segment it may result in the creation of the

collection of new trap ezoids whichwere said to depend on this line segment We presented

b er of new trap ezoids that are created with each stage is abackwards analysis that the num

exp ected to b e O This will play an imp ortant role in to days analysis

Point Lo cation Data Structure As in Kirkpatricks algorithm the p oint lo cation data struc

ture will b e based on a ro oted directed acyclic graph In particular to the query pro cessor

it will lo ok like a binary tree but there may b e sharing of subtrees There are twotyp es of

no des xnodes and y nodesEach xno de contains the xco ordinate of an endp oint of one of

the segments Its twochildren corresp ond to the p oints lying to the left and to the right of this

co ordinate Each y no de contains a p ointer to a segment The left and rightchildren corre

sp ond to whether the query p ointisaboveorbelowlinecontaining the segment resp ectively

We will visit a y no de only if we already know that the xco ordinate of the query p oint lies

between the left and right endp oints of the segment

Our construction of the p oint lo cation data structure mirrors the incremental construction of

the trap ezoidal map In particular if we freeze the construction just after the insertion of any

segment the existing structure will b e a p oint lo cation structure for the existing trap ezoidal

map In the gure b elowweshow a simple example of what the data structure lo oks likefor

two line segments from our textb o ok There is one leaf for each trap ezoid The y no des are

shown as hexagons For example if the query p oin t is in trap ezoid D wewould rst detect

that it is to the rightofp thenleftofq then b elow s the rightchild then rightofp

then ab ove s the left child

The question is howdowe build this data structure incrementally First observe that when

a new line segment is added we only need to adjust the p ortion of the tree that involves the

trap ezoids that have b een deleted as a result of this new addition This will b e set of leaves

in the current tree Eachsuch leaf will b e replaced with a new subtree which determines

which one of the new trap ezoids contains the query p oint In Kirkpatricks algorithm we just

said check each of the new triangles that overlapp ed one of the old triangles and we will do

essentially the same thing here As in Kirkpatricks algorithm it will turn out that each old

Lecture Notes CMSC M

p1 q B 1 q q1 A 2 p s 1 s1 1 B s2 G C E G p A D 2 E p C 2 s s2 2

F q2 DF

Figure Trap ezoidal map p oint lo cation data structure

trap ezoid is overlapp ed by a constantnumb er of new trap ezoids However let us consider the

pro cess in a little more detail here

Supp ose that we add a line segment This results in the replacement of an existing set of

trap ezoids with a set of new trap ezoids If the segment passes entirely through an existing

trap ezoid then there will b e twooverlapping trap ezoids in the new trap ezoidal map and

thus we just need to compare against the newly added segmentone y no de If the existing

trap ezoid contains one or b oth endp oints then we need to test on which sides of these endp oints

we lie one or two xno des and if we lie b etween them then we need to test whether we lie

ab oveorbelow the line segmentoney no de If weaddalinesegment to the example ab ove

resulting in the replacementofC D E and G with new trap ezoids we will replace these

leaves of the subtree as shown in the gure b elow It is imp ortant to notice that through

sharing each trap ezoid app ears exactly once as a leaf in the resulting structure

p1 q B 1 K q q1 A 2 p s 1 s1 1 I q q s 3 B s2 3 3 p A p N 2 s 3 p 3 p L M 3 s3 N 2 s s2 2 H F q s3 M H J 2 s3 F

I J K L

Figure Line segment insertion

Analysis We claim that the size of the p oint lo cation data structure is O n and the query time

is O log n b oth in the exp ected case As usual the exp ectation dep ends only on the order of

insertion not on the line segments or the lo cation of the query p oint

To prove the space b ound of O n observe that the numb er of new no des added to the

structure with each new segment is prop ortional to the numb er of newly created trap ezoids

This follows by observing that we create a constantnumb er of new no des for each existing

trap ezoid that was destroyed and the numb er of new trap ezoids is prop ortional to the number

Lecture Notes CMSC M

of old trap ezoids that were destroyed Last time weshowed that with each new insertion the

exp ected numb er of trap ezoids that were created was O Therefore weaddO new no des

with each insertion in the exp ected case implying that the total size of the data structure is

O n

Analyzing the query time is a little subtler In a normal probabilistic analysis of data structures

we think of the data structure as b eing xed and then compute exp ectations over random

queries Here the approach will b e to imagine that wehave exactly one query to handle

Imagine an adversary that to select the worstp ossible query p oint but do es not know

what random choices the algorithm made in building the data structure Wewillshow that

no matter how the query p oint is selected most random orderings of the line segments will

lead to a search path of length O log n in the resulting tree Since our analysis will b e made

without any assumptions on the nal trap ezoid in which q lies it will apply equally well to all

query p oints

Rather than consider the search path for q in the nal search structure we will consider how

q moves incrementally through the structure with the addition of each new line segment Let

denote the trap ezoid of the map that q lies in after the insertion of the rst i segments

i

Observe that if then insertion of the ith segment did not aect the trap ezoid that

i i

q was in and therefore q will stay where it is relative to the current search structure For

example if q was in trap ezoid B prior to adding s in the gure ab ove then the addition of s

do es not incur any additional cost to lo cating q However if then the insertion

i i

of the ith segment caused q s trap ezoid to b e deleted As a result q must lo cate itself with

resp ect to the newly created trap ezoids that overlap Since there are a constantnumber

i

of such trap ezoids at most four there will b e O work needed to lo cate q with resp ect to

these In particular q mayfallasmuch as three levels in the search tree For example if q

was in trap ezoid C b efore the addition of s in the gure ab ove and q was in trap ezoid J

afterwards then q would have to pass through two new levels of the structure as a result of

this insertion

To compute the exp ected length of the search path it suces to compute the probability

that the trap ezoid that contains q changes as a result of the ith insertion Let P denote this

i

probability Since q could fall through up to three levels in the search tree as a result of each

the insertion the exp ected length of q s search path in the nal structure is at most

n

X

P

i

i

Wewillshow that P iFrom this it will follow that the exp ected path length is at most

i

n n

X X

i i

i i

which is roughly ln n O log nby the Harmonic series

To showthat P iwe apply a backwards analysis Recall from last time that the trap ezoid

i

that contains q is dep endent on at most four trap ezoids which dene the top and b ottom edges

and the left and right sides of the trap ezoid Since each segment is equally likely to b e the

last segment to b e added the probability that the last insertion caused q to b elong to a new

trap ezoid is at most i This completes the pro of

Guarantees on SearchTime The only problem with this result is that even though the search

time is provably small in the exp ected case for a given query p oint it might still b e the case

that once the data structure has b een constructed there is a single very long path in the search

Lecture Notes CMSC M

structure and the user rep eatedly p erforms queries along this path The result provides no

guarantees on the running time of all queries

Although we will not prove it the b o ok presents a stronger result namely that the length of

the maximum search path is also O log n with high probability In particular they prove the

following

Lemma Given a set of n noncrossing line segments in the plane and a parameter the

probability that the total depth of the randomized search structure exceeds lnn

ln

is at most n

For example for the probability that the search path exceeds lnn isatmost

n The constant factors here are rather weak but a more careful analysis leads to

a b etter b ound

Nonetheless this itself is enough to lead to variant of the algorith for which O log n time is

guaranteed Rather than just running the algorithm once and taking what it gives instead

keep running it and checking the structures depth As so on as the depth is at most c log n for

some suitably chosen c then stop here Dep ending on c and n the ab ove lemma indicates how

long you may need to exp ect to rep eat this pro cess until the nal structure has the desired

depth For suciently large c the probability of nding a tree of the desired depth will b e

b ounded away from by some constant factor and therefore after a constantnumb er of trials

dep ending on this probability you will eventually succeed in nding a p oint lo cation structure

of the desired depth A similar argument can b e applied to the space b ounds

Theorem Given a set of n noncrossing line segments in the plane in exp ected O n log n

time it is p ossible to construct a p oint lo cation data structure of worst case size O n

that can answer p oint lo cation queries in worst case time O log n

Lecture Review for the Midterm

Thursday Oct

Midterm Exam Oct The exam will b e closedb o ok closednotes but you are allowed one

cheatsheet front and back of notes

What wevecovered so far

Geometric Background Ane geometry homogeneous co ordinates orientation test sym

b olici p erturbation

Convex hulls Grahams scan an O n log n algorithm

Line SegmentIntersection Plane sweep algorithm O n k log n where k is the number

of intersections

Representing planar sub divisions Eulers formula DCELs dual graphs

Polygon Triangulation The artgallery problem monotone decomp osition by plane sweep

in O n log n time triangulating monotone p olygons in O n time There exists an O n

time triangulation but it is quite complicated

Intersection of Halfplanes Divideandconquer solution that runs in O n log n time

Pointline duality The lower and upp er envelop es of a set of lines can b e computed in

O n log n time by applying p ointline duality and computing the convex hull of the dual

points

Lecture Notes CMSC M

Linear Programming Randomized incremental algorithm for low dimensional linear pro

grammingRunsinO dn exp ected time in dimension d

Orthogonal Range Searching kdtrees and range trees Both can b e constructed in O n log n

p

time Showed that kdtrees could b e used to answer orthogonal range queries in O n

time and that range trees could answer them in O log n time Both can b e generalized

d

to higher dimensions with range trees taking O log ntime

Planar PointLocation Kirkpatricks algorithm O n log n prepro cessing time O n space

and O log n query time Based on decimation of a triangulation

Trap ezoidal Maps Randomized incremental construction and p ointlocation O n log n

exp ected prepro cessing time and O n space and O log n query time

Techniques

Plane sweep

Divide and conquer

Randomized incremental construction

Decomp osing search problems into layers of trees

Pointline duality

Fractional cascading

Backwards analysis

Lecture Midterm

Tuesday Oct

Midterm Exam to day No lecture

Lecture Voronoi diagrams

Thursday Oct

Reading BKOS Chapt

Euclidean Geometry Wenow will make a subtle but imp ortant shift Up to know virtually

everything that wehave done has not needed the notion of angles lengths or distances except

for our work on circles All geometric tests were made on the basis of orientation tests a

purely ane construct

But there are imp ortant geometric algorithms which dep end on nonane quantities suchas

distances and angles Let us b egin by dening the Euclidean length ofavector v v v

x y

q

p

in the plane to b e jv j The v v and in general dimension it is jv j v v

x y

d

distance b etween two p oints p and q denoted distp q is dened to b e jp q j

Voronoi Diagrams Voronoi diagrams like convex hulls are among the most imp ortant structures

in computational geometryAVoronoi diagram records information ab out what is close to

what

Let P fp p p g b e a set of p oints in the plane or in any dimensional space which

n

wecallsites Dene V p the Voronoi cel l for p to b e the set of p oints q in the plane such

i i

Lecture Notes CMSC M

that distq p distq p That is the Voronoi cell for p consists of the set of p oints for

i j i

which p is the unique nearest neighbor to q

i

V p fq j distp q distp q j ig

i i j

Another way to dene V p is in terms of the intersection of halfplanes Given two sites p

i i

and p the set of p oints that are strictly closer to p than to p is just the open halfplane

j i j

whose b ounding line is the p erp endicular bisector b etween p and p Denote this halfplane

i j

hp p It is easy to see that a p oint q lies in V p if and only if q lies within the intersection

i j i

of hp p for all j i In other words

i j

V p hp p

i j i i j

Since the intersection of halfplanes is a p ossibly unb ounded convex p olygon it is easy to see

that V p is a p ossibly unb ounded convex p olygon Finally dene the Voronoi diagram of

i

P denoted VorP to b e what is left of the plane after weremove all the op en Voronoi cells

It is not hard to prove see the text that the Voronoi diagram consists of a collection of line

segments whichmaybeunb ounded either at one end or b oth

Figure Voronoi diagram

Voronoi diagrams haveanumb er of imp ortant applications These include

Nearest neighb or queries One of the most imp ortant data structures problems in com

putational geometry is solving nearest neighb or queries Given a p ointset P and given

a query p oint q determine the closest p ointinP to q This can b e answered by rst

computing a Voronoi diagram and then lo cating the cell of the diagram that contains q

Wehave already discussed p oint lo cation algorithms

Computational morphology Some of the most imp ortant op erations in morphology used

very much in computer vision is that of growing and shrinking or thinning

ob jects If wegrow a collection of p oints by imagining a grass re starting simultaneously

from each p oint then the places where the grass res meet will b e along the Voronoi

diagram The medial axis of a shap e used in computer vision is just a Voronoi diagram

of its b oundary

Facility lo cation Wewant to op en a new Blo ckbuster video It should b e placed as far as

p ossible from any existing video stores Where should it b e placed It turns out that the

vertices of the Voronoi diagram are the p oints that lo cally at maximum distances from

any other p oint in the set

High clearance path planning Arobotwants to move around a set of obstacles To mini

mize the p ossibility of collisions it should stay as far away from the obstacles as p ossible

To do this it should walk along the edges of the Voronoi diagram

Lecture Notes CMSC M

Prop erties of the Voronoi diagram Some theoretical observations ab out the Voronoi diagram

are warranted at this p oint

Voronoi edges Each p ointonanedgeoftheVoronoi diagram is equidistant from its two

nearest neighbors p and p Thus there is a circle centered at suchapoint such that p

i j i

and p lie on this circle and no other site is interior to the circle

j

Voronoi vertices It follows that vertex at which three Voronoi cells V p V p and V p

i j k

intersect is equidistant from all sites Thus it is the center of the circle passing through

these sites and this circle contains no other sites in its interior

Degree If we assume that no four p oints are co circular then the vertices of the Voronoi

diagram all have degree three

Convex hull A cell of the Voronoi diagram is unb ounded if and only if the corresp onding

site lies on the convex hull Observe that a p ointisontheconvex hull if and only if it

is the closest p oint from some p oint at innity

Size If n denotes the numb er of sites then the Voronoi diagram is a planar graph if we

imagine all the unb ounded edges as going to a common vertex innity with exactly n

faces It follows from Eulers formula that the numberofVoronoi verticesisatmost

n and the numb er of edges is at most n See the text for details

DelaunayTriangulation Since the Voronoi diagram is a planar graph wemay naturally ask

what is the corresp onding dual graph The vertices for this dual graph can b e taken to b e the

sites themselves Since assuming general p osition the vertices of the Voronoi diagram are of

degree three it follows that the faces of the dual graph excluding the exterior face will b e

triangles The resulting dual graph is a triangulation Among the many triangulations of a

set of p oints this one has a numb er of nice geometric prop erties and is called the Delaunay

triangulation

Figure Delaunay triangulation

Delaunay triangulations haveanumber of interesting prop erties that are consequences of the

structure of the Voronoi diagram

Convex hull The exterior face of the Delaunay triangulation is the convex hull of the p oint

set

Circumcircle prop erty The circumcircle of any triangle in the Delaunay triangulation is

empty containsnopoints of P

Empty circle prop erty Two sites p and p are connected by an edge in the Delaunay

i j

triangulation if and only if there is an empty circle passing through p and p One

i j

direction of the pro of is trivial from the circumcircle prop erty In general if there is an

empty circumcircle passing through p and p then the center c of this circle is a p oint

i j

Lecture Notes CMSC M

on the edge of the Voronoi diagram b etween p and p b ecause c is equidistant from each

i j

of these p oints and there is no closer p oint

Closest pair prop erty The closest pair of p oints in P are Delaunay neighb ors

There are a numb er of other interesting prop erties of Delaunay triangulations that are not so

easy to prove

MaxMin Angle criterion Among all triangulations of the p ointset P the Delaunay trian

gulation maximizes the minimum angle in the triangulation This only holds in dimension

MST prop erty The minimum spanning tree of a set of p oints in the plane is a subgraph of

the Delaunay triangulation

This provides a go o d algorithm for computing MSTs of p oints in the plane First compute

the Delaunay triangulation of the p oint set wewillshow this can b e done in O n log n time

and then in O n log n time you can compute the MST of this sparse graph

Lecture Fortunes Voronoi Diagram Algorithm

TuesdayNov

Reading BKOS Chapt

Computing Voronoi Diagrams Last time weintro duced the Voronoi diagram of a set of n p oints

P fp p g in the plane called sites Recall that this is a planar straightline sub division

n

with n faces each a p ossibly unb ounded convex p olygon The face or Voronoi cel l asso ciated

with site p denoted V p consists of all the p oints in the plane that are strictly closer to

i i

p thantoany other site Recall that the edge joining cells for p and p is the p erp endicular

i i j

bisector b etween these p oints and so a circle grown ab out any p ointonaVoronoi edge will

touch these two sites and contain no other site in its interior Also recall that the Voronoi

vertices are of degree three assuming general p osition and a cicle grown ab out this p oint will

touch all three sites an contain no other site in its center

There are a numb er of algorithms for computing Voronoi diagrams Of course there is a

naive O n log n time algorithm which op erates by computing V p byintersecting the n

i

bisector halfplanes hp p for j iHowever there are much more ecientways which

i j

run in O n log n time Since the convex hull can b e extracted from the Voronoi diagram in

O n time it follows that this is asymptotically optimal in the worstcase

Note from the comments made last time ab out the Delaunay triangulation that the Voronoi

diagram can either b e computed directly or else it can b e built by rst constructing the

Delaunay triangulation of the sites and then taking its dual graph with some care as to

where the Voronoi vertices are to b e placed Historically the rst algorithm for computing

Voronoi diagrams is the simple incremental algorithm that was used for computing Delaunay

triangulations It was known for manyyears that this is not asymptotically optimal and

in fact ran in O n timeintheworst case but this did not deter the practitioners who

were quite happy with it When computational geometry came along a more complex but

asymptotically sup erior O n log n algorithm was discovered This algorithm was based on

divideandconquer But it was rather complex and somewhat dicult to understand Later

SteveFortune invented a plane sweep algorithm for the problem whichprovided a simpler

O n log n solution to the problem It is his algorithm that we will discuss Somewhat later

still it was discovered that the incremental algorithm is actually quite ecient if it is run as

Lecture Notes CMSC M

a randomized incremental algorithm We will discuss this algorithm later but in the form of

aDelaunay triangulation algorithm

Before discussing Fortunes algorithm it is interesting to consider why this algorithm wasnt

invented much earlier In fact it is quite a bit trickier than any plane sweep algorithm wehave

seen so far The key to any plane sweep algorithm is the ability to discover all up coming

events in an ecient manner For example in the line segmentintersection algorithm we

considered all pairs of line segments that were adjacent in the sweepline status and inserted

their intersection p oint in the queue of up coming events The problem with the Voronoi

diagram is that of predicting where the up coming events will o ccur The reason is that a site

that lies ahead of the sweep line may generate a Voronoi vertex that lies b ehind the sweep line

It is these unanticipated events that make the design of a plane sweep algorithm challenging

Beach line Unanticipated Sweep line

events

Figure Plane sweep Voronoi diagrams

Fortunes Algorithm Fortune made the clever observation of rather than computing the Voronoi

diagram through plane sweep in its nal form instead to compute a distorted but top olog

ically equivalentversion of the diagram This distorted version of the diagram was based on

a transformation that alters the way that distances are measured in the plane The resulting

diagram had the same structure as the Voronoi diagram but its edges were parab olic arcs

rather than straight line segments Once this distorted diagram was generated it was an easy

matter to undistort it to pro duce the correct Voronoi diagram

Our presentation will b e dierentfromFortunes Rather than distort the diagram we can

think of this algorithm as distorting the sweep line Actuallywe will think of two ob jects

that control the sweeping pro cess First there will b e a horizontal sweep line moving from

top to b ottom We will also maintain a xmonotonic curve called a beach line I guess b ecause

it lo oks likewaves rolling up on a b each The b each line is formed from parab olic arcs As

the sweep line moves downward the b eachlinemoves downward as well but the b each lines

shap e dep ends on the lo cations of the sites We will see that the Voronoi diagram grows out

of the b each line

In order to make these ideas more concrete recall that the problem with ordinary plane sweep

is that sites that lie b elowthesweep line may aect the diagram that lies ab ovethesweep

tain only the p ortion of the diagram that cannot b e line Toavoid this problem we will main

aected byanything that lies b elowthesweep line To do this we will cut the halfplane

lying ab ovethesweep line into two regions those p oints that are closer to some site p ab ove

the sweep line than they are to the sweep line itself and those p oints that are closer to the

sweep line than anysiteabove the sweep line The set of p oints q that are equidistant from

the sweep line to their nearest site ab ovethesweep line is called the beach line Observe that

for anypoint q ab ovethebeach line we know that its closest p oint cannot b e aected byany

Lecture Notes CMSC M

site that lies b elow the sweep line Hence the p ortion of the Voronoi diagram that lies ab ove

the b each line is safe in the sense that wehave all the information that we need in order to

compute it without knowing ab outs what p oints are still to app ear b elowthesweep line

What do es the b each line lo ok like Weknow from high scho ol geometry that the set of

p oints that are equidistant from a site lying ab ove a horizontal line and the line itself forms

a parab ola that is op en on top With a little analytic geometryitiseasytoshow that the

parab ola b ecomes skinnier as the site b ecomes closer to the line the parab ola degenerates

into a vertical ray emanating from the site You should work out the equations to see why

this is so

Thus the b each line consists of the lower envelop e of these parab olas By the wayifwewere

interested in computing the Voronoi diagram of line segments the b each line is the b oundary

of the Voronoi cell of the sweep line itself Because the parab olas are xmonotone so is the

b each line Also observe that the vertex where two arcs of the b each line intersect whichwe

call a breakpointisapoint that is equidistant from two sites and the sweep line and hence

must lie on some Voronoi edge In particular if the b each line arcs corresp onding to p oints p

i

and p share a common breakp oint on the b each line then this breakp ointliesontheVoronoi

j

edge b etween p and p From this wehave the following imp ortantcharacterization

i j

Lemma The b eachlineisanxmonotone curve made up of parab olic arcs The breakp oints

of the b each line lie on Voronoi edges of the nal diagram

Fortunes algorithm consists of simulating the growth of the b each line as the sweep line moves

downward and in particular tracing the paths of the breakp oints as they travel along the edges

of the Voronoi diagram Of course as the sweep line moves the parab olas forming the b each

line change their shap es continuously As with all planesweep algorithms we will b e interested

in simulating the discrete event p oints where there is a signicantevent that is anyevent

that changes the top ological structure of the b each line It turns out these signicantevents

will b e of twovarieties

Site events When the sweep line passes over a new site a new arc will b e inserted into the

beach line

Vertex events What our text calls circle events When the length of a parab olic arc

shrinks to zero the arc disapp ears and a new Voronoi vertex will b e created at this p oint

The algorithm consists of pro cessing these tw otyp es of events As the Voronoi vertices are

b eing discovered byvertex events it will b e an easy matter to up date a DCEL for the diagram

as we go and so to link the entire diagram together For the rest of the lecture we fo cus on

the nature of the b each line and how these events are discovered and pro cessed

Site events A site event is generated whenever the sweep line passes over a site As wementioned

b efore at the instant that the sweep line touches the p oint its asso ciated parab olic arc will

degenerate to a vertical ray sho oting up from the p oint to the currentbeach line As the sweep

line pro ceeds downwards this ray will widen into an arc along the b each line To pro cess a site

eventwe will determine the arc of the sweep line that lies directly ab ove the new site Let us

make the general p osition assumption that it do es not fall immediately b elowavertex of the

b each line We then split this arc of the b each line in twoby inserting a new innitesimally

small arc at this p oint As the sweep pro ceeds this arc will start to widen and eventually will

join up with other edges in the diagram See the gure b elow

It is imp ortant to consider whether this is the only way that new arcs can b e intro duced into

the sweep line In fact it is We will not prove it but a careful pro of is given in the text As a

consequence of this pro of it follows that the maximum numb er of arcs on the b each line can

Lecture Notes CMSC M

Figure Site events

b e at most n since each new p oint can result in creating one new arc and splitting an

existing arc for a net increase of two arcs p er p oint except the rst

The nice thing ab out site events is that they are all known in advance Thus after sorting

the p oints by y co ordinate all these events are known However the other typeofevent are

somewhat harder to predict

Vertex events In contrast to site events vertex events are generated dynamically as the algorithm

runs As with the line segment plane sweep algorithm the imp ortant idea is that each such

event is generated by ob jects that are neighbors on the b each line However unlike the seg

mentintersection where pairs of consecutivesegments generated events here triples of p oints

generate the events

In particular consider any three consecutive p oints p p andp whose arcs app ear consec

i j k

utively on the b each line from left to right See the gure b elow Further supp ose that the

circumcircle for these three sites lies at least partially b elow the currentsweep line meaning

that the Voronoi vertex has not yet b een generated and that this circumcircle con tains no

p oints lying b elowthesweep line meaning that no future p oint will blo ck the creation of the

vertex

Consider the momentatwhichthesweep line falls to a p oint where it is tangenttothelowest

p oint of this circle At this instant the circumcenter of the circle is equidistant from all three

sites and from the sweep line Thus all three parab olic arcs pass through this center p oint

implying that the contribution of the arc from p has disapp eared from the b each line In

j

terms of the Voronoi diagram the bisectors p p andp p have met each other at the

i j j k

Voronoi vertex and a single bisector p p remains

i k

pj pj pj

pi pi

pk pkpi pk

Figure Vertex events

Sweepline algorithm We can now present the algorithm is greater detail The main structures

that we will maintain are the following

Lecture Notes CMSC M

Partial Voronoi diagram The partial Voronoi diagram that has b een constructed so far

will b e stored in a DCEL There is one technical diculty caused by the fact that the

diagram contains unb ounded edges To handle this we will assume that the entire diagram

is to b e stored within a large b ounding b ox This b ox should b e chosen large enough

that all of the Voronoi vertices t within the b ox

Beach line The b each line is represented using a dictionary eg a balanced binary tree or

skip list An imp ortant fact of the construction is that we do not explicitly store the

parabolic arcs They are just their for the purp oses of deriving the algorithm Instead

for each parab olic arc on the current b each line we store the site that gives rise to this

arc Notice that a site mayappearmultiple times on the b each line in fact linearly many

times in n But the total length of the b each line will never exceed n

Between each consecutive pairofsites p and p there is a breakp oint Although the

i j

breakp ointmoves as a function of the sweep line observe that it is p ossible to compute

the exact lo cation of the breakp oint as a function of p p and the current y co ordinate of

i j

the sweep line Thus as with b each lines we do not explicitly storebreakpoints Rather

we compute them only when we need them

The imp ortant op erations that wewillhave to supp ort on the b each line are

Given a xed lo cation of the sweep line determine the arc of the b each line that in

tersects a given vertical line This can b e done by a binary search on the breakp oints

which are computed on the y Think ab out this

Compute predecessors and successors on the b each line

Insert an new arc p within a given arc p thus splitting the arc for p into two This

i j j

creates three arcs p p and p

j i j

Delete an arc from the b eachline

It is not dicult to mo dify a standard dictionary data structure to p erform these op era

tions in O log n time each

Event queue The event queue is a priority queue with the ability b oth to insert and delete

new events Also the event with the largest y co ordinate can b e extracted For each site

we store its y co ordinate in the queue

For each consecutive triple p p p on the b each line we compute the circumcircle of

i j k

these p oints Well leave the messy algebraic details as an exercise but this can b e done

t of the circle the minimum y co ordinate on the in O time If the lower endp oin

circle lies b elowthesweep line then we create a vertex event whose y co ordinate is the

y co ordinate of the b ottom endp oint of the circumcircle We store this in the priority

queue Eachsuchevent in the priority queue has a cross link back to the triple of sites

that generated it and each consecutive triple of sites has a cross link to the event that it

generated in the priority queue

The algorithm pro ceeds likeany plane sweep algorithm We extract an event pro cess it and

go on to the next event Eacheventmay result in a mo dication of the Voronoi diagram and

the b each line and may result in the creation or deletion of existing events

Here is howthetwotyp es of events are handled

Site event Let p b e the current site Weshootavertical ray up to determine the arc that

i

lies immediately ab ove this p ointinthebeach line Let p b e the corresp onding site

j

We split this arc replacing it with the triple of arcs p p p whichwe insert into the

j i j

beach line Also we create new dangling edge for the Voronoi diagram which lies on the

bisector b etween p and p Any old triple that involved p as its center arc is deleted

i j j

from the priority queue and we generate new events for each of the p ossible three new

triples that result from this insertion

Lecture Notes CMSC M

Vertex event Let p p andp b e the three sites that generate this event from left to

i j k

right We delete the arc for for p from the b each line We create a new vertex in the

j

Voronoi diagram and tie the edges for the bisectors p p p p to it and start a new

i j j k

edge for the bisector p p that starts growing down b elow Finallywe delete anyevents

i k

that arose from triples involving this arc of p and generate new events corresp onding to

j

consecutive triples involving p and p there are two of them

i k

The analysis follows a typical analysis for plane sweep Eacheventinvolves O pro cessing

time plus a constantnumb er accesses to the various data structures Each of these accesses

takes O log n time and the data structures are all of size O n Thus the total time is

O n log n and the total space is O n

Lecture DelaunayTriangulations

ThursdayNov

Sp ecial Announcement Next TuesdayNov class will meet in AVW to attend Prof

Deorianis lecture on multiresolution surface representations You will b e resp onsible for material

presented in Deorianis talk

Reading BKOS Chapt

The DelaunayTriangulation Last time wegave an algorithm for computing Voronoi diagrams

Todaywe consider the related structure called a Delaunay triangulation Recall that a trian

gulation of a p oint set P is a straight line planar sub division whose vertices are the p oints of

P and which is maximal in the sense that no edge may b e added without violating planarity

This implies that very internal face of this sub division is a triangle and the external face is

b ounded by the b oundary of the convex hull of the p oint set

There are many p ossible triangulations of a given p oint set but one stands out as having the

nicest geometric prop erties This is the Delaunay triangulation The Delaunay triangulation

can b e dened in a number of equivalentways The denition that we use is that it is the

straightline dual of the Voronoi diagram of the sites In particular the vertices are the sites

t in the triangulation if and only if their Voronoi cells themselves and two sites are adjacen

share a common edge

Figure DelaunayTriangulation

If the sites are not in general p osition in the sense that four or more are co circular then the

Delaunay triangulation may not b e a triangulation at all but just a planar graph since the

Voronoi vertex that is incidenttofourormoreVoronoi cells will induce a face whose degree is

equal to the number of such cells In this case the more appropriate term would b e Delaunay

graphHowever it is common to either assume the sites are in general p osition or to enforce

it through some sort of symb olic p erturbation or else to simply triangulate the faces of degree

Lecture Notes CMSC M

four or more in any arbitrary way Henceforth we will assume that sites are in general p osition

so we do not have to deal with these messy situations

Given a p ointset P with n sites where there are h sites on the convex hull it is not hard to

prove that the Delaunay triangulation has n h triangles as wesaw on the exam and

n h edges by a similar pro of Recall that in all planar graphs the average degree of a

vertex is a constant at most

Also it is not hard to prove that the graph is planar Weknow that the graph is top ologically

planar since it is the dual of a planar graph but this only implies that there is some wayto

draw the edges so they do not cross It would still need to b e proven that if the edges are

drawn as straight line segments then they still do not cross See the text for details

An equivalent condition that we mentioned earlier is that every triangle in the Delaunay

triangulation has the prop erty called the empty circle property that the circumcircle of the

three vertices of the triangle do es not contain any other site of P in its interior

Maximizing Angles and Edge Flipping One of the interesting prop erties of Delaunay triangu

lations is that among all triangulations the Delaunay triangulation maximizes the minimum

angle In fact a much stronger statement holds as well Among all triangulations with the

same smallest angle the Delaunay triangulation maximizes the second smallest angle and so

on In particular any triangulation can b e asso ciated with a sorted angle sequencethatisthe

increasing sequence of angles app earing in the triangles of the triangulation

m

Note that the length of the sequence will b e the same for all triangulations of the same p oint

set since the numb er dep ends only on n and h

Theorem Among all triangulations of a given p oint set the Delaunay triangulation has the

lexicographically maximum angle sequence

Before getting into the pro of we should recall a few basic facts ab out angles from basic

geometry First recall that if we consider the circumcircle of three p oints then each angle of

the resulting triangle is exactly half the angle of the minor arc subtended by the opp osite two

p oints along the circumcircle It follows as well that if a p oint is inside this circle then it will

subtend a larger angle and a p oint that is outside will subtend a smaller angle This in the

gure part a b elow wehave

θ θ 3 d d 2 ϕ a θ a ab cd ϕbc θ1 θbc ϕda

θda ϕcd θab b c b c

(a) (b) (c)

Figure Angles and edge ips

We will not give a formal pro of of the theorem One app ears in the text The main idea

is to showthatforany triangulation that fails to satisfy the empty circle prop ertyitis

p ossible to p erform a lo cal op eration called an edge ipwhich increases the lexicographical

sequence of angles An edge ip is an imp ortant fundamental op eration on triangulations

Lecture Notes CMSC M

in the plane Given two adjacent triangles abc and cdasuch that their union forms a

convex quadrilateral abcd the edge ip op eration replaces the diagonal ac with bdNote

that it is only p ossible when the quadrilateral is convex Supp ose that the initial triangle

pair violates the empty circle condition in that p oint d lies inside the circumcircle of abc

implying equivalently that b lies inside the circumcircle of cda then if we ip the edge

it will follows that the two circumcircles of the two resulting triangles abd and bcd are

nowempty relative to these four p oints and the observation ab ove ab out circles and angles

proves that the minimum angle increases at the same time In particular in the gure ab ove

wehave

ab ab bc bc cd cd da da

There are two other angles that need to b e compared as well can you sp ot them but even

though their values might decrease it can b e seen that neither of them is the minimum angle

ou see why after the swap can y

Since there are only a nite numb er of triangulations this pro cess must eventually terminate

with the lexicographically maximum triangulation and this triangulation must satisfy the

empty circle condition and hence is the Delaunay triangulation

Randomized Algorithm This observation provides a basis for a simple but p otentially very slow

algorithm Simply build any initial triangulation eg the plane sweep triangulation presented

in the exam and then start p erforming edge ips until every pair of triangles satises the empty

circle prop ertyHowever there are no go o d b ounds on the numb er of edge ips required or

what a go o d strategy would b e for selecting them Instead we will present a simple randomized

O n log n exp ected time algorithm for constructing Delaunay triangulations for n sites in the

plane The algorithm is remarkably similar in spirit to the trap ezoidal map algorithm in

that builds its own p ointlo cation data structure as a side eect We will not discuss the

p ointlo cation data structure in detail but the details are easy to ll in

As with any randomized incremental algorithm the idea is to insert sites in random order

one at a time and up date the triangulation with each new addition The issues involved with

the analysis will b e showing that the numb er of structural changes in the diagram is not very

large it will b e O in the exp ected case for each insertion As with other incremental

algorithm we need some wayofkeeping track of where newly inserted sites are to b e placed

in the diagram Unlike the trap ezoidal map algorithm we will not create a data structure

but will instead use a simpler metho d that puts each of the uninserted p oints into buckets

according to the triangle that it overlaps in the current triangulation In this case we will

need to argue that the n umb er of times that a site is rebucketed on average is not to o large

it will b e O log n in the exp ected case

Incremental up date The basic issue in the design of the algorithm is how to up date the trian

gulation when a new site is added In order to do this we rst investigate the basic prop erties

of a Delaunay triangulation Recall that a triangle abc is in the Delaunay triangulation if

and only if the circumcircle of this triangle contains no other site in its interior Recall that

we make the general p osition assumption that no four sites are co circular Howtowe test

whether a site d lies within the interior of the circumcircle of abc It turns out that this can

b e reduced to a determinant computation It can b e shown that a site d lies in the circumcircle

determined by the counterclo ckwise triangle abc if and only if the following determinantis

p ositive This is called the incircle testWe will assume that this primitiveisavailable to us

a a a a

x y

x y

C B

b b b b

x y

x y

C B

ina b c d det

A

c c c c

x y

x y

d d d d

x y

x y

Lecture Notes CMSC M

When we add the next site p the problem is to convert the current Delaunay triangulation

i

into a new Delaunay triangulation This will b e done by creating an illegal nonDelaunay

triangulation containing the new p oint and then incrementally xing this triangulation to

restore the Delaunay prop erties The fundamental changes will b e adding a site to the

middle of a triangle and creating three new edges and p erforming an edge ip Both of

these op erations can b e p erformed in O time assuming that the triangulation is maintained

say as a DCEL

Figure Basic triangulation changes

Here is how the algorithm works We start with an initial triangulation Guibas Knuth and

Sharir suggest starting with the triangle of three sites at innity Not just any enclosing

triangle will work since we need to b e sure that the newly added vertices will not aect the

structure of the circumcircles and hence the interior structure of the triangulation This

guarantees that all sites to b e added will lie within some triangle of the existing triangulation

The sites are added in random order When a new site p is added we nd the triangle abc

of the current triangulation that contains this site insert the site in this triangle and join

this site to the three surrounding vertices This creates three new triangles pab pbc and

pcaeach of whichmayormay not satisfy the emptycircle condition Howdowe test this

For each of the triangles that have b een added wecheck the vertex of the triangle that lies

on the other side of the edge that do es not include pIfthisvertex fails the incircle test then

weswap the edge creating two new triangles that are adjacenttop and rep eat the same test

with these triangles An example is shown b elow

b b b

d d p p p

ca c a c a

Triangle pab is illegal. Triangles pdb and pbc are illegal. Final triangulation.

Figure Point insertion

The following is a description of the algorithm Guibas Knuth and Sharir give a nonrecursive

version The current triangulation is kept in a global data structure The edges in the

following algorithm are actually p ointers to the quadedge data structure

Insertp f

Find the triangle abc containing p

Insert edges pa pb and pc into triangulation

SwapTestab

Lecture Notes CMSC M

SwapTestbc

SwapTestca

g

SwapTestab f

if ab is an edge on the exterior face return

Let d be the vertex to the right of edge ab

if inp a b d f

Replace edge ab with pd

SwaptTestad

SwaptTestdb

g

g

As you can see the algorithm is very simple The only things that have to b e implemented

are the DCEL or other data structure to store the triangulation the incircle test and

lo cating the triangle that contains pTasks and are straightforward

Task can b e accomplished by one of two means Our text discusses the idea of building a

p ointlo cation data structure for dealing with this The other somewhat simpler approachis

based on a simple bucketing idea whichinvolves the same total amountofwork but it a bit

easier to implement Think of each triangle of the current triangulation as a bucket that holds

the future sites that lie within this triangle and are yet to b e inserted Whenever an edge

is ipp ed or when a triangle is split into three triangles through p oint insertion then some

triangles are destroyed and are replaced by a constantnumb er of new triangles When this

happ ens all the sites in the buckets asso ciated with the old triangles are rebucketed according

to the new triangles that they lie in

There is only one ma jor issue in establishing the correctness of the algorithm When we

p erformed emptycircle tests we only tested triangles containing the site p and only

sites that lay on the opp osite side of an edge of such a triangle To establish observe that

it suces to consider only triangles containing p b ecause since p is the only newly added site

it is the only site that can cause a violation of the emptycircle prop erty

To establish we argue that if for every site dwhich is opp osite from p along some edge ab

lies outside the circumcircle of pab then all these circumcircles are empty A complete pro of

takes some eort but here is a simple justication What could go wrong It might b e that d

lies outside the circumcircle but there is some other site eg a vertex e of a triangle adjacent

to d that lies inside the circumcircle This is illustrated in the following gure We claim that

this cannot happ en It can b e shown that if e lies within the circumcircle of pabthen a

must lie within the circumcircle of bde The argument is a exercise in high scho ol geometry

However this violates the assumption that the initial triangulation b efore the insertion of p

was a Delaunay triangulation

Analysis To analyze the algorithm we need to b ound two things howmanychanges are made

in the triangulation on average with the addition of each new site and howmuch eort is

sp ent in rebuck eting sites

We argue that the exp ected numb er of edge changes with each insertion is O by a simple

application of backwards analysis Observe that whenever the triangulation p erforms an edge

swapitalways adds a new edge to p Therefore the total number of changes made in the

triangulation for the insertion of p is equal to the degree of p after the insertion is completed

By backwards analysis weknow that each of the sites that are currently in the triangulation

are equally likely to b e deleted With the exception of the three initial sites at innity but

they only slightly bias this argument so we ignore them

Lecture Notes CMSC M

d e b a

p

Figure Pro of of suciency of testing neighb oring sites

By the argument just given weknow that the total number of edge changes needed if p were

the last site added is just the degree of p in the resulting triangulation However we also know

that the average degree of a vertex in a planar graph is constant Therefore the exp ected

numberofchanges to the structure is O p er insertion

Next we argue that the exp ected numb er of times that a site is rebucketed as to which

triangle it lies in is O log n Again this is a standard application of backwards analysis

Consider the ith stage of the algorithm after i sites have b een inserted into the triangulation

Among the remaining n i sites we claim that the probability that this site changes triangles

is at most i Observe that when we insert a new site p all of the newly created triangles

include the site p Each triangle in the current triangulation is determined by exactly sites If

none of these was the last site to b e inserted then no uninserted site in this triangle needs

to b e rebucketed Thus for each of the remaining n i sites the probability that this site

needs to b e rebucketed is at most i The probability is indep endent of the site distribution

and dep ends only on the sequence with which the sites are inserted Thus the total exp ected

numb er of rebuc ketings is given by the sum

n n n

X X X

n i n n n ln n

i i i

i i i

Lecture DeFlorianis Lecture

TuesdayNov

Sp ecial Announcement Todays class will meet in AVW to attend Prof Deorianis

lecture on multiresolution surface representations You will b e resp onsible for material presented in

Deorianis talk

Lecture Line Arrangements

ThursdayNov

Reading BKOS Chapt

Arrangements So far wehave studied a few of the most imp ortant in my opinion geometric

structures convex hulls and Voronoi diagrams and Delaunay triangulations The next most

imp ortant structure again in my opinion in computational geometry is that of a line ar

rangementAswithhulls and Voronoi diagrams it is p ossible to dene arrangements in any

dimension but we will concentrate on the plane As with Voronoi diagrams a line arrangement

is a p olygonal sub division of the plane Unlike most of the structures wehaveseenuptonow

a line arrangement is not dened in terms of a set of p oints but rather in terms of a set L of

Lecture Notes CMSC M

lines However line arrangements are used mostly for solving problems on p oint sets The con

nection is that the arrangements are typically constructed in the dual plane We will b egin by

dening arrangements discussing their combinatorial prop erties and how to construct them

and nally discuss applications of arrangements to other problems in computational geometry

Before discussing algorithms for computing arrangements and applications werstprovide

denitions and some imp ortant theorems that will b e used in the construction A nite set L

of lines in the plane sub divides the plane The resulting sub division is called an arrangement

denoted AL Arrangements can b e dened for curves as well as lines and can also b e dened

for d dimensional hyp erplanes in dimension dButwe will only consider the case of lines

in the plane here

In the plane the arrangement denes a planar graph whose vertices are the p oints where two

or more lines intersect edges are the intersection free segments or rays of the lines and faces

are p ossibly unb ounded convex regions containing no line An example is shown b elow vertex

face

edge

bounding box

Figure Arrangementoflines

An arrangementissaidtobe simple if no three lines intersect at a common p oint We will

make the usual general p osition assumptions that no three lines intersect in a single p oint

This assumption is easy to overcome by some sort of symb olic p erturbation

An arrangement is not formally a planar graph b ecause it has unb ounded edges We can

x this top ologically by imagining that a vertex is added at innity and all the unb ounded

edges are attached to this vertex A somewhat more geometric way to x this is to imagine

that there is a b ounding b ox which is large enough to contain all the vertices and we tie all

the unb ounded edges o at this b ox Rather than computing the co ordinates of this huge

box which is p ossible in O n time it is p ossible to treat the sides of the b ox as existing

at innity and handle all comparisons symb olicallyFor example the lines that intersect the

right side of the b ox at innity have slop es b etween and and the order in which they

intersect this side from top to b ottom is in decreasing order of slop e If you dont see this

rightaway think ab out it

The combinatorial complexity of an arrangement is the total number of vertices edges and

faces in the arrangement The following shows that all of these quantities are O n

Theorem Give a set of n lines L in the plane in general p osition

n

i the number of vertices in ALis

ii the number of edges in ALisn and

n

n iii the numb er of faces in ALis

n

is clear from the fact that each pair of lines Pro of The fact that the number of vertices is

we use induction intersects in a single p oint Toprovethatthenumb er of edges is n

The basis case is trivial line and edge When we add a new line to an arrangement

of n lines having n edges by the induction hyp othesis we split n existing

edges thus creating n new edges and weaddn new edges from the n intersections

Lecture Notes CMSC M

with the new line This gives a total of n n n n Thenumb er of faces

comes from Eulers formula v e f with the little trickthatwe need to create

one extra vertex to attach all the unb ounded edges to

Incremental Construction Arrangements are used for solving many problems in computational

geometry But in order to use arrangements we rst must b e able to construct arrangements

We will present a simple incremental algorithm which builds an arrangementby adding lines

one at a time Unlike most of the other incremental algorithms wehave seen so far this one

will not require randomization In fact its asymptotic running time will b e the same O n

no matter what order we insert the lines This is asymptotically optimal since there this is

the size of the arrangement The algorithm will also require O n since this is the amount

of storage needed to store the nal result Later we will consider the question of whether it

is p ossible to traverse an arrangement without actually building it

As usual we will assume that the arrangement is represented in any reasonable data structure

for planar graphs a DCEL for example Let L f g denote the lines We will

n

simply add lines one by one to the arrangement The order do es not matter We will show

that the ith line can b e inserted in O i time If wesumover i this will give O n total

time

Supp ose that the rst i lines have already b een added and consider the eort involved

in adding Recall our assumption that the arrangement is assumed to lie within a large

i

bounding box Since each line intersects this b oxtwice the rst i lines have sub divided

the b oundary of the b oxinto i edges We determine where intersects the b ox and

i

which of these edge it crosses intersects This will tell us which face of the arrangement rst

i

enters

Next we trace the line through the arrangement from one face to the next Whenever weenter

a face the main question is where do es the line exit the face Weanswer the question bya

very simple strategyWewalk along the edges face say in a counterclo ckwise direction recall

that a DCEL allows us to do this and as we visit each edge we ask whether intersects this

i

edge When we nd the edge through which exits the face we jump to the face on the other

i

side of this edge again the DCEL supp orts this and continue the trace This is illustrated in

the gure b elow

l l

traversing the arrangement the zone

Figure Traversing an arrangement and zones

Once weknowthepoints of entry and exit into each face the last matter is to up date the

DCEL by inserting edges for eachentryexit pair This is easy to handle in constant time by

adjusting the appropriate p ointers in the DCEL Details are left as an exercise

Clearly the time that it takes to p erform the insertion is prop ortional to the total number

of edges that havebeentraversed in this tracing pro cess Anaive argumentsays that we

encounter i lines and hence pass through i faces assuming general p osition Since each

Lecture Notes CMSC M

face is b ounded byatmosti lines each facial traversal will take O i time and this gives a

total O i Heywhatwent wrong Ab ovewe said that wewould do this in O i time The

claim is that the traversal do es indeed traverse only O i edges but to understand whywe

need to delve more deeply into a concept of a zone of an arrangement

Zone Theorem The most imp ortant combinatorial prop erty of arrangements which is critical to

their ecient construction is a rather surprising result called the zone theorem Given an

arrangement A of a set L of n lines and given a line that is not in Lthe zone of in A

denoted Z is the set of faces whose closure intersects The gure ab ove illustrates a

A

ve construction we are only interested in the zone for the line For the purp oses of the ab o

edges of the zone that lie b elow but if we b ound the total complexity of the zone then this

i

will b e an upp er b ound on the numb er of edges traversed in the ab ove algorithm

The combinatorial complexity of a zone as argued ab ove is O n The Zone theorem states

that the complexity is actually much smaller only O n

Theorem The Zone Theorem Given an arrangement ALofn lines in the plane and given

any line in the plane the total numb er of edges in all the cells of the zone Z isat

A

most n

Pro of As with most combinatorial pro ofs the key is to organize everything so that the

counting can b e done in an easy way Note that this is not trivial b ecause it is easy to

see that any one line of L mightcontribute manysegments to the zone of The key in

the pro of is nding a way to add up the edges so that each line app ears to induce only a

constantnumberofedgesinto the zone

The pro of is based on a simple inductive argument We will rst imagine through a

suitable rotation that is horizontal and further that none of the lines of L is horizon tal

through an innitesimal rotation We split the edges of the zone into two groups those

that b ound some face from the left side and those that b ound some face from the right

side More formally since each face is convex if we split it at its topmost and b ottommost

vertices we get twoconvex chains of edges The leftbounding edges are on the left chain

and the rightbounding edges are on the rightchain We will show that there are at most

n lines that b ounded faces from the left Note that an edge of the zone that crosses

itself contributes only once to the complexity of the zone In the b o oks pro of they seem

to count this edge twice and hence their b ound they get a b ound of n instead We will

also ignore the edges of the b ounding b ox

For the basis case when n then there is exactly one left b ounding edge in s zone

and n Assume that the hyp othesis is true for anysetofn lines Consider the

rightmost line of the arrangementtointersect Call this Selecting this particular

line is very imp ortant for the pro of Supp ose that we consider the arrangementofthe

other n lines By the induction hyp othesis there will b e at most n leftb ounding

edges in the zone for

Now let us add back and see howmany more leftb ounding edges result Consider the

n

rightmost face of the arrangementofn lines Note that all of its edges are leftb ounding

edges Line will intersect within this face Let e and e denote the two edges of

a b

this that intersects one ab ove and the other b elow The insertion of creates a

new left b ounding edge along itself and splits the left b ounding edges e and e into

a b

two new left b ounding edges for a net increase of three edges Observethat cannot

contribute any other leftb ounding edges to the zone b ecause dep ending on slop e either

the line supp orting e or the line supp orting e blo cks s visibilityfromfromNote

a b

that it might provide rightb ounding edges but we are not counting them here Thus

the total numb er of leftb ounding edges on the zone is at most n n and

hence the total numb er of edges is at most n as desired

Lecture Notes CMSC M

ea

l1

l

eb

Figure Pro of of the Zone Theorem

Lecture Applications of Arrangements

TuesdayNov

Reading This material is not covered in the text

Revised Nov Added material ab out angular sorting

Sweeping Arrangements Last time weshowed how to construct an arrangement of lines in the

plane in O n time Since an arrangement is of size O n this is optimal Usually it is not

sucient just to build the arrangement but necessary to traverse the arrangementaswell In

some instances any graph traversal will suce For other problems it is nice to p erform the

traversal in some order for example as a plane sweep from left to right

If an arrangement is to b e built just so it can b e swept then mayb e you didnt need to construct

the entire arrangement after all You can just p erform the plane sweep on the lines exactly as

we did for the line segmentintersection algorithm Assuming that we are sweeping from left to

right the initial p osition of the sweep line is at x computed symb olically The sweep

line status maintains the lines in top to b ottom order according to their intersection with the

sweep line The initial order is according to increasing order of slop e Then the sweep line

pro ceeds exactly as it did in the algorithm for determining line segmentintersections but the

only events are intersection events since there are no endp oints The sweep ends when the

last intersection event is pro cessed Sweeping an arrangement in this w aytakes O n log n

time but only O n space since we need only maintain the currentsweep line For many

applications involving arrangements this oers a reasonable tradeo b etween time and space

But is the O log n factor necessary In many applications involving plane sweep it is not

necessary to sweep in strictly lefttoright order as long as the vertices lying on each line of

the arrangement are swept from lefttoright In this case wecansavetheO log n factor by

constructing the arrangement then thinking of the edges as b eing directed from left to right

p erform a topological sort of the vertices A top ological sort of an acyclic directed graph is

an ordering of the vertices of a directed graph such that for eachedgeu v in the graph u

app ears b efore v in the order It is well known that the vertices of a graph can b e top ologically

sorted in time that is prop ortional to the size of the graph or O n in this case See CLR

for details Given the top ological ordering of the vertices of the arrangement wecansweep

the arrangementby simply extracting the vertices in this order This gives an O n time and

space algorithm for sweeping arrangements O n

Is it p ossible to sweep arrangements in O n time but with only O n space It turns out

that the answer is yes There is an algorithm called topological plane sweep which incorp orates

Lecture Notes CMSC M

5 9 1 4 6

7 12 2 14 13 16 15 11 8

3 10

Figure One p ossible top ological ordering of the vertices of an arrangement

the top ological nature of the ab ovesweeping algorithm with the incremental nature of plane

sweep

Applications of Arrangements and Duality The computational and mathematical to ols that

wehavedevelop ed with geometric duality and arrangements allow a large numb er of problems

to b e solved Here are some examples Unless otherwise stated all these problems can b e

solved in O n time and O n spaceby constructing a line arrangement or in O n time

and O n space through top ological plane sweep

General p osition test Given a set of n points in the plane determine whether any three

are collinear

Minimum area triangle Given a set of n points in the plane determine the minimum area

triangle whose vertices are selected from these p oints

Minimum k corridor Given a set of n p oints and an integer k determine the narrowest

pair of parallel lines that enclose at least k points of the set The distance b etween the

lines can b e dened either as the vertical distance b etween the lines or the p erp endicular

distance b etween the lines

Visibility graph Given line segments in the plane wesay that twopoints are visible if the

interior of the line segment joining them intersects none of the segments Given a set

of n nonintersecting line segments compute the visibility graph whose vertices are the

endp oints of the segments and whose edges a pairs of visible endp oints

Maximum stabbing line Given a set of n line segments in the plane determine whether

the line that stabs intersects the maximum numb er of these line segments

Hidden surface removal Given a set of n nonintersecting p olygons in space imagine

pro jecting these p olygon onto a plane either orthogonally or using p ersp ective Deter

mine which p ortions of the p olygons are visible from the viewp oint under this pro jection

Note that in the worst case the complexity of the nal visible scene may b e as high as

O n so this is asymptotically optimal However since such complex scenes rarely o ccur

in practice this algorithm is really only of theoretical interest

Ham SandwichCut Given n red p oints and m blue p oints nd a single line that simul

taneously bisects these p oint sets It is a famous fact from mathematics called the

HamSandwich Theoremthatsuch a line always exists If the p oint sets are separated

O n m by a line then this can b e done in time O n m space

Sorting all angular sequences Here is a natural application of duality and arrangements that

turns out to b e imp ortant for the problem of computing visibility graphs Consider a set of n

Lecture Notes CMSC M

p oints in the plane For eachpoint p in this set wewant to p erform an angular sweep sayin

counterclo ckwise order visiting the other n points of the set For each p oint it is p ossible

to compute the angles b etween this p oint and the remaining n points and then sort these

angles This would take O n log n time p er p oint and O n log ntimeoverall

With arrangements we can sp eed this up to O n total time getting rid of the extra O log n

factor Here is how Recall the duality transformation describ ed in Lecture Apoint

p p p and line y ax b in the primal plane are mapp ed through duality to dual

x y

p oint and dual line p by the following relationship

a b

p b p a p

x y

Observe that the aco ordinate in the dual plane corresp onds to the slop e of a line in the primal

plane Supp ose that p is the p oint that wewant to sort around and let p p p b e the

n

p oints in nal angular order ab out p

p p 4 7 p p p 5 6 8 p p p 5 2 p 3 6 p p 2 p 3

p p 4 7 p p 1 p

8 p 1

Figure Arrangements and angular sequences

Consider the arrangement dened by the dual lines p How is this order revealed in the

i

arrangement Consider the dual line p and its intersection p oints with each of the dual lines

p These form a sequence of vertices in the arrangementalongp Consider this sequence

i

ordered from left to right It would b e nice if this order were the desired circular order but

this is not quite correct The aco ordinate of each of these vertices in the dual arrangementis

the slop e of some line of the form pp Thus the sequence in whichthevertices app ear on the

i

line is a slopeordering of the p oints ab out p not an angular ordering

i

However given this slop e ordering we can simply test which primal p oints lie to the left of p

that is have a smaller xco ordinate in the primal plane and separate them from the p oints

that lie to the rightofp having a larger xco ordinate We partition the vertices into two

sorted sequences and then an concatenate these two sequences with the p oints on the right

side rst and the p oints on the left side later The resulting is an angular sequence starting

with the angle degrees and pro ceeding up to degrees

Thus once the arrangement has b een constructed we can reconstruct each of the angular

orderings in O n time for a total of O n time

Lecture More Applications of Arrangements

ThursdayNov

Reading The material on discrepancies is in Chapt of BKOS The other material is not covered

in the text

Lecture Notes CMSC M

Applications of Arrangements Todaywe will discuss a few of applications of line arrangements

in the plane This is to give a feel for how one converts problems into dual form and then uses

arrangements to solve these problems Recall the duality op erator from Lecture We dened

a function that maps p oints in the primal plane to lines in the dual plane and lines in the

primal plane to p oints in the dual plane We denoted it using a asterisk as a sup erscript

Thus given p oint p p p and line y ax b in the primal plane wedene and

x y

p to b e a p oint and line resp ectively in the dual plane dened by

a b

p b p a p

x y

The main prop erty of this transformation was the following order reversing prop erty a p oint

p lies ab oveonb elow line in the primal plane if and only if line p passes b elowonab ove

p oint in the dual plane resp ectively

Narrowest corridor As mentioned ab ove in this problem we are given a set P of n p oints

in the plane and an integer k k n and we wish to determine the narrowest pair of

parallel lines that enclose at least k p oints of the set In this case we will dene the vertical

distance b etween the lines as the distance to minimize It is easy but a bit tricky to adapt

the algorithm for p erp endicular distance

To simplify the presentation we assume that k The generalization to general k is an

exercise We will assume that no three p oints of P are collinear This will allow us to assume

that the narrowest corridor contains exactly three p oints and has width strictly greater than

zero Observe that if three p oints were collinear then they would corresp ond to three lines

that intersect at a common vertex in the arrangement which could b e tested as we build the

arrangement We will also assume that no two p oints have the same xco ordinate The dual

transformation that we consider cannot representvertical lines but this assumption will imply

that the solution is not a vertical line We could x this by using homogeneous co ordinates

but we will not worry ab out it now

If we dualize the p oints of P then in dual space wehave a set L of n lines f g The

n

slop e of each dualline is the xco ordinate of the corresp onding p ointofP and its y intercept

is the negation of the p oints y co ordinate

Anarrowest corridor in the primal plane consists of two parallel lines and in primal

a b

space Their duals and are dual p oints whichhave the same xco ordinates since the

a

b

lines are parallel and the vertical distance b etween these p oints is the dierence in the y

intercepts of the two primal lines Thus the vertical width of the corridor is the vertical length

of the line segment

In the primal plane there are exactly three p oints lying in the corridor that is there are three

p oints that are b oth ab ove and b elow Thus by the order reversing prop erty in the dual

b a

Combining all plane there are three dual lines that pass b oth b elowpoint and ab ove

a

b

these observations it follows that the dual formulation of the narrowest corridor problem is

the following

Shortest vertical stabb er Given an arrangementofn lines determine the shortest ver

tical segment that stabs three lines of the arrangement

It is easy to showby a simple p erturbation argument that the shortest vertical stabb er

may b e assumed to have one of its endp oints on a vertex of the arrangement implying that the

other endp oint lies on the line of the arrangement lying immediately ab oveorbelowthisvertex

In the primal plane the signicance is that we can assume that the minimum corridor one

Lecture Notes CMSC M

l p* a * lb r q* p lb d q d r* la*

Primal Plane Dual Plane

Figure Narrowest corridor primal and dual form

of the lines passes through of the p oints and the other passes through a third p oint and

there are no p oints within the interior of the corridor This is shown in the gure b elow

We can compute the minimum stabb er in an arrangement by a simple plane sweep of the

arrangement using a vertical sweep line Whenever we encounter a vertex of the arrangement

we consider the distance to the edge of the arrangement lying immediately ab ove this vertex

and the edge lying immediately b elow We can solve this problem by top ological plane sweep

in O n timeandO n space

We can also solve this by constructing the arrangement and the computing the vertical

trap ezoidal map Each trap ezoidal edge will corresp ond to a corridor The shortest such edge

is the nal answer This leads to an O n time and space solution

Figure Narrowest corridor and trap ezoidal maps

Maximum Discrepancy Next we consider a problem derived from computer graphics and sam

pling Supp ose that we are given a collection of n points S lying in a unit square U

Wewant to use these p oints for random sampling purp oses In particular the prop erty that

wewould like these p oints to have is that for any halfplane hwewould like the size of the

fraction of p oints of P that lie within h should b e roughly equal to the area of intersection of

h with U That is if we dene h to b e the area of h U and hjS hjjS j then

S

wewould like h h for all h This prop erty is imp ortant when p oint sets are used for

S

things like sampling and MonteCarlo integration

To this end w e dene the discrepancy of S with resp ect to a halfplane h to b e

h jh hj

S S

For example in the gure the area of h U is h and there are out of p oints

in hthus h Thus the discrepancy of h is j j Dene

S

the halfplane discrepancy of S to b e the maximum or more prop erly the supremum or least

Lecture Notes CMSC M

h

Figure Discrepancy of a p oint set

upp er b ound of this quantityover all halfplanes

S sup h

S

h

Since there are an uncountably innite numb er of halfplanes it is imp ortant to derive some

sort of niteness criterion on the set of halfplanes that might pro duce the greatest discrepancy

Lemma Let h denote the halfplane that generates the maximum discrepancy with resp ect

to S and let denote the line that b ounds h Then either i passes through at least

two p oints of S or ii passes through one p ointofS and this p oint is the midp ointof

the line segment U

Remark If a line passes through one or more p oints of S then should this p oint b e included

in h For the purp oses of computing the maximum discrepancy the answer is to

S

either include or omit the p oint whichever will generate the larger discrepancy The

justication is that it is p ossible to p erturb h innitesimally so that it includes none or

all of these p oints without alterning h

Pro of If do es not pass through anypointofS then dep ending on which is larger h

or h wecanmove the line up or down without changing h and increasing or

S S

decreasing h to increase their dierence If passes through a p oint p S but is not

the midp oint of the line segment U thenwe can rotate this line ab out p and hence

increase or decrease h without altering h to increase their dierence

S

Since for eachpoint p S there are only a constantnumber of lines at most two I think

through this p ointsuch that p is the midp ointof U it follows that there are at most O n

lines of typ e i ab ove and hence the discrepancy of all of these lines can b e tested in O n

time

To compute the discrepancies of the other lines we can dualized the problem In the primal

p S is mapp ed in the dual plane to a plane a line that passes through two p oints p

i j

p oint at which the lines p and p intersect This is just a vertex in the arrangement of the

i j

dual lines for S So if wehave computed the arrangement then all we need to do is to visit

eachvertex and compute the discrepancy for the corresp onding primal line

It is easy to see that the area U of each corresp onding line in the primal plane can b e

computed in O time So all that is needed is to compute the number of points of S lying

beloweach such line In the dual plane the corresp onds to determining the numb er of dual

lines that lie b eloworabove eachvertex in the arrangement If weknowthenumb er of dual

lines that lie strictly ab oveeachvertex in the arrangement then it is trivial to compute the

numb er of lines that lie b elowby subtraction

We dene a p ointtobeat level k L in an arrangement if there are at most k lines ab ove

k

el of an arrangementisan this p oint and at most n k lines b elow this p oint The k th lev

xmonotone p olygonal curve as shown b elow For example the upp er envelop e of the lines is

Lecture Notes CMSC M

level of the arrangement and the lower envelop e is level n of the arrangement Note that a

vertex of the arrangement can b e on multiple levels Also note that our denition of level is exactly one greater than our texts denition

L1

L3

L5

Figure Levels in an arrangement

We claim that it is an easy matter to compute the level of eachvertex of the arrangement eg

by plane sweep The initial levels at x are determined by the slop e order of the lines

As the plane sweep pro ceeds the index of a line in the sweep line status is its level Thus by

using top ological plane sweep in O n time we can compute the minimum and maximum level

number of eachvertex in the arrangement From the order reversing prop erty for eachvertex

of the dual arrangement the minimum level number minus indicates the numb er of primal

p oints that lie strictly b elow the corresp onding primal line and the maximum level number is

the numb er of dual p oints that lie on or b elow this line Thus given the level numb ers and

the fact that areas can b e computed in O time we can compute the discrepancy in O n

time and O n space through top ological plane sweep

Lecture Shortest Paths and Visibility Graphs

TuesdayNov

Reading The material on visibility graphs is tak en roughly from Chapter but we will present

slightly more ecientvariant of the one that app ears in this chapter

Shortest paths We are given a set of n disjoint p olygonal obstacles in the plane and two p oints

s and t that lie outside of the obstacles The problem is to determine the shortest path from s

to t that avoids the interiors of the obstacles It maytravel along the edges or pass through

the vertices of the obstacles The complement of the interior of the obstacles is called free

spaceWewant to nd the the shortest path that is constrained to lie entirely in free space

Todaywe consider a simple but p erhaps not the most ecient waytosolve this problem We

assume that we measure lengths in terms of Euclidean distances Howdowe measure paths

lengths for curved paths Luckilywedonothave to b ecause we claim that the shortest path

will always b e a p olygonal curve

Claim The shortest path b etween anytwopoints that avoids a set of p olygonal obstacles is

a p olygonal curve whose vertices are either vertices of the obstacles or the p oints s and

t

Pro of Weshowthatanypath that violates these conditions can b e replaced b y a slightly

shorter path from s to t Since the obstacles are p olygonal if the path were not a p olygonal

curve then there must b e some p oint p in the interior of free space such that the path

passing through p is not lo cally a line segment If we consider any small neighborhood

Lecture Notes CMSC M

ab out p small enough to not contain s or t or anypartofany obstacle then since the

shortest path is not lo cally straight we can shorten it slightly by replacing this curved

segmentby a straight line segment jointing one end to the other Thus is not shortest

acontradiction

Thus is a p olygonal path Supp ose that it contained a vertex v that was not an obstacle

vertex Again we consider a small neighb or ho o d ab out v that contains no part of any

obstacle We can shorten the path as ab ove implying that is not a shortest path

From this it follows that the edges that constitute the shortest path must travel b etween s and

t and vertices of the obstacles Each of these edges must have the prop erty thatitdoesnot

intersect the interior of any obstacle implying that the endp oints must b e mutually visible

Denition The visibility graph of s and t and the obstacle set is a graph whose vertices are s

and t the obstacle vertices and vertices v and w are joined by an edge if the line segment

v w lies entirely in free space

s

t

Figure Visibility graph

It follows from the ab ove claim that the shortest path can b e computed by rst computing

the visibility graph and lab eling each edge with its Euclidean length and then computing the

shortest path bysay Dijkstras algorithm see CLR Note that the visibility graph is not

planar and hence may consist of n edges Also note that even if the input p oints have

integer co ordinates in order to compute distances we need to compute square ro ots and then

sums of square ro ots This can b e approximated by oating p oint computations If you are

a stickler for exactness this can really b e a problem b ecause there is no known p olynomial

time pro cedure for p erforming arithmetic with arbitrary square ro ots of integers

Computing the Visibility Graph Next we givean O n pro cedure for constructing the visi

bility graph of n line segments in the plane The more general task of computing the visibility

graph of an arbitrary set of p olygonal obstacles is a very easy generalization In this context

twovertices are visible if the line segment joining them do es not intersect any of the obstacle

line segments However we allow each line segmenttocontribute itself as an edge in the visi

bility graph We will make the general purp ose assumption that no three vertices are colinear

but this is not hard to handle with some care The algorithm is not output sensitive An

O n log n k algorithm do es exist but it quite complicated

The text gives an O n log n time algorithm W e will givean O n time algorithm Both

algorithms are based on the same concept namely that of p erforming an angular sweep around

eachvertex The texts algorithm op erates by doing this sweep one vertex at a time Our

algorithm do es the sweep for all vertices simultaneously Using the fact that angular sorting

can b e implemented through top ologically sweeping the a line arrangementin O n time we

manage to shaveotheextraO log n factor in running time

Here is a highlevel intuitive view of the algorithm First recall the algorithm for computing

trap ezoidal maps We sho ot a bullet up and down from every vertex until it hits its rst

line segment This implicitly gives us the vertical visibility relationships b etween vertices

Lecture Notes CMSC M

and segments Now we imagine that angle continuously sweeps out all slop es from

to Imagine that all the bullet lines attached to all the vertices b egin to turn slowly

counterclo ckwise If we play the mind exp eriment of visualizing the rotation of these bullet

paths the question is what are the signicantevent p oints and what happ ens with each

event As the sweep pro ceeds we will eventually determine everything that is visible from

every vertex in every direction Thus it should b e an easy matter to piece together the edges

of the visibility graph as we go

Figure Visibility graph bymultiple angular sweep

Let us consider this multiple angular sweep in greater detail Observe that a signicant

event o ccurs whenever a bullet path jumps from one line segment to another This o ccurs

when reaches the slop e of the line joining two visible vertices v and w Unfortunatelyitis

somewhat complicated to keep trackofwhichvertices are visible and which are not although

if we could do so it would lead to a more ecient algorithm Instead we will takeevents to

be al l angles between twovertices whether they are visible or not By duality the slop e of

suchanevent will corresp ond to the avalue of the intersection of lines v and w in the dual

arrangement Convince yourself of this b efore going on Thus bysweeping the arrangement

we will generate all these events

Next lets consider what happ ens at eacheventpoint Consider the state of the angular sweep

algorithm for some slop e For eachvertex v therearetwo bullet paths emanating from v

along the line with slop e Call one the forward bul let path and the other the backward bul let

pathLetf v andbv denote the line segments that these bullet paths hit resp ectivelyIf

either path do es not hit any segmentthenwe store a sp ecial null value As varies the following

events can o ccur Assuming through symb olic p erturbation that each slop e is determined by

exactly two lines whenever we arriveatanevents slop e there are exactly twovertices v and

w that are involved Here are the p ossible scenarios

Same segment If v and w are endp oints of the same segment then they are visible and we

add the edge v w to the visibility graph

Invisible Consider the distance from v to w First determine whether w lies on the same

side as f v orbv For the remainder assume that it is f v The case of bv is

symmetrical

Lecture Notes CMSC M

f(v) f(v) (new) w w (new) w w f(v)(old) v v v v f(v)(old) f(v)

Same segment Invisible Entry Exit

Figure Possible events

Compute the contact p oint of the bullet path shot from v in direction with segment

f v If this path hits f v strictly b efore w thenwe knowthat w is not visible to v and

so this is a nonevent

Segmententry Consider the segmentthatisincidenttow Either the sweep is just ab out

to enter this segment or is just leaving it If we are entering the segment then we set

f v to this segment

Segment exit If we are just leaving this segment then then the bullet path will need to

sho ot out and nd the next segmentthatithits Normally this would require some

searching In particular this is one of the reasons that the texts algorithm has the extra

O log n factorto p erform this search However we claim that the answer is available

to us in O time

In particular since we are sweeping over w at the same time that we are sweeping over

v Thus weknow that the bullet extension from w hits f w All we need to do is to set

f v f w

This is a pretty simple algorithm although there are a numb er of cases The only information

that we need to keep track of is a priority queue for the events and the f v andbv

p ointers for eachvertex v The priority queue is not stored explicitly Instead it is available

from the line arrangement of the duals of the line segmentvertices By p erforming a top ological

sweep of the arrangement we can pro cess all of these events in O n time

There is one subtlety ab out top ological sweep that we should b e careful ab out though Re

memb er that top ological sweep and regular plane sweep are not identical in that a top ological

sweep do es pro cess events in strictly left to right order However we are assured that along

any dual line the sweep will pro cess events from left to right along the line

Here is our fear In the Segment Exit event we accessed f w But since the sweeps along the

dual lines for v and w are pro ceeding indep endently in general mightitbethat f w is lagging

b ehind or has moved ahead of the sweep along v If so this could b e disastrous b ecause f w

would b e set for some other angle To see whythisisnotadangerwe need to lo ok at what

is happ ening in the arrangement At the momentofthisevent we are pro cessing a line that

passes through b oth v and w In the dual plane this line corresp onds to the intersection p oint

of lines v and w in the dual plane The top ological plane sweep sweeps eachvertex of the

arrangement exactly once implying that these events will b e pro cessed at the same time in

the top ological plane sweep and so there is no danger of one b eing ahead or lagging b ehind

the other

There are examples of algorithms where the natural events to b e pro cessed in top ological plane

sweep do not corresp ond to single vertices but rather to groups of events in dierent parts

of the arrangement that are supp osed to o ccur at the same time but might b e out of phase

Lecture Notes CMSC M

b ecause of the top ological nature of the sweep Do es this mean that top ological sweep cannot

b e used Sometimes yes and sometimes no Recall that the top ological sweep arises from a

top ological sort of a DAG the directed edges of the arrangement Sometimes it is p ossible

to add additional edges ie additional ordering constraints thus forcing the sweep to b ehave

itself

Lecture Motion Planning

Tuesday Dec

Reading Chapt in BKOS

Motion planning Last time we considered the problem of computing the shortest path of a p oint

in space around a set of obstacles Todaywe will study a very general approach to the more

general problem of how to plan the motion of one or more rob ots each with p otentially many

degrees of freedom in terms of its movement and p erhaps having articulated joints

Work Space and Conguration Space The environment in which the rob ot op erates is called

its work space which consists of a set of obstacles that the rob ot is not allowed to intersect We

assume that the work space is static that is the obstacles do not move We also assume that

a complete geometric description of the work space is available to us There are interesting

variants of motion planning in environments where the obstacles either unknown or are known

but move In unknown environments the rob ot must have some way of sensing its environment

either by sightortouch In environments with moving ob jects the rob ot m ust b e capable of

detecting the presense of moving ob jects early enough that it can avoid colliding with them

Henceforth let S denote the set of obstacles dening the environment

For our purp oses a robot will b e mo deled bytwo main elements The rst is a conguration

which is a nite sequence of values that fully sp ecies the p osition of the rob ot The second

element is the rob ots geometric shap e description Combined these two element fully dene

the rob ots exact p osition and shap e in space For example supp ose that the rob ot is a

dimensional p olygon that can translate and rotate in the plane Its conguration maybe

describ ed by the x y co ordinates of some reference p oint for the rob ot and an angle

that describ es its its orientation Its geometric information would include its shap e sayat

some canonical p osition given say as a simple p olygon Given its geometric description and

a conguration x y this uniquely determines the exact p osition Rx y of this rob ot

in the plane Thus the p osition of the rob ot can b e identied with a p oint in the rob ots

conguration space

R(4,3,45)

R(0,0,0)

Figure Congurations of a translating and rotating rob ot

A more complex example would b e an articulatedarmconsisting of a set of links connected

to one another by a set of revolute joints The conguration of sucharobotwould consist

ofavector of joint angles The geometric description would probably consist of a geometric

Lecture Notes CMSC M

representation of the links Given a sequence of joint angles the exact shap e of the rob ot

could b e derived bycombining this conguration information with its geometric description

For example a typical dimensional industrial rob ot has six joints and hence its conguration

can b e thoughtofasapoint in a dimensional space Why six Generally there are three

degrees of freedom needed to sp ecify a lo cation in space and more degrees of freedom

needed to sp ecify the direction and orientation of the rob ots end manipulator

Given a p oint p in the rob ots conguration space let Rp denote the placement of the rob ot

at this conguration The gure b elow illustrates this in the case of the planar rob ot dened

ab ove

Work space Configuration space

Figure Work space and conguration space

Because of limitations on the rob ots physical structure and the obstacles not every p ointin

conguration space corresp onds to a legal placement of the rob ot Any conguration whichis

illegal in that it causes the rob ot to intersect one of the obstacles is called a forbidden congu

ration The set of all forbidden congurations is denoted C RS and all other placements

forb

are called freecongurations and the set of these congurations is denoted C RS

free

Now consider the motion planning problem in rob otics Given a rob ot Ranwork space S and

initial conguration s and nal conguration t b oth p oints in the rob ots free conguration

space determine if p ossible a waytomove the rob ot from one conguration to the other

without intersecting any of the obstacles This reduces to the problem of determining whether

there is a path from s to t that lies entirely within the rob ots free conguration space Thus

we map the task of computing a rob ots motion to the problem of nding a path for a single

p oint through a collection of obstacles

Conguration spaces are typically higher dimensional spaces and are typically b ounded by

curved surfaces esp ecially when rotational elements are involved Perhaps the simplest case

to visualize is that of translating a convex p olygonal rob ot in the plane amidst a collection

of p olygonal obstacles In this cased b oth the work space and conguration space are two

dimensional Consider a reference p oint placed in the center of the rob ot As shown in the

gure ab ove the pro cess of mapping to conguration space involves replacing the rob ot with

t its reference p oint and growing the obstacles by a comp ensating amount a single p oin

These grown obstacles are called conguration obstacles or C obstacles

This approach while very general ignores many imp ortant practical issues It assumes that we

have complete knowledge of the rob ots environment and have p erfect knowledge and control

of its placement As stated we place no requirements on the nature of the path but in reality

physical ob jects can not b e broughttomove and stop instantaneously Nonetheless this

abstract view is very p owerful since it allows us to abstract the motion planning problem into

avery general framework

Lecture Notes CMSC M

For the rest of the lecture we will consider a very simple case of a convex p olygonal rob ot that

is translating among a convex set of obstacles Even this very simple problem has a number

of interesting algorithmic issues

Planning the Motion of a Point Rob ot As mentioned ab ove we can reduce complex motion

planning problems to the problem of planning the motion of a p oint in free conguration

space First we will consider the question of how to plan the motion of a p oint amidst a set of

p olygonal obstacles in the plane and then we will consider the question of how to construct

conguration spaces

To determine whether there is a path from one p oint to another of free conguration space we

will sub divide free space into simple convex regions In the plane we already knowhowtodo

this by computing a trap ezoidal map We can construct a trap ezoidal map for all of the line

segments b ounding the obstacles then throwawayany faces that lie in the forbidden space

We also assume that wehaveapoint lo cation data structure for the trap ezoidal map

Next we create a planar graph called a road map based on the trap ezoidal map To do this

we create a vertex in the center of each trap ezoid and a vertex at the midp ointofeachvertical

edge We create edges joining eachcenter vertex to the vertices on its at most four edges

t

s

Figure Motion planning using road maps

Now to answer the motion planning problem weassumewe are given the start p oint s and

destination p oint tWe lo cate the trap ezoids containing these twopoints and connect them

to the corresp onding center vertices We can join them by a straight line segment b ecause the

cells of the sub division are convex Then we determine whether there is a path in the road

map graph b etween these twovertices sayby breadthrst search Note that this will not

necessarily pro duce the shortest path but if there is a path from one p osition to the other it

will nd it

This description ignores many practical issues that arise in motion planning but it is the

basis for many practical motion planning problems More realistic conguration spaces will

contain more information for example enco dings of the currentjoint rotation velo cities

and will usually rene the road map to a muchnerextent so that short paths can b e

approximated well as well as handling other elements suchasguaranteeing minimal clearances

around obstacles

Conguration Obstacles and Minkowski Sums Nowthatwe knowhow to nd paths in con

guration space let us consider how to build conguration space for a set of p olygonal obsta

cles We again consider the simplest case of translating a convex p olygonal rob ot amidst a

collection of convex obstacles If the obstacles are not convex then wemay sub divide them

into convex pieces

Lecture Notes CMSC M

Consider a rob ot R whose placementisdenedby a translation x y so that Rx y denotes

the placement of the rob ot Given an obstacle P the conguration obstacle is dened as all

the placements of R that intersect P that is

CP fx y jRx y P g

One way to visualize CP is to imagine scraping R along the b oundary of P and seeing the

region traced out by Rs reference p oint

The problem we consider next is given R and P compute the conguration obstacle CP To

do this we rst intro duce the notion of a Minkowski sum Let us violate our notions of ane

geometry for a while and think of p oints x y in the plane as vectors Given anytwo sets S

and S in the plane dene their Minkowski sum to b e the set of all pairwise sums of p oints

taken from eachset

p S q S g S S fp q j

Also dene S fp j p S g Observe that for the case of a translating rob ot we could

dene Rx y asR fx y g

CP P+(-R(0,0))

P P

R(0,0) -R(0,0)

Figure Conguration obstacles and Minkowski sums

Claim Given a planar translating rob ot R and an obstacle P then the Cobstacle of P is

P R

Pro of We show that Rx y intersects P if and only if x y P R First if

Rx y intersects P then there must b e a p oint q q q such that q P Rx y

x y

This implies that q x q y R and hence x q y q R Since

x y x y

vex y P R q P by adding q q tothisweha

x y

Converselyifx y P R then there must b e p oints p p P and

x y

r r R such that p r p r x y Thus wehavep p r

x y x x y y x y x

x r y which implies that P intersects Rx y

y

Since it is an easy matter to compute R in linear time by simply negating all of its

vertices the problem of computing the Cobstacle CP reduces to the problem of computing a

ex p olygons We claim that this can b e done in O m n time Minkowski sum of twoconv

where m is the number of vertices in R and n is the number of vertices in P The algorithm

is based on the following observation Given a vector dWesay that a p oint p is extreme in

direction d if it maximizes the dot pro duct p d

Observation Given two p olygons P and R then the set of extreme p oints of P R in

direction d is the set of sums of p oints p and r that are extreme in direction d for P and

R resp ectively

Lecture Notes CMSC M

The b o ok leaves the pro of as an exercise It follows easily by the linearity of the dot pro duct

From this observation it follows that there is a simple rotating calip ers algorithm for computing

P R when b oth are convex p olygons In particular we p erform an angular sweep by

considering a unit vector d rotating counterclo ckwise around a circle As d rotates it is an

easy matter to keep trackofthevertex or edge of P and R that is extreme in this direction

Whenever d is p erp endicular to an edge of either P or Rwe add this edge to the vertex of

the other p olygon The algorithm is given in the text and is illustrated in the gure b elow

P e P+R

d e+r

d R r

d

Figure Computing Minkowski sums

Assuming P and R are convex observe that eachedgeofP and eachedgeofR contributes

exactly one edge to P R If two edges are parallel and on the same side of the p olygons

then these edges will b e combined into one edge which is as long as their sum Thus wehave

the following

Claim Given twoconvex p olygons P and Rwithn and m edges resp ectively their Minkowski

sum P R can b e computed in O n m time and consist of at most n m edges

Lecture More Motion Planning

Thursday Dec

Reading Chapt in BKOS

Motion planning Recall that the motion planning problem is that of determining whether there is

a path from one placement or conguration of a rob ot to another sub ject to the constraint

that the rob ot do es not intersect any of a set of p olygonal obstacles Weshowed that this

problem could b e solved by transforming the obstacles into conguration space where each

p oint in this space corresp onds to a particular conguration or p osition of the rob ot Then the

problem reduces to determining whether it is p ossible to get from the starting conguration

p oint to the ending conguration p oint The transformed obstacles are called conguration

obstacles or Cobstacles

We also showed that in the sp ecial case where the rob ot R can b e translated but not rotated

ie the conguration space is twodimensional then given a workspace obstacle P the

corresp onding conguration obstacle CP is the Minkowski sum P R Wealsoshowed

that if P and R are convex then it is p ossible to compute this Minkowski sum by a rotating

calip ers algorithm in O n m time where n and m are the numb er of sides in P and R

resp ectively

Complexity of Minkowski Sums Todaywecontinue to consider the case of translation only

b ecause it is the simplest nontrivial case and consider the questions of howwe can compute

Lecture Notes CMSC M

a complete description of the conguration space and what the combinatorial complexityof

this description mightbe

To b egin with lets see just how bad things might b e Supp ose you are given a rob ot R with

m sides and a set of workspace obstacle P with n sides Howmany sides might the Minkowski

sum P R have in the worst case O n m O nm even more The complexity generally

dep ends on what sp ecial prop erties if any P and R have

Nonconvex Rob ot and Nonconvex Obstacles Supp ose that b oth R and P are nonconvex sim

ple p olygons Let m be the numb er of sides of R and n b e the numb er of sides of P How

many sides might there b e in the Minkowski sum P R in the worst case We can derivea

to the quick upp er b ound as follows First observe that if we triangulate P we can break it in

union of at most n triangles That is

n

P T

i

i

m

R S

j

j

It follows that

n m

P R T S

i j

i j

Thus the Minkowski sum is the union of O nm p olygons each of constant complexityThus

there are O nm sides in all of these p olygons The arrangement of all of these line segments

can have at most O n m intersection p oints if eachsideintersects with each other and

hence this is an upp er b ound on the number of vertices in the nal result

Could things really b e this bad Yes they could Consider the two p olygons in the gure b elow

left There are O n m ways that these two p olygons can b e do cked as shown on the right

The Minkowski sum P R is shown in the text Notice that the large size is caused by the

numb er of holes It might b e argued that this is not fair since we are not really interested

in the entire Minkowski sum just a single face of the Minkowski sum Proving b ounds on the

complexity of a single face is an interesting problem and the analysis is quite complex

P

R

Figure Minkowski sum of O n m complexity

As a nal observation notice that the upp er b ound holds even if P and R for that matter is

not a single simple p olygon but any union of n triangles

Convex Rob ot and Nonconvex Obstacles Wehave seen that the worstcase complexity of the

Minkowski sum might range from O n m to as high as O n m which is quite a gap Let

us consider an intermediate but realistic situation Supp ose that we assume that P is an

arbitrary nsided simple p olygon and R is a convex msided p olygon Typically m is much

Lecture Notes CMSC M

smaller than n What is the combinatorial complexityof P R in the worst case As b efore

we can observethatP can b e decomp osed into the union of n triangles T implying that

i

n

P R T R

i

i

Each Minkowski sum in the union is of complexity m So the question is howmany sides

might there b e in the union of O nconvex p olygons each with O m sides We could derive

a b ound on this quantity but it will give a rather p o or b ound on the worstcase complexity

To see why consider the limiting case of m Wehave the union of n convex ob jects

each of complexity O This could have complexityashighasn as seen by generating

ou try to construct suchacounter a crisscrossing pattern of very skinny triangles But if y

example you wont b e able to do it

To see why suchacounterexample is imp ossible supp ose that you start with nonintersecting

triangles and then take the Minkowski sum with some convex p olygon The claim is that it is

imp ossible to generate this sort of crisscross arrangement So how complex an arrangement

can you construct We will show the following

Theorem Let R be a convex mgon and P and simple ngon then the Minkowski sum P R

has total complexity O nm

Is O nm an attainable b ound The idea is to go back to our analogy of scraping R around

the b oundary of P Canwe arrange P such that most of the edges of R scrap e over most of

the n vertices of P Supp ose that R is a regular convex p olygon with m sides and that P has

the comb structure shown in the gure b elow where the teeth of the comb are separated by

a distance at least as large as the diameter of R In this case R will havemany sides scrap e

across each of the p oint y ends of the teeth implying that the nal Minkowski sum will have

total complexitynm

P+R

R

P

Figure Minkowski sum of O nm complexity

The Union of Pseudo disks Toshow that O nm is an upp er b ound we need some way of ex

tracting the sp ecial geometric structure of the union of Minkowski sums Recall that we are

computing the union of T R where the T s have disjointinteriors The conguration that

i i

wewanttoavoid is the crisscross pattern shown ab ove Howdoweprove that such a pattern

cannot b e created The key is in the way the Minkowski sums of disjoint ob jects can intersect

We call a pair of convex ob jects o and o are a pair of pseudodisks if the b oth of the dierences

o no and o no are connected In particular if the ob jects intersect then they do not cross

through one another

Note that the b eing a pseudodisk is not a prop erty of a single ob ject but is the prop ertyof

pairs of ob jects A collection of ob jects is said to b e a col lection of pseudodisks if each pair is

a pair of pseudo disks The theorem ab o ve will follow from the next two lemmas

Lecture Notes CMSC M

Pseudodisks Not pseudodisks

Figure Pseudo disks

Lemma Given a set convex ob jects T T T with disjointinteriors and convex R

n

the set

fT R j i ng

i

is a collection of pseudo disks

Lemma Given a collection of pseudo disks with a total of n vertices the complexityof

their union is O n In our case the total number of vertices is O nm

First weprove Lemma Consider two p olygons T and T with disjointinteriors Wewant

to show that T R and T R do not cross over one another There is a very easy wayto

visualize why this is true but it is not a rigorous pro of Recall that the Minkowski sum

T R is related to scraping the negation R around the b oundary of T Supp ose we scrap e

R around the union of T and T Iftheinteriors of these two p olygons do not intersect then

either these two scrapings do not intersect each other at all or else they intersect in exactly

two p oints But from convexity it is plausible that there should not b e more than two

intersections

Here is a careful pro of Recall from yesterdays lecture that given any directional unit vector d

the most extreme pointofR in direction d is the p oint r R that maximizes the dot pro duct

d r Recall that we treat the p oints of the p olygons as if they were vectors The p oint

of T R that is most extreme in direction d is the sum of the p oints t and r that are most

extreme for T and R resp ectively

Given two convex p olygons T and T with disjointinteriors they dene two outer tangents

as shown in the gure b elow Let d and d b e the outward p ointing p erp endicular vectors for

these tangents Because these p olygons do not intersect it follows easily that as the directional

vector rotates from d to d T will b e the more extreme p olygon and from d to d T will

b e the more extreme See the gure b elow

Now if to the contrary T R and T R had a crossing intersection then observe that we

can nd p oints p p p andp in cyclic order around the b oundary of the convex hull of

T R T R suchthatp p T R and p p T R First consider p Because

it is on the convex hull consider the direction d p erp endicular to the supp orting line here

Let r t andt b e the extreme p oints of R T and T in direction d resp ectivelyFrom our

basic fact ab out Minkowski sums wehave

p r t p r t

Since p is on the convex hull it follows that t is more extreme than t in direction d that

is T is more extreme than T in direction d By applying this same argument we nd that

is more extreme than T in directions d and d but that T is more extreme than T in T

directions d and d But this is imp ossible since from the observation ab ove there can b e

Lecture Notes CMSC M

d d2 T1 2 T1 extreme

d d 1 1 T2 extreme

T2 Figure Alternation of extremes

T2 extreme d2 d2 d3 d3 T1ext T1+R

T2+R d1 d1 d4 T1 extreme T2 extreme

d4

Figure Pro of of Lemma

Lecture Notes CMSC M

at most one alternation in extreme p oints for nonintersecting convex p olygons See the gure

below

Next we prove Lemma This is a rather cute combinatorial lemma Wearegiven some

collection of pseudo disks and told that altogether they have n vertices We claim that their

entire union has complexity O n Recall that in general the union of n convex p olygons can

have complexity O n by crisscrossing The pro of is based on a clever charging scheme

Eachvertex in the union will b e charged to a vertex among the original psuedo disks such that

no vertex is charged more than twice This will imply that the total complexityisatmostn

There are twotyp es of vertices that may app ear on the b oundary The rst are vertices from

the original p olygons that app ear on the union There can b e at most n suchvertices and

eachischarged to itself The more troublesome vertices are those that arise when two edges of

two pseudo disks intersect each other Supp ose that twoedges e and e of pseudo disks P and

P intersect along the union Followedge e into the interior of the pseudo disk e Two things

might happ en First wemight hit the endp oint v of this e b efore leaving the interior P In

this case charge the intersection to v Note that v can get at most twosuchcharges one from

either incident edge If e passes all the waythrough P b efore coming to the endp oint then

try to do the same with edge e Again if it hits its endp oint b efore coming out of P then

charge to this endp oint See the gure b elow

e2 e1 e2 e1 e2 e1

v v u v u

Charge v Charge u Cannot happen

Figure Pro of of Lemma

But what do we do if b oth e sho ots straightthrough P and e sho ots straight through P

Nowwehavenovertex to charge This is okay b ecause the pseudo disk prop erty implies that

this cannot happ en If b oth edges sho ot completely through then the two p olygons must cross

over each other

Lecture Final Review

Tuesday Dec

Announcements Class is cancelled this Thursday Oce hours on Wednesday will b e moved up

to pm Ill b e holding usual oce hours on Monday from pm on the day b efore

the nal

Final Exam Tues Dec am The exam will b e closedb o ok closednotes but you

are allowed twocheatsheets front and back

Before the Midterm Convex hulls line segmentintersection planar graphs and DCELs p oly

gon triangulation intersection of halfspaces linear programming in low dimensions orthogonal

range searching planar p oint lo cation trap ezoidal maps You should b e aware of the results

denitions and general techniques but I will not ask you for detailed information eg simu

lating Kirkpatricks algorithm on a data set

Lecture Notes CMSC M

Voronoi diagrams Recall the denition of Voronoi diagrams We presented Fortunes algorithm

which op erated bysweeping a distorted sweepline Voronoi diagrams havemany applica

tions in problems dealing with distances More generallyVoronoi diagrams are an example

of the notion of sub dividing the plane into regions according to some criterion In this case

we sub divide the plane into regions according to who the nearest neighb or is It is p ossible to

dene other sorts of diagrams For example the ndorder Voronoi diagram is a sub division

of the plane according to who your rst two nearest neighb ors are and the k thorder diagram

is dened similarly for the k nearest neighb ors Also the furthest p ointVoronoi diagram is

dened according to whichpoint is the furthest from this p oint Voronoi diagrams can b e

computed for line segments as well and are often used in motion planning applications

DelaunayTriangulations This is the dual of the Voronoi diagram We discussed prop erties such

as the fact that the Delaunay triangulation maximized the minimum angle We presented a

randomized incremental algorithm for the Delaunay triangulation Generally triangulations

play an imp ortant role in computational geometry since they allow us to reduce complex

domains to a collection of simpler domains triangles DeFloriani describ ed howany algorithm

for incrementally up dating a triangulation could b e used for generating a hierarchical surface

representation similar to Kirkpatricks algorithm You are not resp onsible for the details of

her presentation but for understanding how up date rules for triangulations can b e used to

generate hierarchical surface representations

Line Arrangements Weshowed that line arrangements together with dualit y could b e used for

answering many problems having to do with lines and p oints in the plane We presented a

simple incremental construction algorithm for arrangements in the plane proved its O n

running time with the zone theorem We discussed top ological plane sweep as a metho d for

traversing an planar arrangement Duality and arrangements can also b e generalized to higher

dimensions

We presented a numb er of applications of arrangements These included sorting angular se

quences computing the narrowest corridor computing the maximum discrepancy and dis

cussed the notion of a level in an arrangement On Homework Problem we also saw

that there are problems that can b e solved by using the arrangement to conceptualize a

solution even though the actual solution may not involve constructing the arrangement You

should probably exp ect at least one problem on the exam whose solution will require use of

arrangements

Shortest Paths and Visibility Graphs We discussed the problem of computing shortest paths

in the plane and how visibility graphs could b e used to reduce the shortest path problem to

a problem on graphs Notice that using visibility graphs do es not extend to three dimensional

shortest path problems since a shortest path maybendanywhere along the interior of an edge

Nonetheless b ecause graph problems are often much easier to solve the technique of extracting

a graph from a geometric setting is an imp ortant concept Wesaw in Homework Problem

that some sp ecial shortest path problems can b e solved without explicitly constructing a

visibility graph at all For example shortest paths in simple p olygons can b e solved in O n

time once the p olygon has b een triangulated The solution is somewhat more complicated

but still similar to the homework solution

Motion Planning Weintro duced conguration spaces and discussed the idea of mapping work

space obstacles in to obstacles in conguration space We discussed Minkowski sums as a

metho d for computing conguration obstacles where translation is involved Weshowed how

to compute the Minkowski sum of twoconvex p olygons in linear time We also discussed

the combinatorial complexity of the union of a geometric ob jects when these ob jects satised

sp ecial conditions Although the general complexity could b e as high as O n weshowed

that if the ob jects are convex pseudo disks then the complexity only has complexity O n

Lecture Notes CMSC M

Lecture X Randomized Trap ezoidal Decomp osition

Supplemental

Randomized Incremental Algorithms We consider the following problem Given a set of p os

sibly intersecting line segments in the plane sub divide the plane into a collection of trap ezoids

formed by sho oting a bullet to the left and rightofeachvertex and eachintersection p oint

until it hits the rst ob ject Following Mulmuleys presentatio

The running time of this algorithm will b e O k n log n with high probability where n is the

numb er of segments and k is the number of intersection p oints b etween the segments More

succinctly the running time is Ok n log n Mulmuley uses the notation f n O g n

if for all suciently large n f n cgn for some constant c with probability pn

where pn is a p olynomial whose degree increases with cThus we can reduce the probability

that the running time fails to b e O g n as lowaswe like up to the recipro cal of high degree

p olynomial function of n Observe that this running time is asymptotically b etter than the

previous in the sense that wehaveremoved the log n multiplicative factor from in front of the

k The price wehave paid is that the running time is now randomized and so not guaranteed

Randomized Incremental Algorithm The basic idea of the algorithm is describ ed b elow

i

Randomly permute the set of segments Let N denote the rst i segments In general

i

H N will denote the trap ezoidal decomp osition of the rst i segments

Initialize the structure to a trivial empty trap ezoidal decomp osition eg a large empty

enclosing b ox H N

One by one add the segments in random order For each segment do the following

i

a Locate the trap ezoid of H n containing the left endp oint of the segmen t There

areacoupleofways to do this More on this later

b Trace the segment from one trap ezoid to the next At the endp oints of the segment

split the current trap ezoid by adding a vertical wall For each trap ezoid determine

the p ointofentry and p oint of exit of the segment If the segment crosses the top

or b ottom then create new intersection p oints and split the trap ezoid by adding a

vertical wall

i

c After tracing the segment determine the vertical walls of H N thatwere stabb ed

by the segment For each suchwall trim it backtotheportioncontaining its sup

p orting vertex This results in the merger of two adjacent trap ezoids

The implementation of the algorithm relies on the ability to p erform the necessary lo cal ma

nipulations of the planar graph representing the trap ezoidal decomp osition In particular we

assume that we can trace a segment through a face of the decomp osition split a face

by the addition of a vertical wall and merge two adjacent faces when a vertical wall is

trimmed in time prop ortional to the complexity of the face that is the number of vertices

equivalently edges on the face We let f denote a trap ezoidal face of the decomp osition

f denote the complexity of this face Observe that the running time of the ab ove and let c

algorithm is O cf for each face that is traced by this pro cedure b ecause there can only b e

a constantnumb er at most split p erformed for each trap ezoid and a constantnumb er at

most merges for each trap ezoid

The other question weleftopenwas how to lo cate the leftendp oint from which to start the

tracing We do this using a simple bucketing strategyFor eachofthen leftendp oints we

store which trap ezoid of the current sub division contains this p oint and with each trap ezoid f

we asso ciate a list Lf whichcontains the segments whose leftendp oint lies within this face

When we wish to trace a segment we can determine the trap ezoid containing this segment

Lecture Notes CMSC M

Initial decomposition.

Trace and split.

Trim and merge.

Figure Randomized incremental trap ezoidal decomp osition

Lecture Notes CMSC M

in constant time When a segmentintersects a trap ezoid f itmay split a trap ezoid f into

a constantnumb er of new trap ezoids We can walk through the list Lf and determine

which of the new trap ezoids contains a given p oint in constant time each We form new left

endp oint lists for each of the new faces Lf Lf etc When we merge two trap ezoids

we simply concatenate their lists Observe that b oth of these op erations can b e p erformed in

time O l f where l f jLf j

f 3

f f 1 f 2

c(f) = 9 l(f) = 5 c(f1) = 7 l(f1) = 2 c(f2) = 5 l(f2) = 2

c(f3) = 4 l(f3) = 1

Figure Splitting a face

i

Lemma Consider the insertion of segmentinto H N whichintersects faces F ff f f g

k

in the decomp osition The time to insert this segmentis

X

A

O cf l f

f F

Analysis Analyzing the exp ected case running time of this algorithm is quite a tricky task We

want to show that no matter what n segments are given initiallyifwe randomize of all p ossible

insertion orders the total exp ected time to build the decomp osition is O k n log n We will

only prove that this is an exp ected b ound The pro of that this holds with high probability

takes some additional work In particular we seem to need to b e able to determine the

P

exp ected value of cf l f over all segments that might b e inserted next

f

k called backward This task would b e quite daunting if it were not for a very clever analysis tric

analysis Here is the idea we imagine that we are running time algorithm backwards deleting

segments one at a time Whether wecountbackwards or forwards makes no dierence The

running time of a given stage is still given by the lemma ab ove Observe that if all insertion

orders are equally likely then the last segment to b e deleted in the reversed algorithm is equally

i

likely to b e any one of the segments that already exists in the decomp osition H N Since

i

every segmentofN is equally likely to b e deleted to determine the exp ected time for the ith

stage it suces to average over all p ossible segments i to b e deleted and for each determine

the complexity if this were the segmentchosen

i

When we delete some segment from the H N observe that the only trap ezoids that would b e

i

aected from its deletion consist of the trap ezoids of H N that are adjacent to this segment

An example is shown in the gure b elow

Lemma For each j j ilet F denote the faces that the j th segmentintersects in

j

i i

H N The exp ected time for the last stage in the construction of H N is on the order

Lecture Notes CMSC M

Regions affected by deletion.

Final decomposition.

Figure Aected trap ezoids

of

i

X X

E i cf l f

i

j

f F

j

We seem to b e no closer to our goal since there do es not app ear to b e an easy way to analyze the

sums of complexities of all the trap ezoids that a given segmentintersects However the crucial

trick is not to count segmentby segment but to count trap ezoid by trap ezoid Assuming that

the segments are in general p osition observe the following imp ortant fact

Lemma Bounded degree prop erty Each trap ezoid in a trap ezoidal decomp osition is adja

cent to at most segments Namely the segments immediately ab ove and b elow and

the segments which touch the left and rightwalls of the trap ezoid either b ecause of an

endp ointoranintersection p oint

Thus if wetake the complexityofeach trap ezoid and multiply bywe will have an upp er

b ound on the sum of complexities of all the trap ezoids that are intersected by all segments

X

cf l f E i

i

i

f H N

X X

A

cf l f

i

i i

f H N f H N

P

Now this is something we can analyze Weknowthevalue of cf is the sum of all the

f

edges summed over all the faces in the decomp osition However this counts every edge in

the decomp osition twice Since the decomp osition is a planar graph this is prop ortional to

P

the number of vertices in the decomp osition currentlyThevalue of l f is just equal to

f

n i since it includes all the left endp oints of segments that haveyet to b e added If we

let k denote the numberofintersection p oints at the current stage of the decomp osition the

i

i

numberofvertices in H N is just i k so the ab oveformula simplies to

i

E i i k n i

i

i

Lecture Notes CMSC M

cn k

i

i

for some constant c The interesting thing at this p oint is that although our analysis was

i

conditional on the structure of H N the resulting b ound is almost entirely indep endentof

this structure Only the value k is dep endent

i

Atthispointwe can see where the analysis is going If we ignore the k term in the ab ove we

i

see that E i cniTo get the total time we sum these up getting at total exp ected time

of

n

X

TEn E i

i

n

X

cn

i

i

n

X

cn

i

i

cn ln n O n log n

P

The last line uses the well known fact that the Harmonic series i tends to ln n

in

We need to get a handle on what k is exp ected to b e Obviously the value of k should

i i

eventually approach k the total numberofintersections as i approaches n The interesting

fact is that this quantity approaches k quadratically not linearly

i

Lemma For xed i the exp ected value of k assuming that N is a random sample of

i

N of size iis O ki n

Pro of For eachintersection p oint v between twosegments s and s let I denote the

v

i

random variable that this if this intersection is part of the decomp osition H N and

P

otherwise Observe that the exp ected value of k is I However v o ccurs within

i v

v

I if and only if b oth s and s o ccur within the rst i randomly selected segments The

v

probability that each one has b een selected alone is in The probabilitythatbothhave

b een selected is roughly i n for i and n large Thus the exp ected value of k is k times

i

this quantityor O ki n

P

To complete the analysis wemake use of another basic fact from summations i

in

n

n

X

E i TEn

i

n

X

cn k

i

i

i

n n

X X

cn ck

i

i i

i i

n n

X X

ki

c cn

i n i

i i

n

X

ck

cn ln n i

n

i

cn ln n ck

O n log n k

Lecture Notes CMSC M

Lecture X Voronoi Diagrams

Supplemental

Read ORourke Chapt Mulmuley Sect

Planar Voronoi Diagrams Recall that given n p oints P fp p p g in the plane the

n

Voronoi p olygon of a p oint p V p is dened to b e the set of all p oints q in the plane for

i i

which p is among the closest p oints to q in P Thatis

i

V p fq jp q j jp q j j ig

i i j

The union of the b oundaries of the Voronoi p olygons is called the Voronoi diagram of P

denoted VDP The dual of the Voronoi diagram is a triangulation of the p oint set called

the Delaunay triangulation Recall from our discussion of quadedge data structure that given

a go o d representation of any planar graph the dual is easy to construct Hence it suces

to showhow to compute either one of these structures from which the other can b e derived

easily in O n time

There are four fairly wellknown algorithms for computing Voronoi diagrams and Delaunay

triangulations in the plane They are

DivideandConquer For b oth VD and DT The rst O n log n algorithm for this prob

lem Not widely used b ecause it is somewhat hard to implement Can b e generalized to

higher dimensions with some diculty Can b e generalized to computing Vornoi diagrams

of line segments with some diculty

Randomized Incremental For DT and VD The simplest O n log n time with high

probability Can b e generalized to higher dimensions as with the randomized algorithm

for convex hulls Can b e generalized to computing Voronoi diagrams of line segments

fairly easily

Fortunes Plane Sweep For VD A very clever and fairly simple algorithm It computes

a deformed Voronoi diagram by plane sweep in O n log n time from which the true

diagram can b e extracted easily Can b e generalized to computing Voronoi diagrams of

line segments fairly easily

Reduction to convex hulls For DT Computing a Delaunay triangulation of n points in

dimension d can b e reduced to computing a convex hull of n p oints in dimension d

Use your favorite convex hull algorithm Unclear how to generalize to compute Voronoi

diagrams of line segments

We will cover all of these approaches except Fortunes algorithm ORourkedoesnotgive

detailed explanations of any of these algorithms but he do es discuss the idea b ehind For

tunes algorithm Todaywe will discuss the divideandconquer algorithm This algorithm is

presented in Mulmuley Section

Divideandconquer algorithm The divideandconquer approachworks like most standard ge

ometric divideandconquer algorithms We split the p oints according to xco ordinates into

roughly equal sized groups eg by presorting the p oints by xco ordinate and selecting medi

ans We compute the Voronoi diagram of the left side and the Voronoi diagram of the right

side Note that since each diagram alone covers the entire plane these twodiagramsoverlap

We then merge the resulting diagrams into a single diagram

The merging step is where all the work is done Observethatevery p oint in the the plane

lies within twoVoronoi p olygons one in VDLandoneinVDR We need to resolve this

overlap by separating overlapping p olygons Let V l betheVoronoi p olygon for a p oint

Lecture Notes CMSC M

from the left side and let V r betheVoronoi p olygon for a p oint on the right side and

supp ose these p olygons overlap one another Observethatifwe insert the bisector b etween

l and r and through away the p ortions of the p olygons that lie on the wrong side of the

bisector we resolve the overlap If we do this for every pair of overlapping Voronoi p olygons

we get the nal Voronoi diagram This is illustrated in the gure b elow

Left/Right Diagrams and Contour

Final Voronoi Diagram

Figure Merging Voronoi diagrams

The union of these bisectors that separate the left Voronoi diagram from the rightVoronoi

diagram is called the contourApoint is on the contour if and only if it is equidistant from

p oints in S one in L and one in R

Presort the p oints by xco ordinate this is done once

Split the p ointset S bya vertical line into twosubsets L and R of roughly equal size

Compute VDLandVDR recursively These diagrams overlap one another

Merge the two diagrams into a single diagram by computing the contour and discarding

the p ortion of the VDL that is to the right of the contour and the p ortion of VDR

that is to the left of the contour

Assuming we can implement step in O n time where n is the size of the remaining p oint

set then the running time will b e dened by the familiar recurrence

T nT n n

whichwe know solves to O n log n

Lecture Notes CMSC M

Computing the contour What makes the divideandconquer algorithm somewhat tricky is the

task of computing the contour Before giving an algorithm to compute the contour let us

make some observations ab out its geomtetric structure Let us make the usual simplifying

assumptions that no p oints are co circular

Lemma The contour consists of a single p olygonal curve whose rst and last edges are

semiinnite which is monotone with resp ect to the y axis

Pro of A detailed pro of is a real hassle Here are the main ideas though The contour

separates the plane into two regions those p oints whose nearest neighbor lies in L from

those p oints whose nearest neighb or lies in R Because the contour lo cally consists of

points that are equidistantfrompoints it is formed from pieces that are p erp endicular

bisectors with one p oint from L and the other p oint from RThus it is a piecewise

p olygonal curve Because no p oints are co circular it follows that all vertices in the

Voronoi diagram can have degree at most However b ecause the contour separates the

plane into only typ es of regions it can contain only vertices of degree Thus it can

consist only of the disjoint union of closed curves actually this never happ ens as we

will see and unb ounded curves Observe thatifwe orientthecontour counterclo ckwise

with resp ect to each p ointin R clo ckwise with resp ect to each p ointinL then each

segmentmust b e directed in the y directions b ecause L and R are separated bya

vertical line Thus the contour contains no horizontal cusps This implies that the

contour cannot contain any closed curves and hence contains only vertically monotone

unb ounded curves Also this orientability also implies that there is only one such curve

Lemma The topmost b ottommost edge of the contour is the p erp endicular bisector for the

twopoints forming the upp er lower tangent of the left hull and the righthull

Pro of This follows from the fact that the vertices of the hull corresp ond to unb ounded

Voronoi p olygons and hence upp er and lower tangents corresp ond to unb ounded edges

of the contour

These last two theorem suggest the general approach We start by computing the upp er

tangent whichweknow can b e done in linear time once weknow the left and righthulls or

by prune and search Then we start tracing the contour from top to b ottom When we are

in Voronoi p olygons V l and V r we trace the bisector b etween l and r in the negative

y direction until its rst contact with the b oundaries of one of these p olygons Supp ose that

we hit the b oundary of V l rst Assuming that we use a go o d data structure for the Voronoi

diagram eg quadedge data structure we can determine the p oint l lying on the other side

of this edge in the left Voronoi diagram Wecontinue following the contour by tracing the

bisector of l and r

However in order to insure eciencywemust b e careful in howwe determine where the

bisector hits the edge of the p olygon Consider the gure shown b elow We start tracing the

contour b etween l and r Bywalking along the b oundary of V l we can determine the edge

that the contour would hit rst This can b e done in time prop ortional to the number of edges

in V l which can b e as large as O n However we discover that b efore the contour hits the

b oundary of V l it hits the b oundary of V r W e nd the new p oint r and now trace the

bisector b etween l and r Again we can compute the intersection with the b oundary of V l

in time prop ortional to its size However the contour hits the b oundary of V r rst and so

wegoontor As can b e seen if we are not smart we can rescan the b oundary of V l over

and over again until the contour nally hits the b oundaryIfwedothisO n times and the

b oundary of V l isO n then we are stuck with O n timetotracethecontour

Wehavetoavoid this rep eated rescanning However there is a way to scan the b oundary of

eachVoronoi p olygon at most once Observethataswewalk along the contour each time we

Lecture Notes CMSC M

Contour

r0

l 0 r1

r2

Figure Tracing the contour

stay in the same p olygon V l we are adding another edge onto its Voronoi p olygon Because

the Voronoi p olygon is convex weknow that the edges we are creating turn consistently in

the same direction clo ckwise for p oints on the left and counterclo ckwise for p oints on the

right To test for intersections b etween the contour and the currentVoronoi p olygon we trace

the b oundary of the p olygon clo ckwise for p olygons on the left side and counterclo ckwise for

p olygons on the right side Whenever the contour changes direction wecontinue the scan

from the p ointthatwe left o In this waywe knowthatwe will never need to rescan the

same edge of anyVoronoi p olygon more than once

Lecture X DelaunayTriangulations and Convex Hulls

Supplemental

Read ORourke and

DelaunayTriangulations and Convex Hulls At rst Delaunay triangulations and convex hulls

app ear to b e quite dierent structures one is based on metric prop erties distances and the

other on ane prop erties collinearity coplanarity Todayweshow that it is p ossible to con

vert the problem of computing a Delaunay triangulation in dimension d to that of computing

aconv ex hull in dimension d Thus there is a remarkable relationship b etween these two

structures

We will demonstrate the connection in dimension by computing a convex hull in dimension

Some of this may b e hard to visualize but see ORourke for illustrations You can also

reason by analogy in one lower dimension of Delaunay triangulations in d and convex hulls

in d but the real complexities of the structures are not really apparent in this case

The connection b etween the two structures is the paraboloid z x y Observe that this

equation denes a surface whose vertical cross sections constant x or constant y are parab olas

and whose horizontal cross sections constant z are circles For eachpoint in the plane x y

the vertical projection of this p ointonto this parab oloid is x y x y in space Given a set

of p oints S in the plane let S denote the pro jection of every p ointin S onto this parab oloid

Consider the lower convex hul l of S This is the p ortion of the con vex hull of S whichis

visible to a viewer standing at z We claim that if we take the lower convex hull of S

and pro ject it backonto the plane then we get the Delaunay triangulation of S In particular

let p q r S and let p q r denote the pro jections of these p oints onto the parab oloid

Then p q r dene a face of the lower convex hull of S if and only if pq r is a triangle of the

Delaunay triangulation of S The pro cess is illustrated in the following gure

Lecture Notes CMSC M

Project onto paraboloid. Compute convex hull. Project hull faces back to plane.

Figure Delaunay triangulations and convex hull

The question is whydoesthiswork To see whywe need to establish the connection b etween

the triangles of the Delaunay triangulation and the faces of the convex hull of transformed

p oints In particular recall that

Delaunay condition Three p oints p q r S form a Delaunay triangle if and only if the

circumcircle of these p oints contains no other p ointofS

Convex hull condition Three p oints p q r S form a face of the convex hull of S if

and only if the plane passing through p q and r has all the p oints of S lying to one

side

Clearly the connection we need to establish is b etween the emptiness of circumcircles in the

plane and the emptiness of halfspaces in space Wewillprove the following claim

Lemma Consider distinct p oints p q rs in the plane and let p q r s b e their resp ective

pro jections onto the parab oloid z x y The p oint s lies within the circumcircle of

p q r if and only if s lies on the lower side of the plane passing through p q r

To prove the lemma rst consider an arbitrary nonvertical plane in space whichwe assume

is tangent to the parab oloid ab ove some p ointa bintheplaneTo determine the equation

of this tangentplanewe take derivatives of the equation z x y with resp ect to x and y

giving

z z

x y

x y

At the p ointa b a b these evaluate to a and b It follows that the plane passing through

these p oint has the form

z ax by

Tosolvefor we know that the plane passes through a b a b sowe solve giving

a b a a b b

Implying that a b Thus the plane equation is

z ax by a b

If we shift the plane upwards by some p ositiveamount r we get the plane

z ax by a b r

Lecture Notes CMSC M

How do es this plane intersect the parab oloid Since the parab oloid is dened by z x y

we can eliminate z giving

x y ax by a b r

which after some simple rearrangements is equal to

x a y b r

This is just a circle Thus wehaveshown that the intersection of a plane with the parab oloid

pro duces a space curve which turns out to b e an ellipse which when pro jected backonto the

x y co ordinate plane is a circle centered at a b

Thus we conclude that the intersection of an arbitrary lower halfspace with the parab oloid

when pro jected onto the x y plane is the interior of a circle Going back to the lemma when

we pro ject the p oints p q r onto the parab oloid the pro jected p oints p q and r dene a

plane Since p q andr lie at the intersection of the plane and parab oloid the original

p oints p q r lie on the pro jected circle Thus this circle is the unique circumcircle passing

through these p q andr Thus the p oint s lies within this circumcircle if and only if its

pro jection s onto the parab oloid lies within the lower halfspace of the plane passing through

p q r

p’ r’ s’ q’

q s

r p

Figure Planes and circles

Nowwe can prove the main result

Theorem Given a set of p oints S in the plane assume no are co circular and given

points p q r S the triangle pq r is a triangle of the Delaunay triangulation of S if

and only if triangle p q r is a face of the lower convex hull of the pro jected set S

From the denition of Delaunay triangulations we know that pq r is in the Delaunay trian

gulation if and only if there is no p oint s S that lies within the circumcircle of pq r From

the previous lemma this is equivalenttosaying that there is no p oint s that lies in the lower

convex hull of S which is equivalenttosaying that p q r is a face of the lower convex hull

This completes the pro of

In order to test whether a p oint s lies within the circumcircle dened by p q r it suces to

lies within the lower halfspace of the plane passing through p q r Ifwe test whether s

assume that p q r are oriented counterclo ckwise in the plane this this reduces to determining

whether the quadruple p q r s is p ositively oriented or equivalently whether s lies to the

left of the oriented circle passing through p q r

Lecture Notes CMSC M

This leads to the incircle test we presented last time

p p p p

x y

x y

B C

q q q q

x y

x y

B C

inp q rs det

A

r r r r

x y

x y

s s s s

x y

x y

Voronoi Diagrams and Upp er Envelop es Weknow that Voronoi diagrams and Delaunay tri

angulations are dual geometric structures Wehave also seen informally that there is a dual

relationship b etween p oints and lines in the plane and in general p oints and planes in space

From this latter connection we argued that the problems of computing convex hulls of p oint

sets and computing the intersection of halfspaces are somehow dual to one another It turns

are not surprisingly interrelated In particular in out that these two notions of duality

the same way that the Delaunay triangulation of p oints in the plane can b e transformed to

computing a convex hull in space it turns out that the Voronoi diagram of p oints in the

plane can b e transformed into computing the intersection of halfspaces in space

Here is howwe do this For each p oint p a b in the plane recall the tangent plane to the

parab oloid ab ovethispoint given by the equation

z ax by a b

Dene H p to b e the set of p oints that are ab ove this halfplane that is H p fx y z j z

ax by a b gLetS fp p p g b e a set of p oints Consider the intersection of

n

the halfspaces H p This is also called the upper envelope of these halfspaces The upp er

i

envelop e is an unb ounded convex p olyhedron If you pro ject the edges of this upp er envelop e

down into the plane it turns out that you get the Voronoi diagram of the p oints

Theorem Given a set of p oints S in the plane assume no are co circular let H denote

the set of upp er halfspaces dened by the previous transformation Then the Voronoi

diagram of H is equal to the pro jection onto the x y plane of the skeleton of the

convex p olyhedron which is formed from the intersection of halfspaces of S

q’ p’

p

q

Figure Intersection of halfspaces

It is hard to visualized this surface but it is not hard to showwhy this is so Supp ose wehave

p oints in the plane p a b and q c d The corresp onding planes are

z ax by a b and z cx dy c d

Lecture Notes CMSC M

If we determine the intersection of the corresp onding planes and pro ject onto the x y

co ordinate plane by eliminating z from these equations weget

xa c y b d a c b d

We claim that this is the p erp endicular bisector b etween a bandc d To see this observe

that it passes through the midp ointa c b d b etween the twopoints since

b d a c

a c b da c b d

and its slop e is a cb d which is the negative recipro cal of the line segment from

a btoc d From this it can b e shown that the intersection of the upp er halfspaces denes

a p olyhedron whose edges pro ject onto the Voronoi diagram edges

Lecture X Top ological Plane Sweep

Supplemental

Read The material on top ological plane sweep is not discussed in any of our readings The

algorithm for top ological plane sweep can b e found in the pap er Top ologically sweeping an ar

rangement by H Edelsbrunner and L J Guibas J Comput Syst Sci with

Corrigendum in the same journal volume

Top ological Plane Sweep In the last two lectures wehaveintro duced arrangements of lines and

geometric duality as imp ortant to ols in solving geometric problems on lines and p oints Today

give an ecient algorithm for sweeping an arrangement of lines

As we will see many problems in computational geometry can b e solved by applying line

sweep to an arrangement of lines Since the arrangement has size O n and since there are

O n events to b e pro cessed eachinvolving an O log n heap deletion this typically leads to

algorithms running in O n log n time using O n space It is natural to ask whether we

can disp ense with the additional O log n factor in running time and whether we need all of

O n space since in theory we only need access to the current O ncontents of the sweep

line

We discuss a variation of plane sweep called topological plane sweep This metho d runs in O n

time and uses only O n space byessentially constructing only the p ortion of the arrangement

that we need at any p oint Although it may app ear to b e somewhat sophisticated it can

b e implemented quite eciently and is claimed to outp erform conventional plane sweep on

arrangements of any signicant size eg over lines

plane sweep b ecause we do not Cuts and top ological lines The algorithm is called topological

sweep a straightvertical line through the arrangement but rather wesweep a curved topological

line that has the essential prop erties of a vertical sweep line in the sense that this line intersects

each line of the arrangement exactly once The notion of a top ological line is an intuitive one

but it can b e made formal in the form of something called a cut Recall that the faces of

the arrangement are convex p olygons p ossibly unb ounded Assuming no vertical lines the

edges incidenttoeach face can naturally b e partitioned into the edges that are above the face

and those that are below the face Dene a cut in an arrangement to b e a sequence of edges

c c c in the arrangement one taken from each line of the arrangement suchthatfor

n

i n c and c are incident to the same face of the arrangement and c is ab ove

i i i

the face and c is b elow the face An example of a top ological line and the asso ciated cut is

i

shown b elow

Lecture Notes CMSC M

c1

c2

c3 c4

c5

Figure Top ological line and asso ciated cut

The top ological plane sweep starts at the leftmost cut of the arrangement This consists of

all the leftunb ounded edges of the arrangement Observe that this cut can b e computed in

O n log n time b ecause the lines intersect the cut in inverse order of slop e The top ological

sweep line will sweep to the rightuntil wecometotherightmost cut which consists all of the

rightunb ounded edges of the arrangement The sweep line advances by a series of what are

called elementary steps In an elementary steps wendtwo consecutive edges on the cut that

meet at a vertex of the arrangementwe will discuss later how to determine this and push

the top ological sweep line through this vertex Observe that on doing so these two lines swap

in their order along the sweep line This is shown b elow

Figure Elementary step

It is not hard to show that an elementary step is always p ossible since for any cut other than

the rightmost cut there must b e two consecutive edges with a common right endp oint In

particular consider the edge of the cut whose rightendpoint has the smallest xco ordinate It

is not hard to show that this endp oint will always allow an elementary step Unfortunately

determining this vertex would require at least O log n time if we stored these endp oints in

a heap sorted by xco ordinate and wewant to p erform eachelementary step in O time

Hence we will need to nd some other metho d for nding elementary steps

Upp er and Lower Horizon Trees To nd elementary steps weintro duce two simple data struc

tures the upper horizon tree UHT and the lower horizon tree LHT To construct the upp er

horizon tree trace each edge of the cut to the right When two edges meet keep only the one

with the higher slop e and continue tracing it to the right The lower horizon tree is dened

symmetrically There is one little problem in these denitions in the sense that these trees

need not b e connected forming a forest of trees but this can b e xed conceptually at least by

the addition of a vertical line at x For the upp er horizon we think of its slop e as b eing

and for the lo wer horizon we think of its slop e as b eing Notethatwe consider the

left endp oints of the edges of the cut as not b elonging to the trees since otherwise they would

not b e trees It is not hard to show that with these mo dications these are indeed trees Each

edge of the cut denes exactly one line segmentineach tree An example is shown b elow

The imp ortant things ab out the UHT and LHT is that they giveusaneasyway to determine

Lecture Notes CMSC M

Upper Horizon Tree Lower Horizon Tree

Figure Upp er and lower horizon trees

the right endp oints of the edges on the cut Observe that for each edge in the cut its right

endp oint results from a line of smaller slop e intersecting it from ab oveaswe trace it from left

to right or from a line of larger slop e intersecting it from b elow It is easy to verify that the

UHT and LHT determine the rst suchintersecting line of eachtyp e resp ectively It follows

that if weintersect the two trees then the segments they share in common corresp ond exactly

to the edges of the cut Thus byknowing the UHT and LHT we know where are the right

endp oints are and from this we can determine easily which pairs of consecutive edges share

a common right endp oint and from this we can determine all the elementary steps that are

legal We store all the legal steps in a stack or queue or any list is ne and extract them

one by one

The sweep algorithm Here is an overview of the top ological plane sweep

Input the lines and sort by slop e Let C b e the initial leftmost cut a list of lines in

decreasing order of slop e

Create the initial UHT incrementally by inserting lines in decreasing order of slop e Create

the initial LHT incrementally by inserting line in increasing order of slop e More on this

later

By consulting the LHT and UHT determine the right endp oints of all the edges of the

initial cut and for all pairs of consecutive lines l l sharing a common right endp oint

i i

store this pair in stack S

Rep eat the following elementary step until the stack is empty implying that wehave

arrived at the rightmost cut

a Pop the pair l l from the top of the stack S

i i

b Swap these lines within C the cut we assume that each line keeps track of its p osition

in the cut

c Up date the horizon trees More on this later

d Consulting the changed entries in the horizon tree determine whether there are any

new cut edges sharing rightendpoints and if so push them on the stack S

The imp ortant unnished business is to showthatwe can build the initial UHT and LHT in

O n time and to show that for eachelementary step we can up date these trees and all other

relevant information in O amortizedtimeByamortized time we mean that even though

a single elementary step can take more than O time the total time needed to p erform all

O n elementary steps is O n and hence the average time for each step is O

Thisisdoneby an adaptation of the same incremental face walking technique weusedinthe

incremental construction of line arrangements Lets consider just the UHT since the LHT is

Lecture Notes CMSC M

symmetric To create the initial leftmost UHT we insert the lines one by one in decreasing

order of slop e Observe that as each new line is inserted it will start ab ove all of the current

lines The upp ermost face of the current UHT consists of a convex p olygonal chain see the

gure b elow left As we trace the newly inserted line from left to right there will b e some

p ointatwhich it rst hits this upp er chain of the current UHT By walking along the chain

from left to right we can determine this intersection p oint Eachsegment that is walked over

is never visited again by this initialization pro cess b ecause it is no longer part of the upp er

chain and since the initial UHT has a total of O n segments this implies that the total time

sp entinwalking is O n Thus after the O n log n time for sorting the segments the initial

UHT tree can b e built in O n additional time

new line vv

Initial UHT construction. Updating the UHT.

Figure Constructing and up dating the UHT

Next weshowhow to up date the UHT after an elementary step The pro cess is quite similar

as shown in the gure right Let v be the vertex of the arrangement which is passed over in

the sweep step As we pass over v thetwoedgesswap p ositions along the sweep line The new

lower edge call it l which had b een cut o of the UHT by the previous lower edge nowmust

b e reentered into the tree We extend l to the left until it contacts an edge of the UHT At its

rst contact it will terminate and this is the only change to b e made to the UHT In order

tondthiscontact we start with the edge immediately b elow l the current cut Wetraverse

the face of the UHT in counterclo ckwise order until nding the edge that this line intersects

Observethatwemust eventually nd such an edge b ecause l has a lower slop e than the other

edge intersecting at v and this edge lies in the same face

Analysis A careful analysis of the running time can b e p erformed using the same amortization

pro of based on p ebble counting that was used in the analysis of the incremental algorithm

We will not give the pro of in full detail Observe that b ecause wemaintain the set of legal

elementary steps in a stack as opp osed to a heap as would b e needed for standard plane sweep

tary step in O time The only part of the elementary we can advance to the next elemen

step that requires more than constant time is the up date op erations for the UHT and LHT

However we claim that the total time sp ent up dating these trees is O n The argument

is that when we are tracing the edges as shown in the previous gure we are essentially

traversing the edges in the zone for L in the arrangement This is not quite true b ecause

there are edges ab ove l in the arrangement whichhave b een cut out of the upp er tree but

the claim is that their absence cannot increase the complexity of this op eration only decrease

it However a careful pro of needs to takethisinto account Since the zone of each lineinthe

arrangement has complexity O n all n zones have total complexity O n Thus the total

time sp ent in up dating the UHT and LHT trees is O n

Lecture Notes CMSC M

Lecture X HamSandwich Cuts

Supplemental

Ham Sandwich Cuts of Linearly Separated Point Sets We are given n red p oints A and m

blue p oints B and wewant to compute a single line that simultaneously bisects b oth sets If

the cardinality of either set is o dd then the line passes through one of the p oints of the set

We make the simplifying assumption that the sets are separated by a line This assumption

makes the problem much simpler to solve but the general case can still b e solved in O n

time using arrangements

To make matters even simpler we assume that the p oints have b een translated and rotated

so this line is the y axis Thus all the red p oints set Ahave p ositive xco ordinates and

hence their dual lines have p ositive slop es whereas all the blue p oints set B have negative

xco ordinates and hence their dual lines have negative slop es As long as we are simplifying

things lets make one last simplication that b oth sets haveanoddnumberofpoints This

is not dicult to get around but makes the pictures a little easier to understand

Consider one of the sets say A Observe that for each slop e there exists one way to bisect the

p oin ts In particular if we start a line with this slop e at p ositive innity so that all the p oints

lie b eneath it and drop in downwards eventually we will arrive at a unique placement where

there are exactly n points ab ove the line one p oint lying on the line and n

p oints b elow the line assuming no two p oints share this slop e This line is called the median

line for this slop e

What is the dual of this median line If we dualize the p oints using the standard dual trans

formation D a b y ax bthenwegetn lines in the plane By starting a line with

a given slop e ab ovethepoints and translating it downwards in the dual plane wemoving a

p ointfrom upwards in a vertical line Each time the line passes a p oint in the primal

plane the vertically moving p oint crosses a line in the dual plane When the translating line

hits the median p oint in the dual plane the moving p oint will hit a dual line such that there

e are exactly n dual lines ab ove this p ointandn dual lines b elow this p oint W

dene a p ointtobeat level k L in an arrangement if there are at most k lines ab ove

k

this p oint and at most n k lines b elow this p oint The median level in an arrangementofn

lines is dened to b e the d n eth level in the arrangement This is shown as M Ain

the following gure on the left

M(B)

M(A) M(A) Ham sandwich point

Dual arrangement of A. Overlay of A and B’s median levels.

Figure Ham sandwich Dual formulation

Thus the set of bisecting lines for set A in dual form consists of a p olygonal curve Because

this curve is formed from edges of the dual lines in A and b ecause all lines in A have p ositive

slop e this curve is monotonically increasing Similarly the median for B M B is a p olygonal

curvewhich is monotonically decreasing It follows that A and B must intersect at a unique

p oint The dual of this p oint is a line that bisects b oth sets

Lecture Notes CMSC M

We could compute the intersection of these twocurves byasimultaneous top ological plane

sweep of b oth arrangements However it turns out that it is p ossible to do much b etter and in

fact the problem can b e solved in O n m time Since the algorithm is rather complicated I

will not describ e the details but here are the essential ideas The algorithm op erates by prune

and search In O n mtimewe will generate a hyp othesis for where the ham sandwichpoint

is in the dual plane and if we are wrong we will succeed in throwing away a constant fraction

of the lines from future consideration

First observe that for anyvertical line in the dual plane it is p ossible to determine in O n m

time whether this line lies to the left or the rightoftheintersection p oint of the median levels

M AandM B This can b e done by computing the intersection of the dual lines of A with

this line and computing their median in O n time and computing the intersection of the

dual lines of B with this line and computing their median in O m time If As median lies

below B s median then we are to the left of the ham sandwich dual p oint and otherwise we

are to the right of the ham sandwichdualpoint It turns out that with a little more work it

is p ossible to determine in O n m time whether the ham sandwichpoint lies to the right

or left of a line of arbitrary slop e The trick is to use prune and search Wendtwo lines L

and L in the dual plane by a careful pro cedure that I will not describ e These two lines

dene four quadrants in the plane By determining which side of each line the ham sandwich

p oint lies weknowthatwe can throwawayany line that do es not intersect this quadrant from

further consideration It turns out that by a judicious choice of L and L we can guarantee

that a fraction of at least n m lines can b e thrown awayby this pro cess We recurse

on the remaining lines By the same sort of analysis we made in the Kirkpatrick and Seidel

prune and search algorithm for upp er tangents it follows that in O n m time we will nd

the ham sandwichpoint