javascript - 在图中找到具有最小值的节点
问题描述
有一个图,由对象表示的节点:
Node = {
value: <number>,
children: [Node, Node ... Node]
}
我需要找到具有最小值字段的节点。
我找到了图表的最小值,但不知道如何返回节点。
const min = (graph) => !graph.children ? graph.value :
Math.min(graph.value, ...graph.children.map(min));
图表示例:
{value:31,children:[{value:68},{value:10,children:[{value:100,children:[{value:21,children:[{value:21},{value:64}]},{value:86}]}]}]}
答案示例:
{value:10,children:[{value:100,children:[{value:21,children:[{value:21},{value:64}]},{value:86}]}]}
解决方案
作为可能的解决方案,我建议:
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];
}
此解决方案适用于有限图,否则您应该更改结构以更有效地处理大图。
推荐阅读
- javascript - 如何在节点 js 中检查文本框 id 是否为空
- azure-machine-learning-service - 如何从本地部署的 AzureML 容器中公开端口?
- reactjs - 如果它在对象内部,如何更新 redux reducer 中的值
- javascript - React-select {creatable} 与用户输入的条目一起工作,因为只显示没有选项
- firebase - 是否可以将通配符与斜杠之间的其他文本或通配符组合为 Firestore 规则中 get() 或 exists() 路径的一部分?
- json - Powershell - 大括号内大括号的 JSON 语法
- php - 我如何检索发布帖子的用户
- angular - 延迟加载模块子级的角度路由问题
- powershell - 有没有办法检查当前的 Powershell 脚本是否正在通过 WinRM/PS Remoting 会话执行?
- javascript - Lodash 或将两个对象数组与匹配键组合的最佳方法