엔지니어 게시판
LeetCode 솔루션 분류

[2/11] 1129. 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 two arrays redEdges and blueEdges where:

  • redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and
  • blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.

Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.

 

Example 1:

Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []
Output: [0,1,-1]

Example 2:

Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
Output: [0,1,-1]

 

Constraints:

  • 1 <= n <= 100
  • 0 <= redEdges.length, blueEdges.length <= 400
  • redEdges[i].length == blueEdges[j].length == 2
  • 0 <= ai, bi, uj, vj < n
Accepted
58K
Submissions
129.9K
<div class="bg-divider-2 dark:bg-dark-divider-2 h-full w-px border-divider-1 dark:border-dark-divider-1 mr-4 max-h-[14px]" style="border: 0px solid rgba(
태그

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
from collections import defaultdict, deque
class Solution:
    def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:

        blue = defaultdict(list)
        red = defaultdict(list)

        for v1, v2 in redEdges:
            red[v1].append(v2)
        for v1, v2 in blueEdges:
            blue[v1].append(v2)

        res = [-1]*n
        res[0] = 0

        queue = deque([(0,0,1), (0,0,-1)])
        visited = set()

        while queue:
            node, dis, color = queue.popleft()
            if res[node] == -1: res[node] = dis 
            visited.add((node,color))
            if color == 1:
                for nxt in red[node]:
                    if (nxt, color*-1) not in visited: queue.append((nxt,dis+1, color*-1))
            else:
                for nxt in blue[node]:
                    if (nxt, color*-1) not in visited: queue.append((nxt,dis+1, color*-1))
        
        return res
전체 396 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 156 명
  • 오늘 방문자 2,947 명
  • 어제 방문자 5,697 명
  • 최대 방문자 11,134 명
  • 전체 회원수 1,093 명
알림 0