LeetCode 1129. Shortest Path with Alternating Colors 图着色

Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.

Each [i, j] in red_edges denotes a red directed edge from node i to node j.  Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.

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 doesn't exist).

 

Example 1:

Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
Output: [0,1,-1]

Example 2:

Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
Output: [0,1,-1]

Example 3:

Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
Output: [0,-1,-1]

Example 4:

Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
Output: [0,1,2]

Example 5:

Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
Output: [0,1,1]

 

Constraints:

  • 1 <= n <= 100
  • red_edges.length <= 400
  • blue_edges.length <= 400
  • red_edges[i].length == blue_edges[i].length == 2
  • 0 <= red_edges[i][j], blue_edges[i][j] < n

----------------------------------

反应有些慢,红色最短了不一定蓝色也最短了,因为这个还WA了一次,下面是正确的codes:

class Solution:
    def shortestAlternatingPaths(self, n: int, red_edges, blue_edges):
        res = [[-1 for i in range(n)] for j in range(2)]
        graph=[[[] for j in range(n)] for i in range(2)]
        for idx in [0,1]:
            edges = red_edges if idx == 0 else blue_edges
            for edge in edges:
                frm,to = edge[0],edge[1]
                graph[idx][frm].append(to)
        layers = [[(0,0),(0,1)],[]]
        res[0][0] = res[1][0] = 0
        cur,nxt,step = 0,1,0
        while (layers[cur]):
            step += 1
            for node,color in layers[cur]:
                ncolor = 1-color
                for nnode in graph[ncolor][node]:
                    if (res[ncolor][nnode] < 0):
                        res[ncolor][nnode] = step
                        layers[nxt].append((nnode,ncolor))
            layers[cur].clear()
            cur,nxt = nxt,cur
        return [min(res[0][i],res[1][i]) if (min(res[0][i],res[1][i])>0) else max(res[0][i],res[1][i]) for i in range(n)]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值