-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2316_Count_Unreachable_Pairs_of_Nodes_in_an_Undirected_Graph.java
More file actions
55 lines (42 loc) · 1.38 KB
/
2316_Count_Unreachable_Pairs_of_Nodes_in_an_Undirected_Graph.java
File metadata and controls
55 lines (42 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
* Problem Link: https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
boolean [] visited;
Map<Integer, List<Integer>> graph;
public long countPairs(int n, int[][] edges) {
// create a graph
graph = new HashMap<>();
for (int [] edge: edges) {
graph.computeIfAbsent(edge[0], k->new ArrayList<>()).add(edge[1]);
graph.computeIfAbsent(edge[1], k->new ArrayList<>()).add(edge[0]);
}
long ans = 0;
long remainingNodes = n;
visited = new boolean[n];
for (int i = 0; i < n; i++) {
int componentSize = dfs(i);
remainingNodes -= componentSize;
ans += componentSize * remainingNodes;
}
return ans;
}
int dfs(int node) {
if (visited[node]) return 0;
visited[node] = true;
// no neighbour
if (!graph.containsKey(node)) return 1;
int count = 1;
for (int neighbour: graph.get(node)) {
count += dfs(neighbour);
}
return count;
}
}