|
| 1 | +// https://leetcode.com/problems/find-if-path-exists-in-graph |
| 2 | +// T: O(V + E) |
| 3 | +// S: O(V + E) |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +public class FindIfPathExistsInGraph { |
| 11 | + public boolean validPath(int n, int[][] edges, int start, int end) { |
| 12 | + UnDirectedGraph graph = UnDirectedGraph.from(n, edges); |
| 13 | + return graph.pathFrom(start, end); |
| 14 | + } |
| 15 | + |
| 16 | + private static final class UnDirectedGraph { |
| 17 | + private final Map<Integer, Vertex> vertices = new HashMap<>(); |
| 18 | + |
| 19 | + public static UnDirectedGraph from(int vertices, int[][] edges) { |
| 20 | + UnDirectedGraph graph = new UnDirectedGraph(vertices); |
| 21 | + for (int[] edge : edges) { |
| 22 | + graph.vertices.get(edge[0]).addEdge(edge[1]); |
| 23 | + graph.vertices.get(edge[1]).addEdge(edge[0]); |
| 24 | + } |
| 25 | + return graph; |
| 26 | + } |
| 27 | + |
| 28 | + private UnDirectedGraph(int vertices) { |
| 29 | + for (int i = 0 ; i < vertices ; i++) { |
| 30 | + this.vertices.put(i, new Vertex(i)); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public boolean pathFrom(int start, int end) { |
| 35 | + return pathTo(vertices.get(start), end, new HashSet<>()); |
| 36 | + } |
| 37 | + |
| 38 | + private boolean pathTo(Vertex from, int to, Set<Integer> visited) { |
| 39 | + if (visited.contains(from.value)) return false; |
| 40 | + if (from.value == to) return true; |
| 41 | + visited.add(from.value); |
| 42 | + for (int edge : from.edges) { |
| 43 | + if (pathTo(vertices.get(edge), to, visited)) { |
| 44 | + return true; |
| 45 | + } |
| 46 | + } |
| 47 | + return false; |
| 48 | + } |
| 49 | + |
| 50 | + private static final class Vertex { |
| 51 | + private final int value; |
| 52 | + private final Set<Integer> edges = new HashSet<>(); |
| 53 | + |
| 54 | + Vertex(int value) { |
| 55 | + this.value = value; |
| 56 | + } |
| 57 | + |
| 58 | + public void addEdge(int to) { |
| 59 | + edges.add(to); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments