|
| 1 | +package com.fishercoder.solutions.secondthousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +public class _1059 { |
| 7 | + public static class Solution1 { |
| 8 | + /** |
| 9 | + * Credit: https://leetcode.com/problems/all-paths-from-source-lead-to-destination/editorial/ |
| 10 | + * A very powerful algorithm, three colors to DFS a tree/graph. |
| 11 | + */ |
| 12 | + enum Color { |
| 13 | + WHITE, |
| 14 | + GRAY, |
| 15 | + BLACK |
| 16 | + } |
| 17 | + |
| 18 | + public boolean leadsToDestination(int n, int[][] edges, int source, int destination) { |
| 19 | + List<Integer>[] graph = buildGraph(n, edges); |
| 20 | + Color[] colors = new Color[n]; |
| 21 | + for (int i = 0; i < n; i++) { |
| 22 | + colors[i] = Color.WHITE; |
| 23 | + } |
| 24 | + return leadsToDest(graph, colors, source, destination); |
| 25 | + } |
| 26 | + |
| 27 | + private boolean leadsToDest(List<Integer>[] graph, Color[] colors, int node, int destination) { |
| 28 | + //if it's not WHITE, then it should be BLACK, otherwise, there's a circle |
| 29 | + if (colors[node] != Color.WHITE) { |
| 30 | + return colors[node] == Color.BLACK; |
| 31 | + } |
| 32 | + //if this is a leaf node, then it should be destination, otherwise, it's a dead end and we return false |
| 33 | + if (graph[node].size() == 0) { |
| 34 | + return node == destination; |
| 35 | + } |
| 36 | + |
| 37 | + //now, we start processing this node and mark it as GRAY |
| 38 | + colors[node] = Color.GRAY; |
| 39 | + for (int neighbor : graph[node]) { |
| 40 | + if (!leadsToDest(graph, colors, neighbor, destination)) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + } |
| 44 | + //recursive processing is done, we mark it as BLACK |
| 45 | + colors[node] = Color.BLACK; |
| 46 | + return true; |
| 47 | + } |
| 48 | + |
| 49 | + private static List<Integer>[] buildGraph(int n, int[][] edges) { |
| 50 | + List<Integer>[] graph = new ArrayList[n]; |
| 51 | + for (int i = 0; i < n; i++) { |
| 52 | + graph[i] = new ArrayList<>(); |
| 53 | + } |
| 54 | + for (int[] edge : edges) { |
| 55 | + graph[edge[0]].add(edge[1]); |
| 56 | + } |
| 57 | + return graph; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments