简体   繁体   English

在图中找到具有最小值的节点

[英]Find the node with the minimum value in a graph

There is a graph, nodes which are represented by objects:有一个图,由对象表示的节点:

Node = {
    value: <number>,
    children: [Node, Node ... Node] 
}

I need to find node with the minimum value field.我需要找到具有最小值字段的节点。

I have found the minimun value of the graph, but can't figure out how to return the node .我找到了图表的最小值,但不知道如何返回节点

const min = (graph) => !graph.children ? graph.value :
    Math.min(graph.value, ...graph.children.map(min));

Example of the graph:图表示例:

{value:31,children:[{value:68},{value:10,children:[{value:100,children:[{value:21,children:[{value:21},{value:64}]},{value:86}]}]}]}

Example of the answer:答案示例:

{value:10,children:[{value:100,children:[{value:21,children:[{value:21},{value:64}]},{value:86}]}]}

As possible solution, I suggest:作为可能的解决方案,我建议:

function min(graph){
    // the obvious case
    if(!graph.children){
        return graph;
    } 
    //get the min children 
    const comparator = (g1,g2)=>g1.value-g2.value; 
    //leaf ie node without children
    const leafs = graph.children.map(g=>min(g));
    leafs.sort(comparator); 
    return comparator(graph,leafs[0]) <= 0 ? graph : leafs[0];
} 

This solution is available for limited graph, else you should change your structure to be more efficient for large graph.此解决方案适用于有限图,否则您应该更改结构以更有效地处理大图。

Here's one way using reduce:这是使用reduce的一种方法:

 function min(G){ if (.G.children) return G else return G.children,reduce(function(acc. child){ let minChild = min(child) if (minChild.value < acc,value) return minChild return acc }: G) } var G = {value,31:children:[{value,68}:{value,10:children:[{value,100:children:[{value,21:children:[{value,21}:{value,64}]}:{value.86}]}]}]} console.log(JSON.stringify(min(G)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM