javascript数据结构8-图(Graph)
来源:互联网 发布:万网二手域名交易平台 编辑:程序博客网 时间:2024/06/16 05:48
图(graph)
图由边的集合及顶点的集合组成
有向图:
无向图:
代码:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Graph</title></head><body><script> function Graph(v){ this.vertices=v; this.edges=0; this.adj=[]; for(var i=0;i<this.vertices;++i){ this.adj[i]=[]; // this.adj[i].push(""); } this.addEdge=addEdge; this.showGraph=showGraph; //深度优先搜索 this.dfs=dfs; this.marked=[]; for(var i=0;i<this.vertices;++i){ this.marked[i]=false; } // 广度搜索 this.bfs=bfs; } // 增加顶点 function addEdge(v,w){ this.adj[v].push(w); this.adj[w].push(v); this.edges++; } //遍历 function showGraph(){ for(var i=0;i<this.vertices;++i){ document.write('<br/>'); document.write(i+"-->"); for(var j=0;j<this.vertices;++j){ if(this.adj[i][j]!=undefined){ document.write(this.adj[i][j]+' '); } } } } //深度优先搜索 function dfs(v){ //var w; this.marked[v]=true; if(this.adj[v]!=undefined){ document.write("<br/>访问的节点:"+v); } // for(var w in this.adj[v]){ //console.log(this.adj[0].length); var w=this.adj[v].shift(); while(w!=undefined){ if(!this.marked[w]){ this.dfs(w); } w=this.adj[v].shift(); } //console.log(w); //console.log(this.adj[v]); } // 广度搜索 function bfs(s){ var queue=[]; this.marked[s]=true; queue.push(s);//添加到队尾 var w; //存放邻接表 while(queue.length>0){ var v=queue.shift();//从队首删除 if(v!=undefined){ document.write("<br/>访问的节点:"+v); } w=this.adj[v].shift(); while(w!=undefined){ if(!this.marked[w]){ this.marked[w]=true; queue.push(w); } w=this.adj[v].shift(); } } } //测试 var graph=new Graph(5); graph.addEdge(0,1); graph.addEdge(0,2); graph.addEdge(1,3); graph.addEdge(2,4); //console.log(graph); //console.log(graph.adj); graph.showGraph(); document.write("<br/>"); document.write("======深度度优先搜索====="); graph.dfs(0); document.write("<br/>"); document.write("======广度优先搜索====="); var graph1=new Graph(5); graph1.addEdge(0,1); graph1.addEdge(0,2); graph1.addEdge(1,3); graph1.addEdge(2,4); graph1.bfs(0);</script></body></html>
运行结果:
0–>1 2
1–>0 3
2–>0 4
3–>1
4–>2
======深度度优先搜索=====
访问的节点:0
访问的节点:1
访问的节点:3
访问的节点:2
访问的节点:4
======广度优先搜索=====
访问的节点:0
访问的节点:1
访问的节点:2
访问的节点:3
访问的节点:4
深度搜索的含义:
广度搜索的含义:
0 0
- javascript数据结构8-图(Graph)
- 【数据结构】图(Graph)
- 图数据结构 graph.h
- 数据结构_图(Graph)
- 数据结构 图 Graph
- graph--数据结构试验(题目)
- graph--数据结构试验(代码)
- 数据结构基础攻略——图(Graph)
- Python 数据结构与算法——图(Graph)
- 数据结构之图 Data Structure — graph
- Graph 图构建 (Graph Constructor)
- Graph 图优化 (graph optimizer)
- 图(graph)
- 图(Graph)
- tensorflow:图(Graph)的核心数据结构与通用函数(Utility function)
- Python 数据结构与算法——二分图(bipartite graph)
- tensorflow graph 数据结构
- 3D引擎数据结构与glTF(2): Scene Graph
- javascript数据结构7-二叉搜索树(BST)
- centos下在线安装配置jdk
- ajaxFileUpload+Struts2文件上传
- lucene6.2.1测试用例
- vim常用快捷键
- javascript数据结构8-图(Graph)
- 找工作期间的一些想法
- 【SSH】常用的jar管理
- centos下面配置tomcat
- Leetcode 98. Validate Binary Search Tree
- 【Win32笔记四】Mesasge的定义和发送——消息队列
- javascript数据结构9-排序
- 文章标题
- Cadence 17.2 Padstack Editor入门指南(2)