-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path547_Friend_Circles.py
92 lines (83 loc) · 2.37 KB
/
547_Friend_Circles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
# because
visited = [0] * len(M)
count = 0
for i in range(len(M)):
if visited[i] == 0:
self.dfs(M, visited, i)
count += 1
return count
def dfs(self, M, visited, i):
for j in range(len(M)):
if M[i][j] == 1 and visited[j] == 0:
visited[j] = 1
self.dfs(M, visited, j)
# def findCircleNum(self, M):
# # BFS
# visited = [0] * len(M)
# count = 0
# queue = []
# for i in range(len(M)):
# if visited[i] == 0:
# queue.append(i)
# while queue:
# curr = queue.pop(0)
# visited[curr] = 1
# for j in range(len(M)):
# if M[curr][j] == 1 and visited[j] == 0:
# queue.append(j)
# count += 1
# return count
# def findCircleNum(self, M):
# # Union Find
# union = Union()
# for i in range(len(M)):
# union.add(i)
# for i in range(len(M)):
# for j in range(i + 1, len(M)):
# if M[i][j] == 1:
# union.union(i, j)
# return union.count
# class Union(object):
# """
# weighted quick union find
# """
# def __init__(self):
# # both dic and list is fine
# self.id = {}
# self.sz = {}
# self.count = 0
# def count(self):
# return self.count
# def connected(self, p, q):
# return self.find(p) == self.find(q)
# def add(self, p):
# # init
# self.id[p] = p
# self.sz[p] = 1
# self.count += 1
# def find(self, p):
# """
# find root of p, and compress path
# """
# while p != self.id[p]:
# self.id[p] = self.id[self.id[p]]
# p = self.id[p]
# return p
# def union(self, p, q):
# """
# connect p and q
# """
# i, j = self.find(p), self.find(q)
# if i == j:
# return
# if self.sz[i] > self.sz[j]:
# i, j = j, i
# self.id[i] = j
# self.sz[j] += self.sz[i]
# self.count -= 1