### 323. Number of Connected Components in an Undirected Graph





题目： 
<https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/>



难度 : Medium



思路：



最容易想到的是针对每个节点做dfs？然后发现其已经被mark了就不管了，最后数dfs的次数？

这样尝试，到n =2000 的时候 TLE

```
class Solution(object):
    def countComponents(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: int
        """
        def dfs(node):
        	if visited[node] == 1:
        		return 
        	else:
        		visited[node] = 1
        		for node1, node2 in edges:
        			if node1 == node:
        				dfs(node2)
        			elif node2 == node:
        				dfs(node1)

        res = 0
        visited = [ 0 for i in range(n)]
        for i in range(n):
        	if visited[i] == 0:
        		dfs(i)
        		res += 1
        return res
```



tag是union find，不用是否浪费？

所谓的union find，应当不是每个做dfs，而是每个来看一下是否属于同一个set，一次dfs，然后loop 做union find

[Disjoint-set_data_structure](https://en.wikipedia.org/wiki/Disjoint-set_data_structure)

<https://zh.wikipedia.org/wiki/并查集>

这里有一个很棒的[实现](http://python-algorithms.readthedocs.io/en/stable/_modules/python_algorithms/basic/union_find.html)



AC代码

这里就偷懒了，利用岛是0-n，然后也只做了path compression，没更多的优化



```
class Solution(object):
    def countComponents(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: int
        """
        def find(x):
        	if uf[x] != x:
        		uf[x] = find(uf[x])
        	return uf[x]

        def union(x,y):
        	xRoot = find(x)
        	yRoot = find(y)
        	uf[xRoot] = yRoot

        uf = [i for i in range(n)]

        for node1, node2 in edges:
        	union(node1, node2)

        res = set()
        for i in range(n):
        	res.add(find(i))

        return len(res)
```



