Find Eventual Safe States

LeetCode Q 802 - Find Eventual Safe States

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]

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

Solution 1 : BFS

Code:

public List<Integer> eventualSafeNodes(int[][] graph) {
	List<Integer> res = new ArrayList<>();
	if (graph == null || graph.length == 0) return res;

	int n = graph.length;

	// build graph
	// 2 -> 5, 4 -> 5 ; then map(5) = {2, 4};
	Map<Integer, List<Integer>> map = new HashMap<>();
	int[] order = new int[n];
	for (int i = 0; i < n; i++) 
		map.put(i, new ArrayList<>());
	for (int i = 0; i < n; i++) {
		for (int next: graph[i]) {
			map.get(next).add(i);
			order[i]++;
		}    
	}
	
	Queue<Integer> que = new LinkedList<>();
	for (int i = 0; i < n; i++) {
		if (order[i] == 0) que.offer(i); 
	}
	
	while (!que.isEmpty()) {
		int curr = que.poll();
		res.add(curr);
		for (int next: map.get(curr)) {
			order[next]--;
			if (order[next] == 0) que.offer(next);
		}
	}
	
	Collections.sort(res);
	
	return res;
}

Solution 2 : DFS

Code:

public List<Integer> eventualSafeNodes(int[][] graph) {
	List<Integer> res = new ArrayList<>();
	if (graph == null || graph.length == 0) return res;
	
	int n = graph.length;
	int[] status = new int[n];
	for (int i = 0; i < n; i++) {
	    if (!hasCycle(graph, i, status))
	        res.add(i);
	}
	
	return res;
}

private boolean hasCycle(int[][] graph, int i, int[] status) {
	if (status[i] == 1) return true;
	
	status[i] = 1;
	for (int next: graph[i]) {
		if (status[next] == 2) continue;
		if (hasCycle(graph, next, status))
			return true;
	}
	status[i] = 2;
	
	return false;
}

   Reprint policy


《Find Eventual Safe States》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC