最短路径优先算法:

JavaScript最短路径优先算法:

在这里插入图片描述

代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>数据结构</title>
</head>

<body>
  <script>
    let Graph = (function () {
      //队列类,辅助广度优先遍历
      class Queue{
        constructor(){
          this.items = [];
        }
        //入队 被发现队
        enqueue(data){
          this.items.push(data);
        }
        //出队 先入先出
        dequeue(){
          return this.items.shift();
        }
        size(){
          return this.items.length;
        }
      }

      return class{
        constructor() {
          //存储所有顶点
          this.vertices = [];
          //存储每个顶点对应的相邻顶点(边)
          this.edges = [
            // "R1":["R2","R3"],
          ];
        }
        //添加节点
        addVertex(...rest) {
          rest.forEach(v => {
            //数组includes判断是否含有某值
            if (this.vertices.includes(v)) return;
            //添加节点
            this.vertices.push(v);
            //添加节点相连数组
            this.edges[v] = [];

          });
        }
        //添加边
        addEdge(v1, v2) {
          //添加节点
          this.addVertex(v1, v2);
          //数组里添加边
          if (this.edges[v1].includes(v2)) return;
          this.edges[v1].push(v2);
          this.edges[v2].push(v1);
        }
        //广度优先
        BFS(v){
          let vertices = this.vertices,
                 edges = this.edges,
                 color = {},
                 queue = new Queue(),
                 info = {};
          //对每个节点添加 状态标志
          this.vertices.forEach(v=>{
            color[v] = "无状态";
          });
          //从入口节点v入队开始探索
          queue.enqueue(v);
          color[v] = "被发现";
          info[v] = {distance: 0,path:v};
          //发现于探索
          while(queue.size()){
            let u =queue.dequeue(); //出队
            edges[u].forEach(v=>{ //遍历A对应的直连边数组
              if(color[v] !== "无状态")return;
              color[v] = "被发现";
              queue.enqueue(v); //无状态的入队
              info[v] = {
                distance : info[u].distance +1,
                path : info[u].path + "->" + v
              }
            });
            color[u] = "被探索";
          }
          // 返回路径信息
          return info;
        }
      }
    })();

    let graph = new Graph;

    //A边与B边相邻
    graph.addEdge('R1', 'R2');
    graph.addEdge('R1', 'R3');
    graph.addEdge('R1', 'R5');
    graph.addEdge('R2', 'R4');
    graph.addEdge('R2', 'R5');
    graph.addEdge('R3', 'R6');
    graph.addEdge('R5', 'R6');

    // console.log(graph)
    console.log(graph.BFS("R1"))
  </script>
</body>
</html>

运行结果如下:

在这里插入图片描述

发布了234 篇原创文章 · 获赞 46 · 访问量 15万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 终极编程指南 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览