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.pswp.cn/news/456922.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/456922.shtml
英文地址,請注明出處:http://en.pswp.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…