Skip to content

Commit faf0c2c

Browse files
committed
Mar 22
1 parent 243ac89 commit faf0c2c

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from collections import defaultdict
2+
3+
4+
class Solution:
5+
def countCompleteComponents(self, n: int, edges: list[list[int]]) -> int:
6+
graph = defaultdict(list)
7+
for u, v in edges:
8+
graph[u].append(v)
9+
graph[v].append(u)
10+
visited = set()
11+
12+
def dfs(u: int) -> tuple[int, int]:
13+
nonlocal visited, graph
14+
visited.add(u)
15+
nodes, edges = 1, len(graph[u])
16+
for v in graph[u]:
17+
if v in visited:
18+
continue
19+
sub_nodes, sub_edges = dfs(v)
20+
nodes += sub_nodes
21+
edges += sub_edges
22+
return nodes, edges
23+
24+
completed = 0
25+
for node in range(n):
26+
if node in visited:
27+
continue
28+
nodes, edges = dfs(node)
29+
if nodes * (nodes - 1) == edges:
30+
completed += 1
31+
return completed
32+
33+
34+
def main():
35+
n = 6
36+
edges = [[0, 1], [0, 2], [1, 2], [3, 4]]
37+
assert Solution().countCompleteComponents(n, edges) == 3
38+
39+
n = 6
40+
edges = [[0, 1], [0, 2], [1, 2], [3, 4], [3, 5]]
41+
assert Solution().countCompleteComponents(n, edges) == 1
42+
43+
44+
if __name__ == '__main__':
45+
main()

2025-03-March-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
| March 19 | [3191. Minimum Operations to Make Binary Array Elements Equal to One I](https://leetcode.com/problems/minimum-operations-to-make-binary-array-elements-equal-to-one-i/) | Medium | Solved |
2626
| March 20 | [3108. Minimum Cost Walk in Weighted Graph](https://leetcode.com/problems/minimum-cost-walk-in-weighted-graph/) | Hard | Unsolved |
2727
| March 21 | [2115. Find All Possible Recipes from Given Supplies](https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/) | Medium | Unsolved |
28-
| March 22 | []() | | |
28+
| March 22 | [2685. Count the Number of Complete Components](https://leetcode.com/problems/count-the-number-of-complete-components/) | Medium | Unsolved |
2929
| March 23 | []() | | |
3030
| March 24 | []() | | |
3131
| March 25 | []() | | |
@@ -41,5 +41,5 @@
4141
| Level | Problems | Solved | Unsolved |
4242
| --- | --- | --- | --- |
4343
| Easy | 6 | 6 | 0 |
44-
| Medium | 14 | 6 | 8 |
44+
| Medium | 15 | 6 | 9 |
4545
| Hard | 1 | 0 | 1 |

0 commit comments

Comments
 (0)