Question: Number of Connected Components in an Undirected Graph
My solutions (BFS/DFS) passed a few simple test cases, but for more difficult cases, the time limited has been exceeded. I was wondering if there is any way to fix it so that it may run faster?
PS: I know the class here does nothing and I don’t like it. It is just the way the website presents the solution.
BFS
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
nodes_left = list(range(n))
def bfs(node, edges):
visited = {node}
queue = [node]
while queue:
m = queue.pop(0)
nodes_left.remove(m)
nbr = [i for i in range(n) if [m, i] in edges or [i, m] in edges]
for i in nbr:
if i not in visited:
visited.add(i)
queue += [i]
res = 0
while nodes_left:
res += 1
node = nodes_left[0]
bfs(node, edges)
return res
DFS
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
nodes_left = list(range(n))
def dfs(node, edges, visited):
if node not in visited:
visited.add(node)
nodes_left.remove(node)
nbr = [i for i in range(n) if [node, i] in edges or [i, node] in edges]
for i in nbr:
dfs(i, edges, visited)
res = 0
while nodes_left:
res += 1
node = nodes_left[0]
visited = set()
dfs(node, edges, visited)
return res
The following BFS solution (which is from here) runs much faster
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
dist = collections.defaultdict(list)
for source, target in edges:
dist[source].append(target)
dist[target].append(source)
count = 0
visited=set()
queue = collections.deque()
for x in range(n):
if x in visited:
continue
queue.append(x)
while queue:
source=queue.popleft()
if source in visited:
continue
visited.add(source)
for target in dist[source]:
queue.append(target)
count+=1
return count