Application of convex hull algorithm--How many triangles are there in a number of graphs

Source: Internet
Author: User
Tags abs joins

First, the problem introduced

The problem of judging the number of graphs is often encountered on the network, as the following example:

If we are going to select all the triangles in the graph, how do we use the code to determine if the graph we selected is a triangle, given each intersection. For example, how to filter out Figure 3?

There are two steps to be used here:

1. Get the vertex collection of all the small shapes contained in the selected graph (shaded part), and find the convex hull of the set, and determine whether the convex-enclosed shape is a triangle based on the number of convex vertices, if the number of vertices is not 3, it is not a triangle, (1).

.2. If the convex shape is a triangle, determine whether the area of the convex hull is equal to the selected shape (the sum of all selected small plot areas), and if equal, the selected figure is a triangle, and if not equal, it is not a triangle, as in (2).

Second, the convex hull--graham ' s scan method to find the point is introduced

(1) What is a convex bag

In two-dimensional Euclidean space, a convex hull can be imagined as a rubber band that is just wrapped around all points.

In the case of non-rigorous words, given a set of points on a two-dimensional plane, a convex hull is a convex multilateral type that joins the outermost point together, and it can contain all points in a point set. such as the red part:

(2) Graham ' s scan method for convex hull

The algorithm was invented by the mathematical master Grihen (Graham), with the following ideas:

1. Find the lowest y coordinate point of all points, if the minimum y coordinate point has more than two, select the point where the x-coordinate is the smallest, the point is recorded as H;

2. Set the coordinates of all points except H to N{p1,p2,p3,p4,p5,p6,...}, calculate the angle of the vector < h,p1>,< h,p2>,< h,p3> Polar coordinates, and sort the set n by the angle of the polar coordinates, That is, at the center of H, the points are scanned clockwise, and the scanned points are added to the collection in turn, i.e., the ordered coordinate set is N{A1,A2,A3,A4,A5,A6}, where θ is the angle of the vector < h,a1> polar coordinates.

3. Segment < h,a1> must be on the convex hull, now add A2, assuming A2 is also on the convex hull, next add A3, if A3 on the left side of the vector <a1,a2> to judge A2 is not on the convex hull, you need to remove A2 from the convex hull, in this case A3 in the vector <a1, The right side of the a2>, and then joins A4, if A4 on the left side of the vector <a2,a3> to determine that A3 is not on the convex hull, in this case A4 on the left side of the vector <a2,a3>, so A3 from the convex hull to be removed, the next need to retrace A4 in the vector <a1, A2> to the left or right, decide if you want to remove A2 ..., that is, each time you add a point, you must consider whether the preceding segment is on the convex package. Starting from the base point, the direction of rotation of each segment adjacent to the convex hull should be the same as the direction of the scan. If new points are found to change the direction of rotation of the new line segment and the line segment, it is necessary to determine that the above point is not on the convex hull. Such as:

When the D point is added, the rotation direction of <c,d> and <b,c> is found to be inconsistent (d on <b,c> left), then the C point is not on the convex hull.

The cross product can be used to determine whether a point is on the left or right side of a vector, for example, if the cross product of <b,c> and <c,d> is regular d on the right side of <b,c>, if the negative is on the right side of <b,c>, if 0, in D at <b,c> The line.

Complexity of

This algorithm can operate directly on the original data, so the spatial complexity is o⑴. However, if the result of the convex hull is stored in another array, it may be optimized at the code level. Because sorting is done before the convex hull is scanned, the time complexity is at least the fast sort O (NLGN). The complexity of the subsequent scanning process is O (n), so the complexity of the entire algorithm is O (NLGN).

Third, the JavaScript code to solve the convex hull

Set array points is a collection of all the vertices that store the selected drawing

1 varConvexpoints=[];//used to store convex packets2 varStartpoint=getstartpoint (points);//get the point with the least Y coordinate3Points.splice (Points.indexof (startPoint), 1);4Points.sort (Compare);//Sort by polar coordinates5 Convexpoints.push (startPoint);6Convexpoints.push (points[0]);7     8  for(i=1;i<points.length;i++){9    varvector1={x:convexpoints[convexpoints.length-1].x-convexpoints[convexpoints.length-2].x,TenY:convexpoints[convexpoints.length-1].y-convexpoints[convexpoints.length-2].y}; One                          A    varvector2={x:points[i].x-convexpoints[convexpoints.length-1].x, -Y:points[i].y-convexpoints[convexpoints.length-1].y}; -If the two vector cross product is less than 0, you need to remove the previous point the     while(Getcross (Vector1,vector2) <0){ - Convexpoints.pop (); -vector1={x:convexpoints[convexpoints.length-1].x-convexpoints[convexpoints.length-2].x, -Y:convexpoints[convexpoints.length-1].y-convexpoints[convexpoints.length-2].y}; +vector2={x:points[i].x-convexpoints[convexpoints.length-1].x, -Y:points[i].y-convexpoints[convexpoints.length-1].y}; +    } A Convexpoints.push (Points[i]); at}

Points the point with the lowest Y coordinate in the set, and the Y coordinate in the same case, take the point with the smallest x coordinate.

