用图表循环计算最大距离

时间:2018-06-25 17:26:12

标签: javascript jquery tree binary-tree

我有一个带有元素的图表。这些元素具有ID并与其他元素连接。

连接对象采用两个参数,第一个元素的ID和第二个元素。

每个元素都可以连接到任何其他元素!可能会出现周期。

diagramm

如您所见,最短的距离是从上到下。但是我需要最大距离。较长的路径会沿着正确的路径移动。

如右图所示,元素之间存在一个循环,因此算法会陷入无限循环。

有没有一种方法可以计算从起始元素1开始的最大深度?

我试图创建一个算法,但是我不认为这会返回正确的结果。

function Element(id) {
  this.id = id;
}

function Connection(startElementId, targetElementId) {
  this.startElementId = startElementId;
  this.targetElementId = targetElementId;
}

const elements = [
  new Element(1),
  new Element(2),
  new Element(3),
  new Element(4),
  new Element(5),
  new Element(6),
  new Element(7),
  new Element(8),
  new Element(9),
  new Element(10)
];

const connections = [
  new Connection(7, 5),
  new Connection(9, 2),
  new Connection(4, 6),
  new Connection(3, 6),
  new Connection(8, 2),
  new Connection(1, 8),
  new Connection(7, 9),
  new Connection(2, 5),
  new Connection(4, 7),
  new Connection(9, 6),
  new Connection(3, 4),
  new Connection(1, 7),
  new Connection(5, 3),
  new Connection(9, 4)
];

$(document).ready(() => {
  elements.forEach(ele => {
    let maxDepth = 0;
    connections.forEach(con => {
      const startId = con.startElementId;

      if (ele.id == startId) {
        const currentDepth = Math.abs(startId - con.targetElementId);

        if (maxDepth < currentDepth) {
          maxDepth = currentDepth;
        }
      }
    });

    console.log(maxDepth); // RESULT HERE
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0 个答案:

没有答案