DFS solution
# time O(N^2) space O(N)
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
size = len(M)
cnt = 0
visited = [False] * size
for i in range(size):
if(not visited[i]):
self.dfs(M,visited,i)
cnt += 1
return cnt
def dfs(self,M,visited, person):
for other in range(len(M)):
# found another person in current person's friend cycle
if M[person][other] == 1 and not visited[other]:
visited[other] = True
self.dfs(M,visited,other) # start a new DFS based on the reached friend
UF solution TODO