1. BFS Component Sizing with Double Loop Combinations
Intuition
Traverse the graph with BFS starting at each unvisited node to count component sizes. After gathering the list of component sizes, iterate with two nested loops for i in 0..c: for j in i+1..c: pairs += size[i] * size[j].
Algorithm
- Build adjacency list for all n astronauts.
- Initialize visited array of size n to false.
- Initialize componentSizes list.
- Loop i from 0 to n - 1:
- If !visited[i]:
- Run BFS from i, counting nodes in this component.
- componentSizes.push(count).
- Initialize totalPairs = 0.
- For i from 0 to componentSizes.length - 1:
- For j from i + 1 to componentSizes.length - 1:
- totalPairs += componentSizes[i] * componentSizes[j].
- Return totalPairs.
#include <iostream>#include <vector>#include <queue> class Solution {public: long long journeyToMoon(int n, std::vector<std::vector<int>>& astronaut) { std::vector<std::vector<int>> adj(n); for (const auto& p : astronaut) { adj[p[0]].push_back(p[1]); adj[p[1]].push_back(p[0]); } std::vector<bool> visited(n, false); std::vector<long long> compSizes; for (int i = 0; i < n; ++i) { if (!visited[i]) { long long count = 0; std::queue<int> q; q.push(i); visited[i] = true; while (!q.empty()) { int curr = q.front(); q.pop(); count++; for (int neighbor : adj[curr]) { if (!visited[neighbor]) { visited[neighbor] = true; q.push(neighbor); } } } compSizes.push_back(count); } } long long totalPairs = 0; int k = compSizes.size(); for (int i = 0; i < k; ++i) { for (int j = i + 1; j < k; ++j) { totalPairs += compSizes[i] * compSizes[j]; } } return totalPairs; }}; int main() { Solution sol; std::vector<std::vector<int>> pairs = {{0, 1}, {2, 3}, {0, 4}}; std::cout << "Pairs: " << sol.journeyToMoon(5, pairs) << " (Expected: 6)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(V + E + k^2) - Space complexity:
O(V + E)