【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 描述》一書)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM