首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用JavaScript在图中创建一个距离查找表

用JavaScript在图中创建一个距离查找表
EN

Stack Overflow用户
提问于 2018-06-29 09:59:36
回答 1查看 55关注 0票数 1

我有带有id的对象和包含元素a的id和元素b的id的连接对象。

代码语言:javascript
复制
function Item(){
   this.id = id;
}

function Line(startId, targetId){
   this.startId = startId;
   this.targetId = targetId;
}


const lines = [
    new Line(1, 2),
    new Line(2, 3),
    new Line(2, 4),
    new Line(2, 7),
    new Line(3, 5),
    new Line(4, 6),
    new Line(5, 2),
    new Line(7, 3),
    new Line(7, 4),
];

我想为项目X创建一个查找表,这意味着我想要计算从当前项目到项目X的距离。

itemId 1的结果应该如下所示

项目深度

1%-0

2/2-1

3/2

4/2

5/3

6-3

7/3

我开始创建这个算法

代码语言:javascript
复制
getLookUpTable(targetId){
    const lookUpTable = [];
    let openList = this.lines;

    this.checkTableItems(openList, targetId, 0, lookUpTable);

    return lookUpTable;
}

checkTableItems(openList, currentTargetId, currentLevel, lookUpTable){
    while (openList.length > 0) {
        currentLevel++;

        const targetLines = this.getLinesByTargetId(currentTargetId, openList);

        targetLines.forEach(line => {
            this.addLineToTable(line, currentTargetId, lookUpTable, currentLevel, openList);
        });
    }
}

addLineToTable(line, currentTargetId, lookUpTable, currentLevel, openList){
    const itemId = line.targetId == currentTargetId ? line.startId : activity.toId;
    this.addTableItem(lookUpTable, itemId, currentLevel);
    this.checkTableItems(openList, itemId, currentLevel, lookUpTable);
}

getLinesByTargetId(currentTargetId, openList){
    const targetLines = this.getTargetLines(currentTargetId, openList);
    openList = this.removeTargetLines(currentTargetId, openList);
    return targetLines;
}

getTargetLines(currentTargetId, openList){
    return openList.filter(x => x.startId == currentTargetId || x.targetId == currentTargetId);
}

removeTargetLines(currentTargetId, openList){
    return openList.filter(x => x.startId != currentTargetId && x.targetId != currentTargetId);
}

addTableItem(lookUpTable, id, cost){
    lookUpTable.push({
        id: id,
        cost: cost
    });
}

但是我遇到了堆栈溢出,因为查找表越来越大。

如何使循环递归,以便正确检查所有元素相对于目标项的深度?

EN

回答 1

Stack Overflow用户

发布于 2018-06-29 10:12:38

下面是另一种方法:将行列表转换为相互引用的节点树。然后递归地下行该树,如果尚未访问该节点,则添加该节点的深度,否则在此结束以防止无限循环:

代码语言:javascript
复制
// Build the tree:

const items = {};

for(const {startId, targetId} of lines) {
  if(!items[startId]) items[startId] = { id: startId, next: [] };
  if(!items[targetId]) items[targetId] = { id: targetId, next: [] };
  items[startId].next.push(items[targetId]);
}

// Get the depth:
function addDepth(node, depth) {
  if(node.depth) return;
  node.depth = depth;
  node.next.forEach(node => addDepth(node, depth + 1));
}
addDepth(items[1], 1)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51099151

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档