<p>You are given a <strong>directed</strong> graph of <code>n</code> nodes numbered from <code>0</code> to <code>n - 1</code>, where each node has <strong>at most one</strong> outgoing edge.</p>

<p>The graph is represented with a given <strong>0-indexed</strong> array <code>edges</code> of size <code>n</code>, indicating that there is a directed edge from node <code>i</code> to node <code>edges[i]</code>. If there is no outgoing edge from node <code>i</code>, then <code>edges[i] == -1</code>.</p>

<p>Return <em>the length of the <strong>longest</strong> cycle in the graph</em>. If no cycle exists, return <code>-1</code>.</p>

<p>A cycle is a path that starts and ends at the <strong>same</strong> node.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/06/08/graph4drawio-5.png" style="width: 335px; height: 191px;" />
<pre>
<strong>Input:</strong> edges = [3,3,4,2,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest cycle in the graph is the cycle: 2 -&gt; 4 -&gt; 3 -&gt; 2.
The length of this cycle is 3, so 3 is returned.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/06/07/graph4drawio-1.png" style="width: 171px; height: 161px;" />
<pre>
<strong>Input:</strong> edges = [2,-1,3,1]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no cycles in this graph.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</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>

class Solution:
    def longestCycle(self, edges: List[int]) -> int:
        longest_cycle_length = -1  # 用來存儲最長的環長度，如果沒有找到環則返回 -1

        for start_node in range(len(edges)):  # 遍歷所有節點
            current_node = start_node  # 從當前節點開始
            path = []  # 儲存當前路徑中的節點
            while edges[current_node] >= 0:  # 只要當前節點有出邊且還未被訪問過
                path.append(current_node)  # 將當前節點加入路徑中
                next_node = edges[current_node]  # 找到下一個節點
                edges[current_node] = -1  # 標記當前節點為已訪問
                current_node = next_node  # 移動到下一個節點
            # 當環路形成時（即當前節點已經出現在當前的路徑中）
            if current_node in path:
                # 環的長度是從當前節點第一次出現的位置到路徑末尾的長度
                cycle_start_index = path.index(current_node)
                cycle_length = len(path) - cycle_start_index
                longest_cycle_length = max(longest_cycle_length, cycle_length)  # 更新最長環長度

        return longest_cycle_length  # 返回最長環的長度（或 -1 如果沒有環）

316