【发布时间】:2018-10-15 23:49:50
【问题描述】:
正在解决以下问题 (https://leetcode.com/problems/friend-circles/):
一个班有 N 个学生。他们有的是朋友,有的是 不是。他们的友谊本质上是传递性的。例如,如果 A 是 B 的直接朋友,B 是 C 的直接朋友,那么 A 是 C的间接朋友。而我们定义的朋友圈是一组 直接或间接朋友的学生。
给定一个 N*N 矩阵 M 表示之间的朋友关系 班上的学生。如果 M[i][j] = 1,那么第 i 个和第 j 个学生 彼此是直接朋友,否则不是。你必须 输出所有学生的朋友圈总数。 例如:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
这是我的解决方案:
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
parents = [i for i in range(len(M))]
count = len(M)
def union(i, j):
parent_i = get_parent(i)
parent_j = get_parent(j)
parents[i] = parent_j
def get_parent(i):
while not parents[i] == i:
parents[i] = parents[parents[i]] # compress
i = parents[i]
return i
for i in range(len(M)):
for j in range(i+1, len(M)):
if M[i][j] == 1:
union(i, j)
return sum(i == parent for i, parent in enumerate(parents))
此代码因以下输入而中断:
[
[1,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,1,0,1,0,0,0,0,0,0,0,0,0,1,0],
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
[0,1,0,1,0,0,0,1,0,0,0,1,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,1,1,0,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0,0,0],
[1,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,1,0,0,0,0,0,0,0,1,0,0],
[0,1,0,0,0,0,0,0,0,0,0,0,0,1,0],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
]
(我的解决方案返回 10 而不是 8)并且我在跟踪我的算法不正确的地方时遇到了一些麻烦。有人看到这里有什么问题吗?注意:它包含在 class Solution 中,因为这是 Leetcode 的东西。
【问题讨论】:
标签: python connected-components union-find