1 //Select the smallest point of the y-axis startpoint2 functionGetStartPoint (points) {3     varStartpoint=points[0];4      for(vari=1;i<points.length;i++){5         if(points[i].y<Startpoint.y) {6Startpoint=Points[i];7}Else if(points[i].y==Startpoint.y) {8             if(points[i].x<startpoint.x) {9Startpoint=Points[i];Ten             } One         } A     } -     returnStartPoint -}

Compare functions sorted by polar coordinate angle

1 //sorts points by polar coordinate angle2 functionCompare (value1,value2) {3     varvalue1angle=Getpolarangle (startpoint,value1);4     varvalue2angle=Getpolarangle (startpoint,value2);5     if(value1angle<value2angle) {6         return-1;7}Else if(value1angle>value2angle) {8         return1;9}Else{Ten         return0; One     } A}

Use this convex hull to determine if the selected shape is a triangle:

As shown, we want to get the {a,b,c} three points for the convex hull of the points contained in the Shadow section, so that we can know the shape of the convex hull by judging the size of the convex hull, and in fact the convex hull which we obtained through the above algorithm may contain d,e,f, whether it contains the sampling precision which depends on the d,e,f coordinates. So how do you remove these points from the convex hull?

Delete a point in the middle of a segment of two vertices in a convex hull: for example, when the sample coordinates of a point in the middle of a segment are concave to the inside of the graph, it is excluded by the convex hull algorithm (such as the D point), and when the sampling coordinates are convex, it is computed by the convex hull algorithm (such as E,f points) <E,B> the angle of the vector, when the angle is less than a certain range (depending on the estimation of the sampling error), we can determine the e point on AB, you can remove the e point from the convex hull. This method sequentially detects all the points in the convex hull, and finally gets the vertices of the graph we selected.

The code is as follows:

1//remove a point in the middle of a line, leaving a vertex2 Convexpoints.push (StartPoint);//to determine the last point of the convex hull, you need to add the starting point to the end to form a ring3 deletepointindexs=[];//index of the point to store for deletion4 for(i=0;i<convexpoints.length-2;i++){ 5varvector1={x:convexpoints[i+1].x-convexpoints[i].x,y:convexpoints[i+1].y-Convexpoints[i].y}6varVector2={x:convexpoints[i+2].x-convexpoints[i+1].x,y:convexpoints[i+2].y-convexpoints[i+1].y}7varangle=Getangle (VECTOR1,VECTOR2);8if(Math.Abs (angle) <math.pi/90) {//Error range set to 2 degrees 9 Deletepointindexs.push (i+1);10     };11 }12if(deletepointindexs.length>0){13 for(i=deletepointindexs.length-1;i>=0;i--){Convexpoints.splice (deletepointindexs[i],1);15     }16 }Convexpoints.pop ();//remove the starting point
When the length of the convexpoints is 3 o'clock, we can determine that the convex hull is surrounded by a triangular shape.

Iv. determining selected shape shapes by comparison of area

When our chosen shape is shaped, it is judged by the convex hull above that it is a triangle (the red part) and not actually. In this case, we can finally determine the shape by comparing the area of the selected graph (the shaded portion) with the area of the graph formed by the convex hull.

In the case where each vertex of a polygon is known, it can be computed by decomposing the polygon into multiple triangles, such as. The triangular area can be obtained by the cross product of two-side vectors;

Calculate polygon area code as follows

1 //The graph area is calculated according to the coordinates of each vertex, and the idea is that the polygon is decomposed into multiple triangles, and the triangular area is computed by cross product2 functionGetpolygonarea (pointdata) {3     varArea=0;4     varStartpoint=pointdata[0];5      for(vari=1;i<pointdata.length-1;i++){6         varvector1={x:pointdata[i].x-startpoint.x,y:pointdata[i].y-Startpoint.y};7         varvector2={x:pointdata[i+1].x-pointdata[i].x,y:pointdata[i+1].y-pointdata[i].y};8Area+=math.abs (Getcross (Vector1,vector2))/2;9     }Ten     returnArea ; One}

V. Let the program automatically select all triangles

We can traverse the graphics of the small and medium-sized graphics of various possible permutations, through the above-mentioned way to calculate whether each combination is a triangle, so that the program helps us determine how many triangles the graph, and generate each kind of triangle, the concrete implementation will not repeat.

Note : Some of the tools used to calculate geometry

1 //to get the angle of the vector polar coordinates, p1 and P2 are the starting and ending points of the vectors.2 functionGetpolarangle (p1,p2) {3     returnMath.atan2 (p2.y-p1.y,p2.x-p1.x);4 }5 6 //find the cross product of two vectors7 functionGetcross (vector1,vector2) {8     returnvector1.x*vector2.y-vector2.x*vector1.y;9 }Ten  One //find the angle of two vectors A functionGetangle (vector1,vector2) { -     returnMath.acos (Getdot (VECTOR1,VECTOR2)/(Getlengthofvector (Vector1) *getlengthofvector (Vector2))); - } the  - //to find the length of a vector - functionGetlengthofvector (vector) { -     returnMATH.SQRT (vector.x*vector.x+vector.y*vector.y); + } -  + //Find the dot product of two vectors A functionGetdot (vector1,vector2) { at     returnvector1.x*vector2.x+vector1.y*vector2.y; -}


Application of convex hull algorithm--How many triangles are there in a number of graphs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.