学习笔记——并查集工具函数(javascript)

/*
 * @Author: zhihui
 * @Date: 2021-11-30 21:16:30
 * @LastEditTime: 2021-11-30 09:49:11
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \ECloud-H5d:\Test\网络连通数目-并查集.js
 */ 
var makeConnected = function(n, connections) {
  if (connections.length < n - 1) {
      return -1;
  }

  const uf = new UnionFind(n);
  for (const conn of connections) {
      uf.unite(conn[0], conn[1]);
  }

  return uf.result - 1;
};

class UnionFind {
  constructor(n) {
    this.parent = new Array(n).fill(0).map((item,index) => {
      return index
    })
    this.size = new Array(n).fill(1)
    // 当前连通数
    this.result = n
  }

  /**
   * @method find 进行路径压缩
   * @param {Number} x 待查询的值 
   */
  find(x) {
    if(this.parent[x] == x) return x;
    this.parent[x] = this.find(this.parent[x])
    return this.parent[x]
  }

  /**
   * @method unite 进行合并
   * @param {*} x 
   * @param {*} y 
   */
  unite(x, y) {
    x = this.find(x)
    y = this.find(y)
    if(x == y) return
    if(this.size[x] < this.size[y]) {
      [x, y] = [y, x]
    }
    this.parent[y] = x
    this.size[x] += this.size[y]
    this.result --
  }
}

var result = makeConnected(4, [[0,1],[0,2],[1,2]])

并查集比较适合用在 判断图的连通性,图的连通个数, 图是否存在环

这个是我最近学习并查集算法的写的一个工具函数,方便之后自己温习(j加油!!!!!!)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值