Skip to content

Commit 906efae

Browse files
committed
Do weekly
1 parent a91bc13 commit 906efae

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

my-submissions/m323 v1.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def countComponents(self, n: int, edges: List[List[int]]) -> int:
3+
e = defaultdict(list)
4+
for u, v in edges :
5+
e[u].append(v)
6+
e[v].append(u)
7+
to_visit = set(range(0, n))
8+
9+
output = 0
10+
while to_visit :
11+
visited = set()
12+
nxt = [to_visit.pop()]
13+
output += 1
14+
15+
while nxt :
16+
curr = nxt.pop()
17+
if curr in visited :
18+
continue
19+
visited.add(curr)
20+
for x in e[curr] :
21+
if x not in visited :
22+
nxt.append(x)
23+
to_visit -= visited
24+
25+
return output

my-submissions/m323 v2 shortened.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def countComponents(self, n: int, edges: List[List[int]]) -> int:
3+
e = defaultdict(list)
4+
for u, v in edges :
5+
e[u].append(v)
6+
e[v].append(u)
7+
to_visit = set(range(0, n))
8+
9+
output = 0
10+
while to_visit :
11+
to_visit.add((nxt := [to_visit.pop()])[0])
12+
output += 1
13+
14+
while nxt :
15+
if (curr := nxt.pop()) not in to_visit :
16+
continue
17+
to_visit.remove(curr)
18+
nxt.extend(x for x in e[curr] if x in to_visit)
19+
20+
return output

0 commit comments

Comments
 (0)