Python DFS Fast Solution


  • 0
    D
    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))

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.