• 矩形并积


        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;
            }
        }
    

    留个记录,求平面内多个矩形的并积,返回面积。

    第一次 思路 想以两两运算,发现走不通。

    第二次 参考网友思路,分成小块来运算。

  • 相关阅读:
    Spring1()
    常用的比较器:实现方式Compareable和Comparator
    数据结构 2(数据结构 逻辑关系 存储关系 数据类型 抽象数据类型)
    面试题目
    数据结构(1术语)
    第一次作业-四则运算题目生成程序
    第二次 作业——APP案例分析
    面试题
    字符串转换时间的方法
    安卓获取手机内存,SD卡内存使用状态的方法
  • 原文地址:https://www.cnblogs.com/gw2010/p/3374286.html
Copyright © 2020-2023  润新知