Skip to content

323. Number of Connected Components in an Undirected Graph #69

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tech-cow opened this issue Sep 23, 2019 · 0 comments
Closed

323. Number of Connected Components in an Undirected Graph #69

tech-cow opened this issue Sep 23, 2019 · 0 comments

Comments

@tech-cow
Copy link
Owner

323. Number of Connected Components in an Undirected Graph

Buggy

class Solution(object):
    def countComponents(self, n, edges):
        graph = self.makeGraph(edges)
        count = 0
        for i in range(n):
            if i in graph: continue    # wtf? if i in visited
            self.bfs(graph, i)
            count += 1
        return count
    
    
    def makeGraph(self, edges):
        graph = collections.defaultdict(list)
        for n1, n2 in edges:
            graph[n1].append(n2)
            graph[n2].append(n1)
        return graph

    
    def bfs(self, graph, index):
        queue, visited = collections.deque([index]), set(index)  # visited needs to be outside/global
        while queue:
            node = queue.popleft()
            for neighbor in graph[node]:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

Final Solution

class Solution(object):
    def countComponents(self, n, edges):
        graph = self.makeGraph(edges)
        count = 0
        visited = set()        

        for i in range(n):    
            if i in visited: continue
            self.bfs(graph, i, visited)
            count += 1
        return count
    
    
    def makeGraph(self, edges):
        graph = collections.defaultdict(list)
        for n1, n2 in edges:
            graph[n1].append(n2)
            graph[n2].append(n1)
        return graph

    
    def bfs(self, graph, index, visited):
        queue = collections.deque([index])
        while queue:
            node = queue.popleft()
            visited.add(node)
            for neighbor in graph[node]:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)
        
        
            
            
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant