正在解决以下问题(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。
答案 0 :(得分:1)
您写的是parents[i] = parent_j
而不是parents[parent_i] = parent_j
,因此可以将对象i
移动到集合parent_j
中,而无需携带其余集合。