给定一个整数N ,表示通过形成网络的电缆连接的计算机数量和二维数组connection[][] ,每行(i, j)代表第i和第j台计算机之间的连接,任务是连接通过删除任何给定的连接并连接两台断开连接的计算机,直接或间接地删除所有计算机。
如果无法连接所有计算机,请打印-1 。
否则,打印所需的最小数量的此类操作。
例子:
Input: N = 4, connections[][] = {{0, 1}, {0, 2}, {1, 2}}
Output: 1
Explanation: Remove the connection between computers 1 and 2 and connect the computers 1 and 3.
Input: N = 5, connections[][] = {{0, 1}, {0, 2}, {3, 4}, {2, 3}}
Output: 0
方法:思想是使用类似于最小生成树的概念,如在具有N 个节点的 Graph 中,只需要N-1 条边即可使所有节点连接。
Redundant edges = Total edges – [(Number of Nodes – 1) – (Number of components – 1)]
If Redundant edges > (Number of components – 1) : It is clear that there are enough wires that can be used to connect disconnected computers. Otherwise, print -1.
请按照以下步骤解决问题:
- 初始化一个无序映射,比如adj来存储来自给定的关于边的信息的邻接列表。
- 初始化一个布尔数据类型的向量,比如visited ,来存储一个节点是否被访问过。
- 生成邻接表并计算边数。
- 初始化一个变量,比如components ,以存储连接组件的数量。
- 使用 DFS 遍历图的节点,计算连通分量的数量并将其存储在变量components 中。
- 初始化一个变量,比如冗余,并使用上述公式存储冗余边的数量。
- 如果冗余边 > components – 1 ,则所需操作的最小数量等于components – 1 。否则,打印-1 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to visit the nodes of a graph
void DFS(unordered_map >& adj,
int node, vector& visited)
{
// If current node is already visited
if (visited[node])
return;
// If current node is not visited
visited[node] = true;
// Recurse for neighbouring nodes
for (auto x : adj[node]) {
// If the node is not vistied
if (visited[x] == false)
DFS(adj, x, visited);
}
}
// Utility function to check if it is
// possible to connect all computers or not
int makeConnectedUtil(int N,
int connections[][2],
int M)
{
// Stores whether a
// node is visited or not
vector visited(N, false);
// Build the adjacency list
unordered_map > adj;
// Stores count of edges
int edges = 0;
// Building adjaceny list
// from the given edges
for (int i = 0; i < M; ++i) {
// Add edges
adj[connections[i][0]].push_back(
connections[i][1]);
adj[connections[i][1]].push_back(
connections[i][0]);
// Increment count of edges
edges += 1;
}
// Stores count of components
int components = 0;
for (int i = 0; i < N; ++i) {
// If node is not visited
if (visited[i] == false) {
// Increment components
components += 1;
// Perform DFS
DFS(adj, i, visited);
}
}
// At least N - 1 edges are required
if (edges < N - 1)
return -1;
// Count redundant edges
int redundant = edges - ((N - 1)
- (components - 1));
// Check if components can be
// rearranged using redundant edges
if (redundant >= (components - 1))
return components - 1;
return -1;
}
// Function to check if it is possible
// to connect all the computers or not
void makeConnected(int N, int connections[][2], int M)
{
// Stores counmt of minimum
// operations required
int minOps = makeConnectedUtil(
N, connections, M);
// Print the minimum number
// of operations required
cout << minOps;
}
// Driver Code
int main()
{
// Given number of computers
int N = 4;
// Given set of connections
int connections[][2] = {
{ 0, 1 }, { 0, 2 }, { 1, 2 }
};
int M = sizeof(connections)
/ sizeof(connections[0]);
// Function call to check if it is
// possible to connect all computers or not
makeConnected(N, connections, M);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to visit the nodes of a graph
public static void DFS(HashMap > adj,
int node, boolean visited[])
{
// If current node is already visited
if (visited[node])
return;
// If current node is not visited
visited[node] = true;
// Recurse for neighbouring nodes
for (int x : adj.get(node)) {
// If the node is not vistied
if (visited[x] == false)
DFS(adj, x, visited);
}
}
// Utility function to check if it is
// possible to connect all computers or not
public static int
makeConnectedUtil(int N, int connections[][], int M)
{
// Stores whether a
// node is visited or not
boolean visited[] = new boolean[N];
// Build the adjacency list
HashMap > adj
= new HashMap<>();
// Initialize the adjacency list
for (int i = 0; i < N; i++) {
adj.put(i, new ArrayList());
}
// Stores count of edges
int edges = 0;
// Building adjaceny list
// from the given edges
for (int i = 0; i < M; ++i) {
// Get neighbours list
ArrayList l1
= adj.get(connections[i][0]);
ArrayList l2
= adj.get(connections[i][0]);
// Add edges
l1.add(connections[i][1]);
l2.add(connections[i][0]);
// Increment count of edges
edges += 1;
}
// Stores count of components
int components = 0;
for (int i = 0; i < N; ++i) {
// If node is not visited
if (visited[i] == false) {
// Increment components
components += 1;
// Perform DFS
DFS(adj, i, visited);
}
}
// At least N - 1 edges are required
if (edges < N - 1)
return -1;
// Count redundant edges
int redundant
= edges - ((N - 1) - (components - 1));
// Check if components can be
// rearranged using redundant edges
if (redundant >= (components - 1))
return components - 1;
return -1;
}
// Function to check if it is possible
// to connect all the computers or not
public static void
makeConnected(int N, int connections[][], int M)
{
// Stores counmt of minimum
// operations required
int minOps = makeConnectedUtil(N, connections, M);
// Print the minimum number
// of operations required
System.out.println(minOps);
}
// Driver Code
public static void main(String[] args)
{
// Given number of computers
int N = 4;
// Given set of connections
int connections[][]
= { { 0, 1 }, { 0, 2 }, { 1, 2 } };
int M = connections.length;
// Function call to check if it is
// possible to connect all computers or not
makeConnected(N, connections, M);
}
}
// This code is contributed by kingash.
Python3
# Python3 code for the above approach
# Function to visit the nodes of a graph
def DFS(adj, node, visited):
# If current node is already visited
if (visited[node]):
return
# If current node is not visited
visited[node] = True
# Recurse for neighbouring nodes
if(node in adj):
for x in adj[node]:
# If the node is not vistied
if (visited[x] == False):
DFS(adj, x, visited)
# Utility function to check if it is
# possible to connect all computers or not
def makeConnectedUtil(N, connections, M):
# Stores whether a
# node is visited or not
visited = [False for i in range(N)]
# Build the adjacency list
adj = {}
# Stores count of edges
edges = 0
# Building adjaceny list
# from the given edges
for i in range(M):
# Add edges
if (connections[i][0] in adj):
adj[connections[i][0]].append(
connections[i][1])
else:
adj[connections[i][0]] = []
if (connections[i][1] in adj):
adj[connections[i][1]].append(
connections[i][0])
else:
adj[connections[i][1]] = []
# Increment count of edges
edges += 1
# Stores count of components
components = 0
for i in range(N):
# If node is not visited
if (visited[i] == False):
# Increment components
components += 1
# Perform DFS
DFS(adj, i, visited)
# At least N - 1 edges are required
if (edges < N - 1):
return -1
# Count redundant edges
redundant = edges - ((N - 1) - (components - 1))
# Check if components can be
# rearranged using redundant edges
if (redundant >= (components - 1)):
return components - 1
return -1
# Function to check if it is possible
# to connect all the computers or not
def makeConnected(N, connections, M):
# Stores counmt of minimum
# operations required
minOps = makeConnectedUtil(N, connections, M)
# Print the minimum number
# of operations required
print(minOps)
# Driver Code
if __name__ == '__main__':
# Given number of computers
N = 4
# Given set of connections
connections = [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ] ]
M = len(connections)
# Function call to check if it is
# possible to connect all computers or not
makeConnected(N, connections, M)
# This code is contributed by ipg2016107
1
时间复杂度: O(N + M)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live