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;虽…

Linux中配置ftp服务器

1. 先用rpm -qa| grep vsftpd命令检查是否已经安装&#xff0c;如果ftp没有安装&#xff0c;使用yum -y install vsftpd 安装,(ubuntu 下使用apt-get install vsftpd) 2. service vsftpd start / service vsftpd restart 启动要让FTP每次开机自动启动&#xff0c;运行命令:…

机器学习中各类算法的优缺点比较

1决策树&#xff08;Decision Trees&#xff09;的优缺点 决策树的优点&#xff1a; 一、 决策树易于理解和解释.人们在通过解释后都有能力去理解决策树所表达的意义。 二、 对于决策树&#xff0c;数据的准备往往是简单或者是不必要的.其他的技术往往要求先把数据一般化&am…

在程序开发中日志级别

日志打印可以查看代码的执行情况&#xff0c;以及快速定位错误。 在代码中&#xff0c;特别是业务层逻辑的代码&#xff0c;适当的添加日志是必须的&#xff0c;一般在catch代码块中是出现异常的&#xff0c;如果需要打印 可以用error级别&#xff0c; 一般的无关紧要的日志&am…

基于Python搭建Django后台管理系统

一、博客网站的创建 创建项目 生成站点&#xff08;sites&#xff09;Model&#xff0c;这两步骤第一篇有介绍&#xff0c;这里就直接操作了 二、数据库配置 介绍一下数据库的配置就是在setting里面配置链接的数据库&#xff0c;这里系统以及配置好了&#xff0c;链接一个…

计算机研究所专业课,【择校必看】十三所计算机专业课只考数据结构的985院校!...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼敲黑板&#xff1a;本文涉及到的学校计算机专业考研只考数据结构&#xff0c;其中部分院校同时也会考算法、C语言等相关内容。但是&#xff0c;相对其他几门&#xff0c;无疑在专业课的复习上大大降低了难度。如果各位同学目前的专…

在Python2.7下如何安装TA-lib库

最近在做一个关于股票预测的模型&#xff0c;由于想要用Talib库中的方法&#xff0c;来提取各种金融技术指标&#xff0c;所以就下了这个库。但整个过程可谓是一波三折。花费了大半天才搞定这件事。 下面来给大家分享一下安装的步骤&#xff0c;省的大家再往这个坑里跳。。。 …

JavaScript 实现继承的5种方式

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

day20 django

1、Django请求的生命周期武彦涛&#xff1a;路由系统 -> 试图函数(获取模板数据》渲染) -> 字符串返回给用户2、路由系统王腾&#xff1a;/index/ -> 函数或类.as_view()/detail/(\d) -> 函数(参数) 或 类.as_view()&#xff08;参数&am…

解决Django 忘记超级管理员密码 重设密码登录教程

看到标题就知道有逗比忘了密码。。。没错就是我。 你也忘了密码&#xff1f; 不要着急&#xff01; 00&#xff1a; 第一步&#xff1a;运行django shell python3 manage.py shell 01&#xff1a; 第二步&#xff1a;重设密码 >>> from django.contrib.auth…

计算机统计知识,计算机知识在统计工作中的重要性

计算机知识在统计工作中的重要性目前计算机已在县以上统计部门广为利用,如何注意提高统计业务人员的计算机水平,培养出既懂统计业务,又懂计算机知识的复合型统计人才,是当前急待研究和解决的重要问题。一、计算机存在的问题当前在基层统计队伍中使用计算机存在(本文共1页)阅读全…

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

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

cocoapods-安装

下面方法解决pod setup出错&#xff08;特别慢&#xff09;&#xff1a; 1.访问 https://github.com/CocoaPods/Specs&#xff0c;然后将Specs项目fork到自己的github账户上2. 下载GitHub Desktop, 然后clone Specs项目&#xff08;客户端还是特别慢&#xff0c;我直接check一份…

计算机在输电线路设计中的应用研究,计算机在输电线路基础设计中的应用原稿(备份存档)...

《计算机在输电线路基础设计中的应用(原稿).doc》由会员分享&#xff0c;可免费在线阅读全文&#xff0c;更多与《计算机在输电线路基础设计中的应用(原稿)》相关文档资源请在帮帮文库(www.woc88.com)数亿文档库存里搜索。1、节省与浪费材料的情况之分。遵从相应的规则对全部可…

global全局变量

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

C# 获取文件MD5值的方法

可用于对比文件是否相同 1 /// <summary>2 /// 获取文件MD5值3 /// </summary>4 /// <param name"fileName">文件绝对路径</param>5 /// <returns>MD5值</returns>6 public static str…

快速入门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…

远程控制python

import telnetlibdef telnetDoSomething(IP,user,passwd,command):try:# 连接服务器telnet telnetlib.Telnet(IP)# 设置调试级别telnet.set_debuglevel(2)# 读取输入用户名信息rt telnet.read_until("Login username:".encode("utf-8"))# 写入用户名tel…