图 -- 大二上十三周十四周

一般是一组顶点(vertex)和一组(eage)边
按照邻接矩阵来表示,如果是稀疏图(就是图中有很多0),就表示我们用了大量的内存来存储压根儿就没有的边,这是邻接矩阵的一个缺点

图的实现

function Graph() {//邻接表记录图的具体存储情况
  // 属性:顶点,边
  this.vertexes = [];
  this.edges = new Dictionary();//用了字典

  // 方法
  // 添加顶点
  Graph.prototype.addVertex = function (v) {
    this.vertexes.push(v);
    this.edges.set(v, []);
  }
  Graph.prototype.addEdge = function (v1, v2) {
    this.edges.get(v1).push(v2);
    this.edges.get(v2).push(v1);
  }
  Graph.prototype.toString = function () {
    let resstr = '';
    for (let i = 0; i < this.vertexes.length; i++) {
      resstr += this.vertexes[i] + '->';
      let temp = this.edges.get(this.vertexes[i]);
      for (let j = 0; j < temp.length; j++) {
        resstr +=  temp[j] + ' ';
      }
      resstr += "\n";
    }
    return resstr;
  }
  Graph.prototype.initializeColor = function () {
    let colors = [];
    for (let i = 0; i < this.vertexes.length; i++) {
      colors[this.vertexes[i]] = 'white';
    }
    return colors;
  }
  Graph.prototype.BFS = function(initV, handler) {//基于队列
    let colors = this.initializeColor();//初始化颜色
    let queue = new Queue();

    queue.enqueue(initV);
    while (!queue.isEmpty()) {
      let v = queue.dequeue();
      let vlist = this.edges.get(v);
      colors[v] = "gray";
      for (let i = 0; i < vlist.length; i++) {
        let temp = vlist[i]
        if(colors[temp] == 'white'){
          colors[temp] = "gray";
          queue.enqueue(temp);
        }            
      }
      handler(v);//访问顶点
      colors[v] = 'black';
    }
  }
  Graph.prototype.DFS = function(initV, handler) {//栈或递归
    let colors = this.initializeColor();
    this.dfsVisit(initV, colors, handler);
  }
  Graph.prototype.dfsVisit = function (v, colors, handler) {
    colors[v] = 'gray';
    handler(v);
    let vlist = this.edges.get(v);
    for (let i = 0; i < vlist.length; i++) {
      let temp = vlist[i];
      if(colors[temp] == 'white'){
        this.dfsVisit(temp, colors, handler);
      }
    }
    colors[v] = 'black';
  }
}

let g = new Graph()
let myVertex = ['A','B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
for (let i = 0; i < myVertex.length; i++) {
  g.addVertex(myVertex[i]);
}
g.addEdge('A', 'B');
g.addEdge('A', 'C');
g.addEdge('A', 'D');
g.addEdge('C', 'D');
g.addEdge('C', 'G');
g.addEdge('D', 'G');
g.addEdge('D', 'H');
g.addEdge('B', 'E');
g.addEdge('B', 'F');
g.addEdge('E', 'I');

// alert(g);
// console.log(g.toString());
let result = '';
g.DFS(g.vertexes[0], function (v) {
  result += v + ' ';
})
alert(result);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值