leetcode 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 thanK 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.

这里写图片描述


我们可以使用染色法来解决这道题:
在这里我给出三种颜色。
0:代表没有颜色
1:safe颜色
2:unsafe不安全颜色
递归的更新每个节点的颜色,就OK了。

class Solution {
   public  List<Integer> eventualSafeNodes(int[][] graph) {
        // 0: 没有 color
        // 1 : safe 
        // 2 : unsafe

        // 默认都是 没有颜色的
        int[] colors = new int[graph.length];
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < graph.length; i++) {
            if (dfs(graph, i, colors)) {
                res.add(i);
            }
        }
        return res;

    }
    public  boolean dfs(int[][] graph, int color, int[] colors) {
        // 如果 这点已经有颜色了
        if (colors[color] != 0) {
            return colors[color] == 1; // 看他是否 safe
        }
        // 先把这点 置为不安全,只有他的后继节点都安全, 才把他置为安全
        colors[color] = 2;
        for (int color_next : graph[color]) {
            if (!dfs(graph, color_next, colors)) {
                return false;
            }
        }
        colors[color] = 1;
        return true;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值