547. Friend Circles

2020-01-19
阅读 3 分钟
2.7k
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direc...

快速理解Union Find算法--java代码实现

2017-12-07
阅读 3 分钟
9.5k
在并查集中,如果想要将连个对象相连,当且仅当这两个对象不在同一个连通分量中时,才会相连。这句话什么意思呢?也就是说,如果已经存在一条路径,使得p和q之间相通,那么就不会对后续的连接p和q的请求作出任何操作。

leetcode130. Surrounded Regions

2017-09-12
阅读 2 分钟
2.5k
这篇题目与leetcode200. Number of Islands思路非常相近,建议毫无思路的同学先参考一下这篇博客。其实这种将区域相连的题目往往都可以使用深度优先遍历或者是Union-Find方法来实现。在这里我就给出深度优先遍历的实现方法,有兴趣的同学可以参考上文的博客来自己实现Union-Find方法。

leetcode200. Number of Islands

2017-09-08
阅读 3 分钟
3k
这道题目从经典的数据结构的角度来说可以使用并查集来进行判断,将每一个海洋看做一个集合合并起来,将相邻的陆地通过并查集连接起来。最后查看并查集中剩余下的集合数。这里使用一个新的二维数组来表示对应地图上的元素属于哪个并查集。在合并的时候先进行判断,如果二者为已经相连的陆地,则无需合并,否则将新的二维...