|
| 1 | +# Time: O(n^2 * m) |
| 2 | +# Space: O(n) |
| 3 | + |
| 4 | +# graph, flood fill, bfs |
| 5 | +class Solution(object): |
| 6 | + def numberOfComponents(self, properties, k): |
| 7 | + """ |
| 8 | + :type properties: List[List[int]] |
| 9 | + :type k: int |
| 10 | + :rtype: int |
| 11 | + """ |
| 12 | + def bfs(u): |
| 13 | + q = [u] |
| 14 | + while q: |
| 15 | + new_q = [] |
| 16 | + for u in q: |
| 17 | + for v in adj[u]: |
| 18 | + if lookup[v]: |
| 19 | + continue |
| 20 | + lookup[v] = True |
| 21 | + new_q.append(v) |
| 22 | + q = new_q |
| 23 | + |
| 24 | + p_set = [set(p) for p in properties] |
| 25 | + adj = [[] for _ in xrange(len(properties))] |
| 26 | + for i in xrange(len(p_set)): |
| 27 | + for j in xrange(i+1, len(p_set)): |
| 28 | + if sum(x in p_set[j] for x in p_set[i]) >= k: |
| 29 | + adj[i].append(j) |
| 30 | + adj[j].append(i) |
| 31 | + lookup = [False]*len(properties) |
| 32 | + result = 0 |
| 33 | + for i in xrange(len(properties)): |
| 34 | + if lookup[i]: |
| 35 | + continue |
| 36 | + bfs(i) |
| 37 | + result += 1 |
| 38 | + return result |
| 39 | + |
| 40 | + |
| 41 | +# Time: O(n^2 * m) |
| 42 | +# Space: O(n) |
| 43 | +# graph, union find |
| 44 | +class Solution2(object): |
| 45 | + def numberOfComponents(self, properties, k): |
| 46 | + """ |
| 47 | + :type properties: List[List[int]] |
| 48 | + :type k: int |
| 49 | + :rtype: int |
| 50 | + """ |
| 51 | + class UnionFind(object): # Time: O(n * alpha(n)), Space: O(n) |
| 52 | + def __init__(self, n): |
| 53 | + self.set = range(n) |
| 54 | + self.rank = [0]*n |
| 55 | + |
| 56 | + def find_set(self, x): |
| 57 | + stk = [] |
| 58 | + while self.set[x] != x: # path compression |
| 59 | + stk.append(x) |
| 60 | + x = self.set[x] |
| 61 | + while stk: |
| 62 | + self.set[stk.pop()] = x |
| 63 | + return x |
| 64 | + |
| 65 | + def union_set(self, x, y): |
| 66 | + x, y = self.find_set(x), self.find_set(y) |
| 67 | + if x == y: |
| 68 | + return False |
| 69 | + if self.rank[x] > self.rank[y]: # union by rank |
| 70 | + x, y = y, x |
| 71 | + self.set[x] = self.set[y] |
| 72 | + if self.rank[x] == self.rank[y]: |
| 73 | + self.rank[y] += 1 |
| 74 | + return True |
| 75 | + |
| 76 | + p_set = [set(p) for p in properties] |
| 77 | + uf = UnionFind(len(properties)) |
| 78 | + return len(properties)-sum(sum(x in p_set[j] for x in p_set[i]) >= k and uf.union_set(i, j) for i in xrange(len(p_set)) for j in xrange(i+1, len(p_set))) |
0 commit comments