【问题标题】:Performant way to convert adjacency list to links for undirected graph将邻接表转换为无向图链接的高效方法
【发布时间】:2017-03-29 12:25:50
【问题描述】:

我有一个如下的邻接列表:

const list = [
 [1, 6, 8],
 [0, 4, 6, 9],
 [4, 6],
 [4, 5, 8],
 // ...
];

我需要为无重复的无向图创建一组链接(示例如下)。 [0,1] 和 [1,0] 等链接被视为重复链接。

const links = [
 [ 0, 1 ], // duplicates
 [ 0, 6 ],
 [ 0, 8 ],
 [ 1, 0 ], // duplicates
 [ 1, 4 ],
 // ...
]

现在我是这样做的:

const links = new Set;
const skip = [];

list.forEach( (v, i) => {
    v.forEach( j => {
        if (skip.indexOf(j) === -1) {
            links.add([i, j]);
        }
    })
    skip.push(i);
})

我想知道是否有更好的模式来解决大规模数组上的此类任务。

【问题讨论】:

    标签: javascript data-structures graph


    【解决方案1】:

    您可以对链接元组值进行排序,跳过检查 skip.indexOf(j) 并让 Set 处理重复项。

    【讨论】:

      【解决方案2】:

      您可以将字符串数组作为集合的值,因为只有排序值的数组在集合中使用严格模式进行检查。

      像字符串这样的原始数据类型效果最好。

      var list = [[1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8]],
          links = new Set;
      
      list.forEach((v, i) => v.forEach(j => links.add([Math.min(i, j), Math.max(i, j)].join())));
         
      console.log([...links]);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案3】:

        您可以使用一个对象来存储已使用的value: index,然后在添加到数组之前检查该对象。

        const list = [[1, 6, 8],[0, 4, 6, 9],[4, 6],[4, 5, 8],];
        var o = {},r = []
        
        list.forEach(function(e, i) {
          e.forEach(function(a) {
            if (o[i] != a) {
              r.push([i, a])
              o[a] = i
            }
          })
        })
        
        console.log(JSON.stringify(r))

        使用 ES6 箭头函数,你可以这样写。

        const list = [[1, 6, 8], [0, 4, 6, 9], [4, 6], [4, 5, 8],];
        var o = {}, r = []
        
        list.forEach((e, i) => e.forEach(a => o[i] != a ? (r.push([i, a]), o[a] = i) : null))
        console.log(JSON.stringify(r))

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-18
          • 1970-01-01
          • 1970-01-01
          • 2018-07-14
          相关资源
          最近更新 更多