zoukankan      html  css  js  c++  java
  • 深度优先搜索

    //深度优先搜索 从一条路径的起始顶点开始追溯到达最后一个顶点,然后回溯继续追溯下一条路径,直到最后一个顶点,如此N次,直到没有路径为止。
    //创建图
    function Graph(v) {
       this.vertices = v;
       this.edges = 0;
       this.adj = [];
       for (var i = 0; i < this.vertices; ++i) {
          this.adj[i] = [];
       }
       this.addEdge = addEdge;
       this.showGraph = showGraph;
       this.dfs = dfs;
       this.marked = [];
       for (var i = 0; i < this.vertices; ++i) {
          this.marked[i] = false;
       }
    }
     
     
    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++){
      console.log('顶点'+i+'->');
      for(var j=0;j<this.vertices;j++){
       if(this.adj[i][j]){
        console.log(this.adj[i][j]+' ');
       }
      }
     }
    }
     
    function dfs(s) {
       var queue=[];this.edgeTo=[];
       this.marked[s] = true;
      queue.push(s)
      while(queue.length>0){
        var v=queue.shift();
     
          console.log('vs:'+v);
     
        for each(var w in this.adj[v]){
          if(!this.marked[w]){
            this.edgeTo[w]=v;
            this.marked[w]=true;
            queue.push(w)
         
          }
       
        }
     
      }
    }
    g = new Graph(5);
    g.addEdge(0,1);
    g.addEdge(0,2);
    g.addEdge(1,3);
    g.addEdge(2,4);
    g.showGraph();
    g.dfs(0);
    //0 1 2 3 4
  • 相关阅读:
    layer-list:Android中layer-list使用详解
    Nexus6p:正在下载系统更新,没有进度
    转:浅谈char类型范围
    C/C++/Java中的volatile关键字
    C++中的mutable关键字
    C++中的typedef typename 作用
    C++中的友元函数和友元类
    用flashfxp做ftp镜像同步
    python读取caffemodel文件
    py-faster-rcnn几个辅助脚本
  • 原文地址:https://www.cnblogs.com/yuzhongwusan/p/4094620.html
Copyright © 2011-2022 走看看