当前位置:网站首页>【Leetcode】2360. Longest Cycle in a Graph
【Leetcode】2360. Longest Cycle in a Graph
2022-08-01 23:47:00 【记录算法题解】
题目地址:
https://leetcode.com/problems/longest-cycle-in-a-graph/
给定一个 n n n个点的有向图,每个点最多只有一条出边。给定每个点的出边指向的点,如果不存在则以 − 1 -1 −1标记。求长度最大的环的长度。若不存在环,则返回 − 1 -1 −1。
当然可以直接用Tarjan求一下最大的强联通分量。由于每个点只有一条出边,所以每个点只会存在于一个环中,从而可以直接模拟,直接从每个点出发,并且做标记,同时用一个哈希表记录步数。代码如下:
class Solution {
public:
int longestCycle(vector<int>& e) {
int n = e.size();
vector<bool> vis(n);
int res = -1;
for (int i = 0; i < n; i++) {
if (!vis[i]) {
unordered_map<int, int> mp;
int x = i, time_stamp = 0;
while (true) {
mp[x] = ++time_stamp;
vis[x] = true;
// 找到环了
if (mp.count(e[x])) {
res = max(res, mp[x] - mp[e[x]] + 1);
break;
}
// 走到了死胡同
if (e[x] == -1 || vis[e[x]]) break;
// 向后走一步
x = e[x];
}
}
}
return res;
}
};
时空复杂度 O ( n ) O(n) O(n)。
边栏推荐
猜你喜欢
随机推荐
Work for 5 years, test case design is bad?To look at the big case design summary
Chapter 11 Working with Dates and Times
Quartus 使用 tcl 文件快速配置管脚
Classical Literature Reading--DLO
6133. 分组的最大数量
Special characters & escapes in bat
chrome copies the base64 data of an image
How do programmers solve online problems gracefully?
Spark Sql之union
Additional Features for Scripting
yay 报错 response decoding failed: invalid character ‘<‘ looking for beginning of value;
架构基本概念和架构本质
20220725 Information update
What is CICD excuse me
cdh6 opens oozieWeb page, Oozie web console is disabled.
Always use "noopener" or "noreferrer" for links that open in a new tab
UI自动化测试框架搭建-标记性能较差用例
Chrome书签插件,让你实现高效整理
经典文献阅读之--DLO
@WebServlet注解(Servlet注解)








