class Program
{
static void Main(string[] args)
{
int rectCount =2;
IList<Rectangle> rects = new List<Rectangle>();
rects.Add(new Rectangle(0, 0, 2, 2));
rects.Add(new Rectangle(1, 1, 3, 3));
//rects.Add(new Rectangle(2, 2, 4, 4));
UnionRect(rectCount, rects);
Console.Read();
}
static void UnionRect(int ct, IList<Rectangle> rects)
{
List<int> x = new List<int>();
List<int> y = new List<int>();
foreach (Rectangle r in rects)
{
x.Add(r.X1);
x.Add(r.X2);
y.Add(r.Y1);
y.Add(r.Y2);
}
x.Sort();
y.Sort();
int s = 0;
for (int i = 1; i <= ct * 2 - 1; i++)
{
for (int j = 1; j <= ct * 2 - 1; j++)
{
Rectangle r = new Rectangle(x[i - 1], y[j - 1], x[i], y[j]);
foreach (Rectangle re in rects)
{
if (re.Contain(r))
{
s += r.Squre();
break;
}
}
}
}
Console.WriteLine("面积:{0}", s);
}
}
public class Rectangle
{
public int X1 { get; set; }
public int X2 { get; set; }
public int Y1 { get; set; }
public int Y2 { get; set; }
public Rectangle(int x1, int y1, int x2, int y2)
{
X1 = x1;
X2 = x2;
Y1 = y1;
Y2 = y2;
}
//面积
public int Squre()
{
return (X2 - X1) * (Y2 - Y1);
}
//是否包含矩形
public bool Contain(Rectangle smallRect)
{
return smallRect.X1 >= this.X1 && smallRect.X2 <= this.X2 && smallRect.Y1 >= this.Y1 && smallRect.Y2 <= this.Y2;
}
}
留个记录,求平面内多个矩形的并积,返回面积。
第一次 思路 想以两两运算,发现走不通。
第二次 参考网友思路,分成小块来运算。