```
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
n = len(M)
visited = [False]*n
def dfs(curr):
if visited[curr]: return False
stack = [curr]
while stack:
curr = stack.pop()
visited[curr] = True
for i, v in enumerate(M[curr]):
if not v or i == curr or visited[i] : continue
stack.append(i)
return True
return sum(dfs(i) for i in range(n))
```