1. DFS Traversal with Component Counting
Intuition
First check if the total edge count is at least n - 1. If not, return -1. Next, build an adjacency list of the graph and run standard Depth-First Search from every unvisited computer. Each DFS invocation explores an entire connected component. Count the total number of components C; the answer is C - 1.
Algorithm
- If
connections.length < n - 1, return -1. - Build an undirected adjacency list
adjof size n. - Initialize
visitedarray of size n filled with false. - Initialize
components = 0. - For each vertex i from 0 to n - 1:
- If
!visited[i]: - Increment
components. - Perform recursive
dfs(i)to mark all reachable computers as visited. - Return
components - 1.
#include <iostream>#include <vector> void dfs(int u, const std::vector<std::vector<int>>& adj, std::vector<bool>& visited) { visited[u] = true; for (int v : adj[u]) { if (!visited[v]) { dfs(v, adj, visited); } }} int makeConnectedDFS(int n, std::vector<std::vector<int>>& connections) { if (connections.size() < n - 1) return -1; std::vector<std::vector<int>> adj(n); for (const auto& conn : connections) { adj[conn[0]].push_back(conn[1]); adj[conn[1]].push_back(conn[0]); } std::vector<bool> visited(n, false); int components = 0; for (int i = 0; i < n; ++i) { if (!visited[i]) { components++; dfs(i, adj, visited); } } return components - 1;} int main() { std::vector<std::vector<int>> connections = {{0,1},{0,2},{0,3},{1,2},{1,3}}; std::cout << "Operations (DFS): " << makeConnectedDFS(6, connections) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(V + E) where V is n and E is connections.length. Visiting each node and edge once during DFS. - Space complexity:
O(V + E) to store the adjacency list and recursion stack.