```
class Solution(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
N = len(M)
visited = [False] * N
res = 0
for i in range(N):
if visited[i]:
continue
stack = [i]
visited[i] = True
while stack:
x = stack.pop()
for y in range(N):
if not visited[y] and M[x][y] == 1:
visited[y] = True
stack.append(y)
res += 1
return res
```