-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
56 lines (42 loc) · 1.35 KB
/
Copy pathsolution.java
File metadata and controls
56 lines (42 loc) · 1.35 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
56
class Solution {
// DFS function to visit all reachable nodes
void dfs(int node, ArrayList<ArrayList<Integer>> adj, boolean[] visited) {
visited[node] = true;
// Visit all neighbours
for (int neighbor : adj.get(node)) {
if (!visited[neighbor]) {
dfs(neighbor, adj, visited);
}
}
}
public int findMotherVertex(int V, int[][] edges) {
// Create adjacency list
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
}
boolean[] visited = new boolean[V];
int candidate = -1;
// Find possible mother vertex
for (int i = 0; i < V; i++) {
if (!visited[i]) {
dfs(i, adj, visited);
// Last finished node becomes candidate
candidate = i;
}
}
// Reset visited array
visited = new boolean[V];
// Verify candidate
dfs(candidate, adj, visited);
for (int i = 0; i < V; i++) {
if (!visited[i]) {
return -1;
}
}
return candidate;
}
}