Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ba0eaca

Browse files
1319: Number of Operations to Make Network Connected
1 parent 98fc01f commit ba0eaca

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# https://leetcode.com/problems/number-of-operations-to-make-network-connected/description/
2+
# T: O(M) where M is the number of connections
3+
# S: O(N) where N is the number of nodes
4+
5+
class Solution:
6+
def makeConnected(self, n, connections) -> int:
7+
if len(connections) < n-1:
8+
return -1
9+
if n == 1:
10+
return 0
11+
graph = {}
12+
for a, b in connections:
13+
if a in graph:
14+
graph[a].append(b)
15+
else:
16+
graph[a] = [b]
17+
18+
if b in graph:
19+
graph[b].append(a)
20+
else:
21+
graph[b] = [a]
22+
23+
visited = [0] * n
24+
25+
def dfs(node):
26+
if visited[node]:
27+
return 0
28+
visited[node] = 1
29+
if node in graph:
30+
for num in graph[node]:
31+
dfs(num)
32+
return 1
33+
34+
35+
return sum(dfs(node) for node in range(n)) - 1

0 commit comments

Comments
 (0)