算法-矩形包含

题目

把矩形的层级包含关系表示出来即可。

比如上面的图表示为一个 div 下有两个 div。

数据

r1 = [
  { id: 1, x1: 533, y1: 30, x2: 860, y2: 409 },
  { id: 2, x1: 559, y1: 49, x2: 837, y2: 207 },
  { id: 3, x1: 568, y1: 236, x2: 832, y2: 364 },
]

xy 是坐标信息,层级关系可根据此内容计算。

要处理成的数据

r2 = [
  {
    id: 1, x1: 533, y1: 30, x2: 860, y2: 409,
    child: [
      { pid: 1, id: 2, x1: 559, y1: 49, x2: 837, y2: 207, },
      { pid: 1, id: 3, x1: 568, y1: 236, x2: 832, y2: 364, },
    ],
  },
]

  function checkInclude(data1, data2) {
    return data2.x1 > data1.x1 && data2.y1 > data1.y1 &&
      data2.x2 < data1.x2 && data2.y2 < data1.y2
  }

  function dep(arr, data) {
    for (let i = 0; i < arr.length; i++) {
      // 在容器内
      if (checkInclude(arr[i], data)) {
        // 有子容器,进一步判断
        if (arr[i].child) {
          dep(arr[i].child, data, arr)
          return
        } else {
          // 如果当前容器没有子容器
          arr[i].child = [
            {
              ...data,
              pid: arr[i].id
            }
          ]
          return
        }
      }
    }
    arr.push(data)
  }

  function rectangleContains(data_) {
  // 先进行排序,后续根据循序处理
    const data = data_.sort((item1, item2) => item1.x1 - item2.x1)
    const result = []
    for (let i = 0; i < data.length; i++) {
      dep(result, data[i])
    }
    return result
  }
  var r1 = [
    {id: 1, x1: 10, y1: 10, x2: 20, y2: 20},
    {id: 2, x1: 11, y1: 11, x2: 19, y2: 19},
    {id: 4, x1: 12, y1: 12, x2: 18, y2: 18},
    {id: 5, x1: 11, y1: 11, x2: 18, y2: 18},
    {id: 6, x1: 20, y1: 20, x2: 18, y2: 18},
    {id: 7, x1: 533, y1: 30, x2: 860, y2: 409},
    {id: 8, x1: 559, y1: 49, x2: 837, y2: 207},
    {id: 9, x1: 568, y1: 236, x2: 832, y2: 364},
  ]
  console.log(rectangleContains(r1))
[
  {
    "id": 1, "x1": 10, "y1": 10, "x2": 20, "y2": 20,
    "child": [
      {
        "id": 2, "x1": 11, "y1": 11, "x2": 19, "y2": 19, "pid": 1,
        "child": [
          {
            "id": 4, "x1": 12, "y1": 12, "x2": 18, "y2": 18, "pid": 2
          },
          {
            "id": 6, "x1": 20, "y1": 20, "x2": 18, "y2": 18
          }
        ]
      },
      {
        "id": 5, "x1": 11, "y1": 11, "x2": 18, "y2": 18
      }
    ]
  },
  {
    "id": 7, "x1": 533, "y1": 30, "x2": 860, "y2": 409,
    "child": [
      {
        "id": 8, "x1": 559, "y1": 49, "x2": 837, "y2": 207, "pid": 7
      },
      {
        "id": 9, "x1": 568, "y1": 236, "x2": 832, "y2": 364
      }
    ]
  }
]

扁平转树的需求层出不穷,但解法都类似,循环|循环+递归…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值