zoukankan      html  css  js  c++  java
  • 【js数据结构】图的深度优先搜索与广度优先搜索

    图类的构建

    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;

    }

    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)

    {
      putstr(i + " -> ");
      for (var j = 0; j < this.vertices; ++j )

       {
        if (this.adj[i][j] != undefined)

        {
          putstr(this.adj[i][j] + ' ');
        }
     }

      print();

    }
    }

     

    深度优先搜素

    f

    function dfs(v) {
      this.marked[v] = true;
      if (this.adj[v] != undefined)

       {
        print("Visited vertex: " + v);
      }

      for each(var w in this.adj[v]) {

        if (!this.marked[w]) {
        this.dfs(w);
        }
      }
    }

    广度优先搜索

      

    function bfs(s)

    {
      var queue = [];
      this.marked[s] = true;
      queue.push(s); // 添加到队尾
      while (queue.length > 0)

       {
        var v = queue.shift(); // 从队首移除
        if (v == undefined)

        {
          print("Visisted vertex: " + v);
        }

        for each(var w in this.adj[v])

        {

          if (!this.marked[w])

           {
            this.edgeTo[w] = v;
            this.marked[w] = true;
            queue.push(w);
          }
        }
      }
    }

     

    (本文为作者笔记,代码与图片皆出自《数据结构与算法 javascript 描述》一书)

  • 相关阅读:
    .NET ------ 多线程的简单使用
    .NET --- 页面刷新(html 和 js两种方式)
    .NET ---- B/S的特点,不接收js赋值
    二分查找与二分答案
    c++运行程序 鼠标点击按钮 (c++)(windows)
    c++运行程序 光标隐藏与移动 (c++)(windows)
    推荐:史蒂芬霍金论天道
    LaTeX公式学习
    Markdown语法学习
    文言语言!!!(附c/c++自译)
  • 原文地址:https://www.cnblogs.com/xiabaoying/p/6685163.html
Copyright © 2011-2022 走看看