2360. 图中的最长环 难度困难

给你一个 n 个节点的 有向图 ,节点编号为 0 到 n - 1 ,其中每个节点 至多 有一条出边。

图用一个大小为 n 下标从 0 开始的数组 edges 表示,节点 i 到节点 edges[i] 之间有一条有向边。如果节点 i 没有出边,那么 edges[i] == -1 。

请你返回图中的 最长 环,如果没有任何环,请返回 -1 。

一个环指的是起点和终点是 同一个 节点的路径。

示例 1:

输入:edges = [3,3,4,2,3]
输出去:3
解释:图中的最长环是:2 -> 4 -> 3 -> 2 。
这个环的长度为 3 ,所以返回 3 。
示例 2:

输入:edges = [2,-1,3,1]
输出:-1
解释:图中没有任何环。

public class Demo1 {
    public static void main(String[] args) {
        System.out.println(new Solution().longestCycle(new int[]{3,3,4,2,3}));
    }
}

class Solution {
    static int cnt = 0;
    static Map<Integer, Integer> map = new HashMap<>();
    public int longestCycle(int[] edges) {
        int r = -1;
        map = new HashMap<>();
        for (int i = 0; i < edges.length; i++) {
            Set set = new HashSet();
            cnt = 0;
            int a = dfs(i, i, edges, set);
            map.put(i, a);
            //System.out.println(cnt);
            if (r < a) {
                r = a;
            }
        }
        return r;
    }

    public int dfs(int startIndex, int index, int[] edges, Set set) {
        if (map.get(index) != null) {
            return -1;
        }
        if (index < 0) {
            return -1;
        }
        int cur = edges[index];
        //System.out.println(cur);
        if (cur == -1) {
            return -1;
        }
        if (!set.contains(index)) {
            set.add(index);
            cnt++;
            return dfs(startIndex, cur, edges, set);
        } else {
            if (startIndex != index) {
                return -1;
            } else {
                return cnt;
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值