LeetCode Solutions
323. Number of Connected Components in an Undirected Graph
Time: $O(|V| + |E|)$ Space: $O(|V| + |E|)$
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
int ans = 0;
vector<vector<int>> graph(n);
unordered_set<int> seen;
for (const vector<int>& e : edges) {
const int u = e[0];
const int v = e[1];
graph[u].push_back(v);
graph[v].push_back(u);
}
for (int i = 0; i < n; ++i)
if (!seen.count(i)) {
bfs(graph, i, seen);
++ans;
}
return ans;
}
private:
void bfs(const vector<vector<int>>& graph, int node,
unordered_set<int>& seen) {
queue<int> q{{node}};
seen.insert(node);
while (!q.empty()) {
const int u = q.front();
q.pop();
for (const int v : graph[u])
if (!seen.count(v)) {
q.push(v);
seen.insert(v);
}
}
}
};
class Solution {
public int countComponents(int n, int[][] edges) {
int ans = 0;
List<Integer>[] graph = new List[n];
Set<Integer> seen = new HashSet<>();
for (int i = 0; i < n; ++i)
graph[i] = new ArrayList<>();
for (int[] e : edges) {
final int u = e[0];
final int v = e[1];
graph[u].add(v);
graph[v].add(u);
}
for (int i = 0; i < n; ++i)
if (!seen.contains(i)) {
bfs(graph, i, seen);
++ans;
}
return ans;
}
private void bfs(List<Integer>[] graph, int node, Set<Integer> seen) {
Queue<Integer> q = new ArrayDeque<>(Arrays.asList(node));
seen.add(node);
while (!q.isEmpty()) {
final int u = q.poll();
for (final int v : graph[u])
if (!seen.contains(v)) {
q.offer(v);
seen.add(v);
}
}
}
}
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
ans = 0
graph = [[] for _ in range(n)]
seen = set()
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def bfs(node: int, seen: Set[int]) -> None:
q = deque([node])
seen.add(node)
while q:
u = q.pop()
for v in graph[u]:
if v not in seen:
q.append(v)
seen.add(v)
for i in range(n):
if i not in seen:
bfs(i, seen)
ans += 1
return ans