802. Find Eventual Safe States

Question:

In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop.

Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps.

Which nodes are eventually safe? Return them as an array in sorted order.

The directed graph has N nodes with labels 0, 1, …, N-1, where N is the length of graph. The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph.

Example:
Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Here is a diagram of the above graph.

Illustration of graph Imgur

Note:

  • graph will have length at most 10000.
  • The number of edges in the graph will not exceed 32000.
  • Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1].

Solution:

  • Method 1: dfs + graph
    • This question is about to find the nodes who is not in a cycle, which means itself and its children are not in a cycle.
    • We take 4 states to record a node’s status
      • {UNKNOW, VISIT, SAFE, UNSAFE}
      • UNKNOWN: current node is not visited. Initialized status.
      • VISIT: current node is in the process of dfs. UNKNOW -> VISIT
      • SAFE: current node is safe. All childs are SAFE -> current is SAFE
      • UNSAFE: current node is unsafe. VISIT -> UNSAFE
          class Solution {
           private static final int UNKNOWN = 0;
           private static final int VISIT = 1;
           private static final int SAFE = 2;
           private static final int UNSAFE = 3;
           private int[] state;
           private int len;
           public List<Integer> eventualSafeNodes(int[][] graph) {
          List<Integer> result = new ArrayList<>();
          if(graph == null || graph.length == 0) return result;
          len = graph.length;
          state = new int[len];
          for(int i = 0; i < len; i++){
              if(dfs(graph, i) == SAFE)
                  result.add(i);
          }
          return result;
           }
           private int dfs(int[][] graph, int cur){
          if(state[cur] == VISIT){
              return state[cur] = UNSAFE;
          }else if(state[cur] != UNKNOWN){
              return state[cur];
          }
          state[cur] = VISIT;
          for(int i = 0; i < graph[cur].length; i++){
              if(dfs(graph, graph[cur][i]) == UNSAFE){
                  return state[cur] = UNSAFE;
              }
          }
          return state[cur] = SAFE;
           }
          }
        

Reference

  1. 花花酱 LeetCode 802. Find Eventual Safe States