当前位置:网站首页>leetcode-6135:图中的最长环
leetcode-6135:图中的最长环
2022-08-01 07:50:00 【菊头蝙蝠】
leetcode-6135:图中的最长环
题目
题目连接
给你一个 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
解释:图中没有任何环。
解题
方法一:内向基环树找环+时间戳
class Solution {
public:
int longestCycle(vector<int>& edges) {
int n=edges.size();
vector<int> time(n,0);
int res=-1;
for(int i=0,clock=1;i<n;i++){
if(time[i]) continue;
for(int x=i,start_time=clock;x>=0;x=edges[x]){
if(time[x]){
if(time[x]>=start_time){
res=max(res,clock-time[x]);
}
break;
}
time[x]=clock++;
}
}
return res;
}
};
边栏推荐
猜你喜欢

类似 MS Project 的项目管理工具有哪些

Case practice --- Resnet classic convolutional neural network (Mindspore)

C语言中编译时出现警告C4013(C语言不加函数原型产生的潜在错误)

小程序更多的手势事件(左右滑动、放大缩小、双击、长按)

Holoview--Introduction

Golang: go get url and form attribute value

rhcsa 第四天

LabVIEW中局部变量和全局变量的分配

2022杭电中超杯(1)个人题解

Redis 3.2.3 crashed by signal: 11 服务宕机问题排查
随机推荐
Redis 3.2.3 crashed by signal: 11 服务宕机问题排查
Centos install php7.4, build hyperf, forward RDS
22牛客多校1 J.Serval and Essay (启发式合并)
pytest接口自动化测试框架 | 跳过模块
zip package all files in the directory (including hidden files/folders)
华为深度学习课程第六、七章
如何使用Photoshop合成星轨照片,夜空星轨照片后期处理方法
VoLTE基础学习系列 | 企业语音网简述
What do the values 1, 2, and 3 in nodetype mean?
基于百度OCR的网站验证码在线识别
配置我的kitty
微信小程序请求封装
Golang: go get url and form attribute value
Go 支持 OOP: 用 struct 代替 class
【手撕AHB-APB Bridge】~ AHB地址总线的低两位为什么不用来表示地址呢?
根据指定区域内容生成图片并进行分享总结
2022杭电多校第二场1011 DOS Card(线段树)
好的plm软件有哪些?plm软件排行榜
Vim三种模式
22 Grab the Seat 1 C.Grab the Seat (Geometry + Violence)
