파비의 매일매일 공부기록

2023.03.26 Today's Challenge 본문

Problem Solving/LeetCode

2023.03.26 Today's Challenge

fabichoi 2023. 3. 26. 23:45

https://leetcode.com/problems/longest-cycle-in-a-graph/

 

Longest Cycle in a Graph - LeetCode

Can you solve this real interview question? Longest Cycle in a Graph - You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n,

leetcode.com

가장 긴 사이클 구하는 문제

class Solution:
    def longestCycle(self, edges: List[int]) -> int:
        lcl = -1
        ts = 1
        nvat = [0] * len(edges)

        for n in range(len(edges)):
            if nvat[n] > 0:
                continue
            st = ts
            u = n
            while u != -1 and nvat[u] == 0:
                nvat[u] = ts
                ts += 1
                u = edges[u]
            if u != -1 and nvat[u] >= st:
                lcl = max(lcl, ts-nvat[u])
        
        return lcl
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.03.28 Today's Challenge  (0) 2023.03.28
2023.03.27 Today's Challenge  (0) 2023.03.27
2023.03.25 Today's Challenge  (0) 2023.03.25
2023.03.24 Today's Challenge  (0) 2023.03.24
2023.03.23 Today's Challenge  (0) 2023.03.23
Comments