gojs实现最短路径寻址实例

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

JS

  function init() {if (window.goSamples) goSamples();  // init for these samples -- you don't need to call thisvar $ = go.GraphObject.make;  // for conciseness in defining templatesmyDiagram =$(go.Diagram, "myDiagramDiv", // must be the ID or reference to div{initialAutoScale: go.Diagram.UniformToFill,padding: 10,contentAlignment: go.Spot.Center,layout: $(go.ForceDirectedLayout, { defaultSpringLength: 10 }),maxSelectionCount: 2});// define the Node templatemyDiagram.nodeTemplate =$(go.Node, "Horizontal",{ locationSpot: go.Spot.Center,  // Node.location is the center of the ShapelocationObjectName: "SHAPE",selectionAdorned: false,selectionChanged: nodeSelectionChanged },$(go.Panel, "Auto",$(go.Shape, "Ellipse",{ name: "SHAPE",fill: "lightgray",  // default value, but also data-boundstroke: "transparent",  // modified by highlightingstrokeWidth: 2,desiredSize: new go.Size(30, 30),portId: "" },  // so links will go to the shape, not the whole nodenew go.Binding("fill", "isSelected", function(s, obj) { return s ? "red" : obj.part.data.color; }).ofObject()),$(go.TextBlock,new go.Binding("text", "distance", function(d) { if (d === Infinity) return "INF"; else return d | 0; }))),$(go.TextBlock,new go.Binding("text")));// define the Link templatemyDiagram.linkTemplate =$(go.Link,{selectable: false,      // links cannot be selected by the usercurve: go.Link.Bezier,layerName: "Background"  // don't cross in front of any nodes},$(go.Shape,  // this shape only shows when it isHighlighted{ isPanelMain: true, stroke: null, strokeWidth: 5 },new go.Binding("stroke", "isHighlighted", function(h) { return h ? "red" : null; }).ofObject()),$(go.Shape,// mark each Shape to get the link geometry with isPanelMain: true{ isPanelMain: true, stroke: "black", strokeWidth: 1 },new go.Binding("stroke", "color")),$(go.Shape, { toArrow: "Standard" }));// Override the clickSelectingTool's standardMouseSelect// If less than 2 nodes are selected, always add to the selectionmyDiagram.toolManager.clickSelectingTool.standardMouseSelect = function() {var diagram = this.diagram;if (diagram === null || !diagram.allowSelect) return;var e = diagram.lastInput;var count = diagram.selection.count;var curobj = diagram.findPartAt(e.documentPoint, false);if (curobj !== null) {if (count < 2) {  // add the part to the selectionif (!curobj.isSelected) {var part = curobj;if (part !== null) part.isSelected = true;}} else {if (!curobj.isSelected) {var part = curobj;if (part !== null) diagram.select(part);}}} else if (e.left && !(e.control || e.meta) && !e.shift) {// left click on background with no modifier: clear selectiondiagram.clearSelection();}}generateGraph();// select two nodes that connect from the first one to the second onevar num = myDiagram.model.nodeDataArray.length;var node1 = null;var node2 = null;for (var i = 0; i < num; i++) {node1 = myDiagram.findNodeForKey(i);var distances = findDistances(node1);for (var j = 0; j < num; j++) {node2 = myDiagram.findNodeForKey(j);var dist = distances.getValue(node2);if (dist > 1 && dist < Infinity) {node1.isSelected = true;node2.isSelected = true;break;}}if (myDiagram.selection.count > 0) break;}}function generateGraph() {var names = ["Joshua", "Kathryn", "Robert", "Jason", "Scott", "Betsy", "John","Walter", "Gabriel", "Simon", "Emily", "Tina", "Elena", "Samuel","Jacob", "Michael", "Juliana", "Natalie", "Grace", "Ashley", "Dylan"];var nodeDataArray = [];for (var i = 0; i < names.length; i++) {nodeDataArray.push({ key: i, text: names[i], color: go.Brush.randomColor(128, 240) });}var linkDataArray = [];var num = nodeDataArray.length;for (var i = 0; i < num * 2; i++) {var a = Math.floor(Math.random() * num);var b = Math.floor(Math.random() * num / 4) + 1;linkDataArray.push({ from: a, to: (a + b) % num, color: go.Brush.randomColor(0, 127) });}myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);}// There are three bits of functionality here:// 1: findDistances(Node) computes the distance of each Node from the given Node.//    This function is used by showDistances to update the model data.// 2: findShortestPath(Node, Node) finds a shortest path from one Node to another.//    This uses findDistances.  This is used by highlightShortestPath.// 3: collectAllPaths(Node, Node) produces a collection of all paths from one Node to another.//    This is used by listAllPaths.  The result is remembered in a global variable//    which is used by highlightSelectedPath.  This does not depend on findDistances.// Returns a Map of Nodes with distance values from the given source Node.// Assumes all links are unidirectional.function findDistances(source) {var diagram = source.diagram;// keep track of distances from the source nodevar distances = new go.Map(go.Node, "number");// all nodes start with distance Infinityvar nit = diagram.nodes;while (nit.next()) {var n = nit.value;distances.add(n, Infinity);}// the source node starts with distance 0distances.add(source, 0);// keep track of nodes for which we have set a non-Infinity distance,// but which we have not yet finished examiningvar seen = new go.Set(go.Node);seen.add(source);// keep track of nodes we have finished examining;// this avoids unnecessary traversals and helps keep the SEEN collection smallvar finished = new go.Set(go.Node);while (seen.count > 0) {// look at the unfinished node with the shortest distance so farvar least = leastNode(seen, distances);var leastdist = distances.getValue(least);// by the end of this loop we will have finished examining this LEAST nodeseen.remove(least);finished.add(least);// look at all Links connected with this nodevar it = least.findLinksOutOf();while (it.next()) {var link = it.value;var neighbor = link.getOtherNode(least);// skip nodes that we have finishedif (finished.contains(neighbor)) continue;var neighbordist = distances.getValue(neighbor);// assume "distance" along a link is unitary, but could be any non-negative number.var dist = leastdist + 1;  //Math.sqrt(least.location.distanceSquaredPoint(neighbor.location));if (dist < neighbordist) {// if haven't seen that node before, add it to the SEEN collectionif (neighbordist === Infinity) {seen.add(neighbor);}// record the new best distance so far to that nodedistances.add(neighbor, dist);}}}return distances;}// This helper function finds a Node in the given collection that has the smallest distance.function leastNode(coll, distances) {var bestdist = Infinity;var bestnode = null;var it = coll.iterator;while (it.next()) {var n = it.value;var dist = distances.getValue(n);if (dist < bestdist) {bestdist = dist;bestnode = n;}}return bestnode;}// Find a path that is shortest from the BEGIN node to the END node.// (There might be more than one, and there might be none.)function findShortestPath(begin, end) {// compute and remember the distance of each node from the BEGIN nodedistances = findDistances(begin);// now find a path from END to BEGIN, always choosing the adjacent Node with the lowest distancevar path = new go.List();path.add(end);while (end !== null) {var next = leastNode(end.findNodesInto(), distances);if (next !== null) {if (distances.getValue(next) < distances.getValue(end)) {path.add(next);  // making progress towards the beginning} else {next = null;  // nothing better found -- stop looking}}end = next;}// reverse the list to start at the node closest to BEGIN that is on the path to END// NOTE: if there's no path from BEGIN to END, the first node won't be BEGIN!path.reverse();return path;}// Recursively walk the graph starting from the BEGIN node;// when reaching the END node remember the list of nodes along the current path.// Finally return the collection of paths, which may be empty.// This assumes all links are unidirectional.function collectAllPaths(begin, end) {var stack = new go.List(go.Node);var coll = new go.List(go.List);function find(source, end) {source.findNodesOutOf().each(function(n) {if (n === source) return;  // ignore reflexive linksif (n === end) {  // successvar path = stack.copy();path.add(end);  // finish the path at the end nodecoll.add(path);  // remember the whole path} else if (!stack.contains(n)) {  // inefficient way to check having visitedstack.add(n);  // remember that we've been here for this path (but not forever)find(n, end);stack.removeAt(stack.count - 1);}  // else might be a cycle});}stack.add(begin);  // start the path at the begin nodefind(begin, end);return coll;}// Return a string representation of a path for humans to read.function pathToString(path) {var s = path.length + ": ";for (var i = 0; i < path.length; i++) {if (i > 0) s += " -- ";s += path.elt(i).data.text;}return s;}// When a node is selected show distances from the first selected node.// When a second node is selected, highlight the shortest path between two selected nodes.// If a node is deselected, clear all highlights.function nodeSelectionChanged(node) {var diagram = node.diagram;if (diagram === null) return;diagram.clearHighlighteds();if (node.isSelected) {// when there is a selection made, always clear out the list of all pathsvar sel = document.getElementById("myPaths");sel.innerHTML = "";// show the distance for each node from the selected nodevar begin = diagram.selection.first();showDistances(begin);if (diagram.selection.count === 2) {var end = node;  // just became selected// highlight the shortest pathhighlightShortestPath(begin, end);// list all pathslistAllPaths(begin, end);}}}// Have each node show how far it is from the BEGIN node.function showDistances(begin) {// compute and remember the distance of each node from the BEGIN nodedistances = findDistances(begin);// show the distance on each nodevar it = distances.iterator;while (it.next()) {var n = it.key;var dist = it.value;myDiagram.model.setDataProperty(n.data, "distance", dist);}}// Highlight links along one of the shortest paths between the BEGIN and the END nodes.// Assume links are unidirectional.function highlightShortestPath(begin, end) {highlightPath(findShortestPath(begin, end));}// List all paths from BEGIN to ENDfunction listAllPaths(begin, end) {// compute and remember all paths from BEGIN to END: Lists of Nodespaths = collectAllPaths(begin, end);// update the Selection element with a bunch of Option elements, one per pathvar sel = document.getElementById("myPaths");sel.innerHTML = "";  // clear out any old Option elementspaths.each(function(p) {var opt = document.createElement("option");opt.text = pathToString(p);sel.add(opt, null);});sel.onchange = highlightSelectedPath;}// A collection of all of the paths between a pair of nodes, a List of Lists of Nodesvar paths = null;// This is only used for listing all paths for the selection onchange event.// When the selected item changes in the Selection element,// highlight the corresponding path of nodes.function highlightSelectedPath() {var sel = document.getElementById("myPaths");var idx = sel.selectedIndex;var opt = sel.options[idx];var val = opt.value;highlightPath(paths.elt(sel.selectedIndex));}// Highlight a particular path, a List of Nodes.function highlightPath(path) {myDiagram.clearHighlighteds();for (var i = 0; i < path.count - 1; i++) {var f = path.elt(i);var t = path.elt(i + 1);f.findLinksTo(t).each(function(l) { l.isHighlighted = true; });}}

HTML

<div id="sample"><div id="myDiagramDiv" style="border: solid 1px black; background: white; width: 100%; height: 700px"></div>Click on a node to show distances from that node to each other node.Click on a second node to show a shortest path from the first node to the second node.(Note that there might not be any path between the nodes.)<p>Clicking on a third node will de-select the first two.</p><p>Here is a list of all paths between the first and second selected nodes.Select a path to highlight it in the diagram.</p><select id="myPaths" style="min-width:100px" size="10"></select>
</div>

效果

点击两个节点,如0和5:

185019_rGBV_2391658.png

获取到的节点路径:

185055_jht6_2391658.png

点击上面的记录,则可以在上图中显示路径走向。

原文地址:http://gojs.net/latest/samples/distances.html

转载于:https://my.oschina.net/u/2391658/blog/869438

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/456922.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

河南王牌计算机专业,河南计算机专业实力突出的7所大学,郑大位列次席,榜首实至名归...

郑州大学是省内唯一的211建设高校&#xff0c;整体办学实力在国内同类高校之中名列前茅&#xff0c;虽然没有能够在学科评估之中取得A类学科&#xff0c;但学校有化学、考古学、材料科学与工程等多个学科获评B&#xff0c;学校计算机科学与技术学科取得了C的成绩&#xff0c;虽…

JavaScript 实现继承的5种方式

js是一个面向对象的语言&#xff0c;所以具备一些面向对象的方式----------例如继承。接下来介绍5种js的继承方式.注意&#xff1a;js 中的函数其实是对象&#xff0c;函数名是对 Function 对象的引用。 1.采用call方法改变函数上下文实现继承&#xff0c;原理是改变函数内部的…

初学者在python下使用Ta-lib库时遇到的一些问题及解决办法

由于Ta-lib是一款小众库&#xff0c;所以没有很好的API来说明其中各个函数的使用方法。无奈只能摸着石头过河&#xff0c;一个个试其中函数。期间遇到一些问题希望分享出来对大家有帮助。 问题描述:在使用Ta-lib库时用到的一些简单函数如SMA(),WMA(),EMA()这类方法时&#xff…

global全局变量

global全局变量 在不指向新的地址时&#xff0c;可以不调用&#xff47;&#xff4c;&#xff4f;&#xff42;&#xff41;&#xff4c;

快速入门Matplotlib

以下是原文正文&#xff1a; 数据的处理、分析和可视化已经成为 Python 近年来最重要的应用之一。这种现象又进一步引出“大数据”分析等类似的话题&#xff0c;而大数据分析在人们所能预见的诸多领域内都有广泛应用&#xff0c;这其中就包含笔者个人感兴趣的机器学习。 Pytho…

谷歌开源 Python Fire:可自动生成命令行接口

为什么80%的码农都做不了架构师&#xff1f;>>> 今天我们很高兴地宣布 Python Fire 开源。Python Fire 可从任何 Python 代码生成命令行接口&#xff08;command line interfaces (CLIs)&#xff09;&#xff0c;简单地调用任意 Python 程序中的 Fire 函数以将那个…

tcp ip计算机网络协议,一篇文章带你熟悉 TCP/IP 协议-(一)

一、 计算机网络体系结构分层不难看出&#xff0c;TCP/IP 与 OSI 在分层模块上稍有区别。OSI 参考模型注重“通信协议必要的功能是什么”&#xff0c;而 TCP/IP 则更强调“在计算机上实现协议应该开发哪种程序”。二、 TCP/IP 基础1. TCP/IP 的具体含义从字面意义上讲&#xff…

Random Forest算法参数解释及调优

文章介绍了如何对随机森林模型进行参数调优 原文来自&#xff1a;http://www.analyticsvidhya.com/blog/2015/06/tuning-random-forest-model/ 为什么要调整机器学习算法&#xff1f; 一个月以前&#xff0c;我在kaggle上参加了一个名为TFI的比赛。 我第一次提交的结果在50%…

Random Forest随机森林概述

引言 在机器学习中&#xff0c;随机森林由许多的决策树组成&#xff0c;因为这些决策树的形成采用了随机的方法&#xff0c;因此也叫做随机决策树。随机森林中的树之间是没有关联的。当测试数据进入随机森林时&#xff0c;其实就是让每一颗决策树进行分类&#xff0c;最后取所…

kd tree学习笔记 (最近邻域查询)

https://zhuanlan.zhihu.com/p/22557068 http://blog.csdn.net/zhjchengfeng5/article/details/7855241 KD树在算法竞赛中主要用来做各种各样的平面区域查询&#xff0c;包含则累加直接返回&#xff0c;相交则继续递归&#xff0c;相离的没有任何贡献也直接返回。可以处理圆&am…

图像影音型计算机主板选择什么,电脑主板型号在哪里看? 每日一答

电脑主板型号在哪里看&#xff1f;想要看主板的型号其实非常简单&#xff0c;一般来说&#xff0c;主板上都会有一个专门的身份标识&#xff0c;位于PCI-E显卡插槽之间&#xff0c;比如下方这张图&#xff0c;就清晰地写明了MAXIMUS X APEX的标识&#xff0c;熟悉的玩家一眼就能…

使用叶神模拟器无法访问本机服务器的问题(报错:java.net.ConnectException: failed to connect to /127.0.0.1 (port 5000) )

最近打算用夜神模拟器来和本机服务器做一些信息交互的功能&#xff0c;但是服务器搭建好了&#xff0c;用叶神模拟器却无法访问。折腾了大半天才发现原来是模拟器的问题。 具体过程如下&#xff1a; 搭建好服务器后&#xff0c;在本机上访问“http://127.0.0.1:5000/”&#…

初学大数据之如何选择机器学习算法

最近在国外网站看到一篇不错的文章&#xff0c;所以就翻译过来给大家分享一下。主要介绍初学者怎么选择机器学习算法,希望对各位初学者有帮助。 原文如下: 一个初学者面临各种机器学习算法的典型问题是“我应该使用哪种算法&#xff1f;”问题的答案取决于许多因素&#xff0…

Django查询 – id vs pk

当编写django查询时&#xff0c;可以使用id / pk作为查询参数。 Object.objects.get(id1) Object.objects.get(pk1) pk代表主键(primary key)&#xff0c; pk更加独立于实际的主键字段&#xff0c;即不必关心主键字段是否被称为id或object_id或其他。 如果您具有不同主键字…

Tomcat的Session管理(三)

摘要&#xff1a;PersistentManager与StandardManager的异同。 之前两篇关于session的文章主要讨论了session相关的创建、查询、过期处理。而我们查看源码的时候都是默认实现是StandardManager类&#xff0c;实际上实现也可以是PersistentManager类&#xff0c;下面我们就查看下…

稳定和性能如何兼顾?58大数据平台的技术演进与实践

作者&#xff5c;赵健博 编辑&#xff5c;尚剑 本文将为你分享58大数据平台在最近一年半内技术演进的过程&#xff0c;包括&#xff1a;58大数据平台目前的整体架构是怎么样的&#xff1b;最近一年半的时间内我们面临的问题、挑战以及技术演进过程&#xff1b;以及未来的规划。…

Random Forest算法简介

转自JoinQuant量化课堂 一、相关概念 分类器&#xff1a;分类器就是给定一个样本的数据&#xff0c;判定这个样本属于哪个类别的算法。例如在股票涨跌预测中&#xff0c;我们认为前一天的交易量和收盘价对于第二天的涨跌是有影响的&#xff0c;那么分类器就是通过样本的交易量…

简单交互

控件有着各种事件&#xff0c;例如被点击的时候&#xff0c;我们可以在事件里面添加动作和命令&#xff0c;让控件可以和用户交互&#xff0c;这里我们演示一个简单的交互&#xff1a;当用户点击文字控件的时候&#xff0c;它开始动画向下移动然后动画旋转&#xff0c;效果入下…

综合素质计算机考点,教师资格证小学综合素质考点及考试真题:信息处理能力...

小学综合素质考点及考试真题——信息处理能力大纲要求&#xff1a;具有运用工具书检索信息、资料的能力。具有运用网络检索、交流信息的能力。具有对信息进行筛选、分类、存储和应用的能力。具有运用教育测量知识进行数据分析与处理的能力。具有根据教育教学的需要&#xff0c;…

API文档自动生成

本文主要讲述自动化API文档生成——apidoc。网上有几个篇文章都只是介绍apidoc的&#xff0c;具体怎么在自己的项目中使用以及与其他配合使用都是没介绍的。最近开始玩服务器&#xff0c;了解到了有Windows与Linux之间共享文件的方法&#xff0c;就是samba。然后具体和apidoc结…