#802 Find Eventual Safe States

Description

There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].

A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node.

Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.

Example

Example 1:

Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]
Output: [2,4,5,6]
Explanation: The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.

Example 2:

Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]
Output: [4]
Explanation:
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.

Constraints:

n == graph.length
1 <= n <= 1 0 4 10^4 104
0 <= graph[i].length <= n
0 <= graph[i][j] <= n - 1
graph[i] is sorted in a strictly increasing order.
The graph may contain self-loops.
The number of edges in the graph will be in the range [1, 4 * 1 0 4 10^4 104].

思路

这里是用一个visited数组同时表示 被完整探测过的节点 和 在该条路径中被探测过的节点,特别地,有

  • 0:还未探测过的节点
  • 1:存在于正在探索的路径上的节点(当前正在探索节点的祖先)/ 确认有环的节点
  • 2:已经探测过,所有路径皆且无环得节点

证明一下使用一个数组可以实现的可能性

	start v
		visited[v] = 1
		...
			start u
				visited[u] = 1
				...
				visited[u] = 2
			finish u
		...
		visited[v] = 2
	finish v

可以看到,从v-u的过程中,途径的所有祖先节点都会被标记为1,只有访问过u节点之后,才有可能被标记为2(在代码里可以看到,如果有环会返回false,不会将visited[i]更新为2)

代码

class Solution {
    // 0 -> haven't visited; 1->visited in one path; 2->have detected that node in whole path
    int[] visited;
    
    public List<Integer> eventualSafeNodes(int[][] graph) {
        visited = new int[graph.length];
        List<Integer> route = new ArrayList();

        for (int i = 0; i < graph.length; ++i)
            if (dfs_visit(i, graph))
                route.add(i);     // ans的增添放在这里,因为题目要求针对i正序输出(如果是针对路径倒序输出[topology sort]就是放在递归里面进行了)
        return route;
    }

    public boolean dfs_visit(int v, int[][] graph) {
        if (visited[v] > 0)
            return visited[v] == 2;

        visited[v] = 1;
        for (int node: graph[v]) {
            if (!dfs_visit(node, graph))
                return false;
        }

        visited[v] = 2;
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值