[Python] Iterative DFS solution using stack, 49ms


  • 0
    H
    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
    

Log in to reply
 

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