파비의 매일매일 공부기록

2023.04.09 Today's Challenge 본문

Problem Solving/LeetCode

2023.04.09 Today's Challenge

fabichoi 2023. 4. 9. 23:45

https://leetcode.com/problems/largest-color-value-in-a-directed-graph/

 

Largest Color Value in a Directed Graph - LeetCode

Can you solve this real interview question? Largest Color Value in a Directed Graph - There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English let

leetcode.com

토폴로지 정렬 활용하는 문제

class Solution:
    def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
        n, k = len(colors), 26
        indegrees = [0] * n
        graph = [[] for _ in range(n)]

        for u, v in edges:
            graph[u].append(v)
            indegrees[v] += 1
        
        zero_indegree = set(i for i in range(n) if indegrees[i] == 0)
        counts = [[0] * k for _ in range(n)]

        for i, c in enumerate(colors):
            counts[i][ord(c) - ord('a')] += 1
        
        max_count, visited = 0, 0

        while zero_indegree:
            u = zero_indegree.pop()
            visited += 1

            for v in graph[u]:
                for i in range(k):
                    counts[v][i] = max(counts[v][i], counts[u][i] + (ord(colors[v]) - ord('a') == i))
                indegrees[v] -= 1
                if indegrees[v] == 0:
                    zero_indegree.add(v)
            
            max_count = max(max_count, max(counts[u]))
        
        return max_count if visited == n else -1
반응형

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

2023.04.11 Today's Challenge  (0) 2023.04.11
2023.04.10 Today's Challenge  (0) 2023.04.10
2023.04.08 Today's Challenge  (0) 2023.04.08
2023.04.07 Today's Challenge  (0) 2023.04.07
2023.04.06 Today's Challenge  (0) 2023.04.06
Comments