边工作边刷题:70天一遍leetcode: day 94

Number of Connected Components in an Undirected Graph

要点:
union-find如何记?

  • data structure就一个array/list,每个元素初始化为val=index,表示每个元素是独立的。之后还保持的元素一定是union后的根。
  • union的过程先find(O(lgn)),然后选rank小的合并。
  • 这里可以简化,不记录rank,任意合并,code可以简化不少

错误点:

  • find:recursion的arg是parents[x],不是x(否则成死循环了)
  • xrange doesn’t support item assignment, use range instead

https://repl.it/Cbe0/1


# Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

# Example 1:
#      0          3
#      |          |
#      1 --- 2    4
# Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.

# Example 2:
#      0           4
#      |           |
#      1 --- 2 --- 3
# Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.

# Note:
# You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.


class Solution(object):
    def countComponents(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: int
        """
        p = range(n)
        def find(x):
        	if p[x]!=x:
        		p[x]=find(p[x])
        	return p[x]
        
        for s,d in edges:
        	ss, dd = find(s),find(d) 
        	p[ss] = dd
        	n-=ss!=dd
        return n

sol = Solution()
assert sol.countComponents(5, [[0,1],[1,2],[3,4]])==2, "should be 2"
assert sol.countComponents(5, [[0,1],[1,2],[0,2],[3,4]])==2, "should be 2"
        
posted @ 2016-07-12 20:19  absolute100  阅读(131)  评论(0编辑  收藏  举报