Similar Problems
Similar Problems not available
Number Of Operations To Make Network Connected  Leetcode Solution
Companies:
LeetCode: Number Of Operations To Make Network Connected Leetcode Solution
Difficulty: Medium
Topics: breadthfirstsearch unionfind depthfirstsearch graph
Problem Statement:
There are n computers numbered from 0 to n1 connected by ethernet cables connections forming a network where connections[i] = [a, b] represents a connection between computers a and b. Any computer can reach any other computer directly or indirectly through the network.
Given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return the minimum number of times you need to do this in order to make all the computers connected. If it's not possible, return 1.
Solution:
To solve this problem, first, we need to understand the concept of a disconnected graph and connected components of a graph. A graph is said to be disconnected if there are two or more vertices that are not connected by any edge. On the other hand, a connected component is a subgraph in which every two vertices are connected to each other by a path.
Approach:
 Create the adjacency matrix for the given connections.
 Count the number of connected components in the graph using DFS or BFS algorithms.
 If there is only one connected component, the given graph is already connected, so return 0.
 Otherwise, the number of cables that need to be added is equal to the number of connected components minus 1.
Pseudo code:
 def makeConnected(n: int, connections: List[List[int]]) > int:

graph = [] # to store the edges

for i in range(n):

graph.append([])

for i in range(len(connections)):

a = connections[i][0]

b = connections[i][1]

graph[a].append(b)

graph[b].append(a)

visited = [False] * n

components = 0

for i in range(n):

if not visited[i]:

dfs(graph, visited, i)

components += 1

if len(connections) < n1:

return 1

else:

return components 1
 def dfs(graph, visited, i):

visited[i] = True

for j in range(len(graph[i])):

if not visited[graph[i][j]]:

dfs(graph, visited, graph[i][j])
Time complexity:
We need to iterate over the connections for creating an adjacency list and perform a DFS or BFS traversal over the graph, hence the overall time complexity is O(N+E).
Space complexity:
We use an adjacency list and visited array to keep track of visited nodes in DFS, which requires O(N+E) space.
Conclusion:
In this problem, we have learned how to count the number of operations required to make a disconnected graph connected. We have used DFS algorithm here, and our solution has a time complexity of O(N+E) and space complexity of O(N+E).
Number Of Operations To Make Network Connected Solution Code
1