1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-01-10 18:48:13 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
leetcode-problemset/leetcode-cn/problem (Chinese)/图中的最长环 [longest-cycle-in-a-graph].html
2022-08-26 01:03:47 +08:00

42 lines
1.7 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<p>给你一个 <code>n</code>&nbsp;个节点的 <b>有向图</b>&nbsp;,节点编号为&nbsp;<code>0</code>&nbsp;&nbsp;<code>n - 1</code>&nbsp;,其中每个节点&nbsp;<strong>至多</strong>&nbsp;有一条出边。</p>
<p>图用一个大小为 <code>n</code>&nbsp;下标从<strong>&nbsp;0</strong>&nbsp;开始的数组&nbsp;<code>edges</code>&nbsp;表示,节点 <code>i</code>&nbsp;到节点&nbsp;<code>edges[i]</code>&nbsp;之间有一条有向边。如果节点&nbsp;<code>i</code>&nbsp;没有出边,那么&nbsp;<code>edges[i] == -1</code>&nbsp;</p>
<p>请你返回图中的 <strong>最长</strong>&nbsp;环,如果没有任何环,请返回 <code>-1</code>&nbsp;</p>
<p>一个环指的是起点和终点是 <strong>同一个</strong>&nbsp;节点的路径。</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<p><img alt="" src="https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" style="width: 335px; height: 191px;" /></p>
<pre>
<b>输入:</b>edges = [3,3,4,2,3]
<b>输出去:</b>3
<b>解释:</b>图中的最长环是2 -&gt; 4 -&gt; 3 -&gt; 2 。
这个环的长度为 3 ,所以返回 3 。
</pre>
<p><strong>示例 2</strong></p>
<p><img alt="" src="https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" style="width: 171px; height: 161px;" /></p>
<pre>
<b>输入:</b>edges = [2,-1,3,1]
<b>输出:</b>-1
<b>解释:</b>图中没有任何环。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>n == edges.length</code></li>
<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>
<li><code>-1 &lt;= edges[i] &lt; n</code></li>
<li><code>edges[i] != i</code></li>
</ul>