package leetcode;

import java.util.ArrayList;
import java.util.List;

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

@@ -62,16 +62,64 @@
 il.List;
+%0Aimport java.util.Set;%0Aimport java.util.TreeSet;
 %0A%0A/**%0A *
@@ -274,19 +274,18 @@
         
-Lis
+Se
 t%3CIntege
@@ -300,24 +300,22 @@
 t = new 
-ArrayLis
+TreeSe
 t%3C%3E();%0A 
@@ -325,48 +325,166 @@
     
-for (int i = 0; i %3C graph.length; i++) %7B
+boolean%5B%5D ignored = new boolean%5B10000%5D;%0A        for (int i = 0; i %3C graph.length; i++) %7B%0A            if (ignored%5Bi%5D) %7B%0A                continue;%0A            %7D
 %0A   
@@ -699,32 +699,180 @@
 !cycle.cycle) %7B%0A
+                for (int j = 0; j %3C visited.length; j++) %7B%0A                    if (visited%5Bj%5D) %7B%0A                        ignored%5Bj%5D = true;%0A        
                 
@@ -886,12 +886,52 @@
 add(
-i
+j
 );%0A
+                    %7D%0A                %7D%0A
     
@@ -965,22 +965,39 @@
  return 
+new ArrayList%3C%3E(
 result
+)
 ;%0A    %7D%0A

Update problem 802