|
| 1 | +// https://leetcode.com/problems/all-paths-from-source-lead-to-destination |
| 2 | +// T: O(V + E) |
| 3 | +// S: O(V) |
| 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 AllPathsFromSourceLeadToDestination { |
| 11 | + // We don't use the state WHITE as such anywhere. Instead, the "null" value in the states array below is a substitute for WHITE. |
| 12 | + enum Color { GRAY, BLACK }; |
| 13 | + |
| 14 | + public boolean leadsToDestination(int n, int[][] edges, int source, int destination) { |
| 15 | + Map<Integer, Set<Integer>> graph = buildGraph(edges); |
| 16 | + return leadsToDestination(graph, source, destination, new Color[n]); |
| 17 | + } |
| 18 | + |
| 19 | + private boolean leadsToDestination(Map<Integer, Set<Integer>> graph, int node, int target, Color[] states) { |
| 20 | + // If the state is GRAY, this is a backward edge and hence, it creates a loop. |
| 21 | + if (states[node] != null) { |
| 22 | + return states[node] == Color.BLACK; |
| 23 | + } |
| 24 | + |
| 25 | + // If this is a leaf node, it should be equal to the destination. |
| 26 | + if (!graph.containsKey(node)) { |
| 27 | + return node == target; |
| 28 | + } |
| 29 | + |
| 30 | + // Now, we are processing this node. So we mark it as GRAY |
| 31 | + states[node] = Color.GRAY; |
| 32 | + |
| 33 | + for (int next : graph.get(node)) { |
| 34 | + if (!leadsToDestination(graph, next, target, states)) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + states[node] = Color.BLACK; |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + private Map<Integer, Set<Integer>> buildGraph(int[][] edges) { |
| 44 | + final Map<Integer, Set<Integer>> graph = new HashMap<>(); |
| 45 | + for (int[] edge : edges) { |
| 46 | + final int from = edge[0], to = edge[1]; |
| 47 | + final Set<Integer> neighbours = graph.getOrDefault(from, new HashSet<>()); |
| 48 | + neighbours.add(to); |
| 49 | + graph.putIfAbsent(from, neighbours); |
| 50 | + } |
| 51 | + return graph; |
| 52 | + } |
| 53 | +} |
0 commit comments