package leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * https://leetcode.com/problems/find-eventual-safe-states/
 */
public class Problem802 {
    public List<Integer> eventualSafeNodes(int[][] graph) {
        Set<Integer> result = new TreeSet<>();
        boolean[] ignored = new boolean[10000];
        for (int i = 0; i < graph.length; i++) {
            if (ignored[i]) {
                continue;
            }
            boolean[] visited = new boolean[10000];
            boolean[] onStack = new boolean[10000];
            Cycle cycle = new Cycle();
            dfs(graph, i, visited, onStack, cycle);
            if (!cycle.cycle) {
                for (int j = 0; j < visited.length; j++) {
                    if (visited[j]) {
                        ignored[j] = true;
                        result.add(j);
                    }
                }
            }
        }
        return new ArrayList<>(result);
    }

    private static class Cycle {
        private boolean cycle;
    }

    private static void dfs(int[][] graph, int source, boolean[] visited,
                            boolean[] onStack, Cycle cycle) {
        visited[source] = true;
        onStack[source] = true;
        for (int neighbor : graph[source]) {
            if (!visited[neighbor]) {
                dfs(graph, neighbor, visited, onStack, cycle);
            } else {
                if (onStack[neighbor]) {
                    cycle.cycle = true;
                }
            }
        }
        onStack[source] = false;
    }

    public static void main(String[ ] args) {
        Problem802 prob = new Problem802();
        System.out.println(prob.eventualSafeNodes(new int[][]{
            {1, 2}, {2, 3}, {5}, {0}, {5}, {}, {}
        })); // [2,4,5,6]
        System.out.println(prob.eventualSafeNodes(new int[][]{
            {1, 2}, {1}, {0}
        })); // []
    }
}

@@ -61,34 +61,19 @@
 til.
-List;%0Aimport java.util.Set
+Collections
 ;%0Aim
@@ -87,22 +87,19 @@
 va.util.
-TreeSe
+Lis
 t;%0A%0A/**%0A
@@ -256,18 +256,19 @@
         
-Se
+Lis
 t%3CIntege
@@ -287,14 +287,16 @@
 new 
-TreeSe
+ArrayLis
 t%3C%3E(
@@ -785,16 +785,31 @@
 sited%5Bj%5D
+ && !ignored%5Bj%5D
 ) %7B%0A    
@@ -962,38 +962,55 @@
     
-return new ArrayList%3C%3E(
+Collections.sort(result);%0A        return 
 result
-)
 ;%0A  

Update problem 802