js图结构代码实现(邻接表表示)

图(Graph)是由顶点和连接顶点的边构成的离散结构。在计算机科学中,图是最灵活的数据结构之一,很多问题都可以使用图模型进行建模求解。例如:人与人之间的社交与关系网络、找到两个城市之间的最短路径等等。
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图结构</title>
</head>
<body>
    <script>
        function Graph(){
            //属性:存储顶点
            this.vertexes=[]
            //属性:存储边
            this.edges={}
        }
        //添加点方法
        Graph.prototype.addVertex=function(v){
            this.vertexes.push(v)
            this.edges[v]=[]
        }
        //添加边方法(无向图)
        Graph.prototype.addEdge=function(v1,v2){
            this.edges[v1].push(v2)
            this.edges[v2].push(v1)
        }
        //toString方法
        Graph.prototype.toSting=function(){
            var resultString=''
            for(var i=0;i<this.vertexes.length;i++){
                resultString+=this.vertexes[i]+'->'
                var vEdges=this.edges[this.vertexes[i]]
                for(var k=0;k<vEdges.length;k++){
                    resultString+=vEdges[k]+" "
                }
                resultString+="\n"
            }
            return resultString
        }
        //初始化颜色,white 未被访问,grey 访问未被探索,black访问并探索
        Graph.prototype.initializeColor=function(){
            var colors=[]
            for(var i=0;i<this.vertexes.length;i++){
                colors[this.vertexes[i]]='white'
            }
            return colors
        }
        //广度优先搜索BFS
        Graph.prototype.bfs=function(initV,handler){
            //初始化颜色
            var colors=this.initializeColor()
            //将顶点放入数组中
            var arr=[]
            arr.push(initV)
            while(arr.length!==0){
                //取出顶点
                var v=arr.shift()
                //把v设置成灰色
                colors[v]='grey'
                //获取顶点相连顶点,并加入数组中
                for(var i=0; i<this.edges[v].length;i++){
                    if(colors[this.edges[v][i]]=='white'){
                        colors[this.edges[v][i]]='grey'
                        arr.push(this.edges[v][i])
                    }
                    
                    
                }
                handler(v)
                colors[v]='black'
            }

        }
        //深度优先递归
        function recursionDfs(v,colors,handler){
            //颜色设置为灰色
            colors[v]='grey'
            //处理顶点
            handler(v)
            //访问相相连顶点
            for(var i=0;i<this.edges[v].length;i++){
                if(colors[this.edges[v][i]]=='white'){
                    recursionDfs.call(this,this.edges[v][i],colors,handler)
                }
            }
            //设置成black
            colors[v]='black'

        }
        //深度优先搜索DFS
        Graph.prototype.dfs=function(initV,handler){
            //初始化颜色
            var colors=this.initializeColor()
            recursionDfs.call(this,initV,colors,handler)
        }
        //测试代码
        var gra=new Graph()
        var vertexesExp=['A','B','C','D','E','F','G','H']
        for(var vertex of vertexesExp){
            gra.addVertex(vertex)
        }
        
        gra.addEdge('A','B')
        gra.addEdge('A','C')
        gra.addEdge('A','D')
        gra.addEdge('C','D')
        gra.addEdge('C','G')
        gra.addEdge('D','G')
        gra.addEdge('D','H')
        gra.addEdge('B','E')
        gra.addEdge('B','F')
        console.log(gra.toSting())
        //测试bfs
        var result=''
        gra.bfs(gra.vertexes[0],function(v){
            result +=v+"_"
            
        })
        console.log(result)
        //测试dfs
        result=''
        gra.dfs(gra.vertexes[0],function(v){
            result +=v+"_"
        })
        console.log(result)
        console.log(gra)
    </script>
</body>
</html>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
邻接矩阵和邻接表是两种常用的表示方法。下面是Java代码实现邻接矩阵和邻接表的示例: 1. 邻接矩阵表示的Java代码实现: ```java import java.util.Arrays; class Graph { private int[][] adjMatrix; private int numVertices; public Graph(int numVertices) { this.numVertices = numVertices; this.adjMatrix = new int[numVertices][numVertices]; } public void addEdge(int src, int dest) { // 无向,所以需要在两个位置都设置为1 adjMatrix[src][dest] = 1; adjMatrix[dest][src] = 1; } public void printGraph() { for (int i = 0; i < numVertices; i++) { System.out.print("Vertex " + i + " is connected to: "); for (int j = 0; j < numVertices; j++) { if (adjMatrix[i][j] == 1) { System.out.print(j + " "); } } System.out.println(); } } } public class Main { public static void main(String[] args) { Graph graph = new Graph(5); graph.addEdge(0, 1); graph.addEdge(0, 4); graph.addEdge(1, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.addEdge(2, 3); graph.addEdge(3, 4); graph.printGraph(); } } ``` 2. 邻接表表示的Java代码实现: ```java import java.util.LinkedList; class Graph { private int numVertices; private LinkedList<Integer>[] adjList; public Graph(int numVertices) { this.numVertices = numVertices; this.adjList = new LinkedList[numVertices]; for (int i = 0; i < numVertices; i++) { adjList[i] = new LinkedList<>(); } } public void addEdge(int src, int dest) { adjList[src].add(dest); adjList[dest].add(src); } public void printGraph() { for (int i = 0; i < numVertices; i++) { System.out.print("Vertex " + i + " is connected to: "); for (int j : adjList[i]) { System.out.print(j + " "); } System.out.println(); } } } public class Main { public static void main(String[] args) { Graph graph = new Graph(5); graph.addEdge(0, 1); graph.addEdge(0, 4); graph.addEdge(1, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.addEdge(2, 3); graph.addEdge(3, 4); graph.printGraph(); } } ``` 以上代码示例分别实现了邻接矩阵和邻接表表示的Java代码。你可以根据自己的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值