js 实现字典、图

字典

function Dictionary() {
  this.items = {};

  Dictionary.prototype.set = function (key, value) {
    this.items[key] = value;
  };

  Dictionary.prototype.has = function (key) {
    return this.items.hasOwnProperty(key);
  };

  Dictionary.prototype.remove = function (key) {
    if (!this.has(key)) return false;
    delete this.items[key];
    return true;
  };

  Dictionary.prototype.get = function (key) {
    return this.has(key) ? this.items[key] : undefined;
  };

  Dictionary.prototype.keys = function () {
    return Object.keys(this.items);
  };

  Dictionary.prototype.size = function () {
    return this.keys.length;
  };

  Dictionary.prototype.clear = function () {
    this.items = {};
  };
}

需要用到队列

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.initColor = function () {
    const colors = [];
    for (let i = 0; i < this.vertexes.length; i++) {
      colors[this.vertexes[i]] = "white";
    }
    return colors;
  };

  // 广度优先搜索
  Graph.prototype.bfs = function (initV, handler) {
    // 1. 初始化颜色
    const colors = this.initColor();

    // 2. 创建队列
    const queue = new Queue();

    // 3. 将顶点加入到队列中
    queue.enqueue(initV);

    // 4. 循环从队列中取出元素
    while (!queue.isEmpty()) {
      const v = queue.dequeue();

      const vList = this.edges.get(v);

      colors[v] = "gray";

      for (let i = 0; i < vList.length; i++) {
        const e = vList[i];
        if (colors[e] === "white") {
          colors[e] = "gray";
          queue.enqueue(e);
        }
      }

      handler(v);

      colors[v] = "black";
    }
  };

  // 深度优先搜索
  Graph.prototype.dfs = function (initV, handler) {
    // 1. 初始化颜色
    const colors = this.initColor();

    //  2. 从某个顶点开始依次递归访问
    this.dfsVisit(initV, colors, handler);
  };

  Graph.prototype.dfsVisit = function (v, colors, handler) {
    // 1. 先将颜色设置为灰色
    colors[v] = "gray";

    // 2. 处理v顶点
    handler(v);

    // 3. 访问v相连的顶点
    const vList = this.edges.get(v);

    for (let i = 0; i < vList.length; i++) {
      const e = vList[i];

      if (colors[e] === "white") {
        this.dfsVisit(e, colors, handler);
      }
    }

    // 4. 将v设置成黑色
    colors[v] = "black";
  };
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值