Time complexity of algorithm

Hi guys,

I'm trying to find the number of integer points lying on or inside a given triangle (which may have non-integer vertices). My algorithm sums the areas of the triangle formed by a given point and two vertices of the triangle, and then compares the sum with the area of the given triangle. (These will be equal only if the point lies on or inside the triangle)

How do I go about finding the time complexity of this solution?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#define max(a,b,c) a > b ? (a > c ? a : c) : (b > c ? b : c)
#define min(a,b,c) a < b ? (a < c ? a : c) : (b < c ? b : c)

using namespace std;


void input(float &x1, float &y1, float &x2, float &y2, float &x3, float &y3)
{
	cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
}

float area(float x1, float y1, float x2, float y2, float x3, float y3)
{
	return abs(x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2));
}

int main()
{
	float x1, y1, x2, y2, x3, y3, min_x, max_x, min_y, max_y;
	int i, j, d_count = 0;

	input(x1, y1, x2, y2, x3, y3);

	float A_tri = area(x1, y1, x2, y2, x3, y3);

	// Enclosing rectangle
	min_x = floor(min(x1, x2, x3));
	max_x = ceil(max(x1, x2, x3));
	min_y = floor(min(y1, y2, y3));
	max_y = ceil(max(y1, y2, y3));

	for (i = min_x; i <= max_x; ++i)
		for (j = min_y; j <= max_y; ++j)
			if (area(i, j, x1, y1, x2, y2) + area(i, j, x2, y2, x3, y3) + area(i, j, x1, y1, x3, y3) == A_tri)
			{
				cout << "(" << i << "," << j << ")" << " ";
				++d_count;
			}
	
	cout << "\n" << A_tri << "\n";
	cout << "Total number of diamonds: " << d_count << "\n";
	system("pause");
	return(0);
}
The time complexity is quadratic linear over the area of the triangle, since you iterate once per square unit of the bounding axis-aligned rectangle of the polygon.
Last edited on
Ahh, thank you :)
Topic archived. No new replies allowed.