-
Notifications
You must be signed in to change notification settings - Fork 5
/
1971. Find if Path Exists in Graph.java
99 lines (84 loc) · 2.24 KB
/
1971. Find if Path Exists in Graph.java
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class Solution {
private static class UnionFind {
private int[] parents;
private int vertices;
public UnionFind(int vertices) {
super();
this.vertices = vertices;
this.parents = new int[vertices + 1];
for (int i = 0; i < vertices; i++)
parents[i] = i;
}
@Override
public String toString() {
return "UnionFind [parents=" + Arrays.toString(parents) + ", vertices=" + vertices + "]";
}
public void union(int u, int v) {
if (u != v) {
int pa = find(u);
int pb = find(v);
parents[pb] = pa;
}
}
private int find(int u) {
// TODO Auto-generated method stub
int x = u;
while (x != parents[x]) {
x = parents[x];
}
parents[u] = x;
return x;
}
public boolean areConnected(int u, int v) {
return find(u) == find(v);
}
}
public boolean validPath(int n, int[][] edges, int source, int destination) {
// return DFSTraversalMethod(n, edges, source, destination);
UnionFind uf = new UnionFind(n);
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
uf.union(u, v);
}
return uf.areConnected(source, destination);
}
private boolean DFSTraversalMethod(int n, int[][] edges, int source, int destination) {
try {
Map<Integer, List<Integer>> graph = buildGraph(edges);
boolean[] visitedVertices = new boolean[n];
Stack<Integer> stack = new Stack<>();
markAsVisited(source, visitedVertices, stack);
while (!stack.isEmpty()) {
int node = stack.pop();
for (int neighbour : graph.get(node)) {
if (neighbour == destination)
return true;
if (!visitedVertices[neighbour]) {
markAsVisited(neighbour, visitedVertices, stack);
}
}
}
return false;
} catch (Exception e) {
// TODO: handle exception
return false;
}
}
private Map<Integer, List<Integer>> buildGraph(int[][] edges) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
graph.putIfAbsent(u, new ArrayList<>());
graph.putIfAbsent(v, new ArrayList<>());
graph.get(u).add(v);
graph.get(v).add(u);
}
return graph;
}
private void markAsVisited(int source, boolean[] visitedVertices, Stack<Integer> stack) {
visitedVertices[source] = true;
stack.add(source);
}
}