파비의 매일매일 공부기록

2023.02.11 Today's Challenge 본문

Problem Solving/LeetCode

2023.02.11 Today's Challenge

fabichoi 2023. 2. 11. 23:45

https://leetcode.com/problems/shortest-path-with-alternating-colors/

 

Shortest Path with Alternating Colors - LeetCode

Shortest Path with Alternating Colors - You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given

leetcode.com

BFS로 풀면 되는 문제!

class Solution:
    def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:
        graph = [[[], []] for i in range(n)]
        for s, e in redEdges:
            graph[s][0].append(e)
        for s, e in blueEdges:
            graph[s][1].append(e)

        dis = [[0, 0]] + [[float('inf'), float('inf')] for i in range(n-1)]
        qu = [[0, 0], [0, 1]]

        for node, color in qu:
            for nei in graph[node][color]:
                if dis[nei][color] == float('inf'):
                    dis[nei][color] = dis[node][1-color] + 1
                    qu.append([nei, 1-color])
        return [d if d < float('inf') else -1 for d in map(min, dis)]

 

반응형

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

2023.02.13 Today's Challenge  (0) 2023.02.13
2023.02.12 Today's Challenge  (0) 2023.02.12
2023.02.10 Today's Challenge  (0) 2023.02.10
2023.02.09 Today's Challenge  (0) 2023.02.09
2023.02.08 Today's Challenge  (0) 2023.02.08
Comments