【问题标题】:Problem with Leetcode problem 1129. Shortest Path with Alternating ColorsLeetcode 问题 1129 的问题。具有交替颜色的最短路径
【发布时间】:2023-02-11 16:07:40
【问题描述】:

我对那个 leetcode 问题有疑问: https://leetcode.com/problems/shortest-path-with-alternating-colors/ 这是我针对该问题的代码:

class Solution:
    def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:

        res = [0] + [-1]*(n-1)

        Red = defaultdict(list)
        Blue = defaultdict(list)

        for x,y in redEdges:
            if x!=0 or y!=0: 
                Red[x].append(y)

        for x,y in blueEdges:
            if x!=0 or y!=0:
                Blue[x].append(y)


        def dfs(vertex,color,cost):
        
            if color == "red":
                for x in Red[vertex]:
                    if res[x] != -1:
                        res[x] = min(cost,res[x])
                    else:
                        res[x] = cost

                    if vertex in Red.keys():
                        del Red[vertex]
                    dfs(x,"blue",cost+1)


            else:
                for x in Blue[vertex]:
                    if res[x] != -1:
                        res[x] = min(cost,res[x])
                    else:
                        res[x] = cost

                    if vertex in Blue.keys():
                        del Blue[vertex]
                    dfs(x,"red",cost+1)

        dfs(0,"red",1)
        dfs(0,"blue",1)

        return res

enter image description here 我不知道为什么那里有错误的价值 我认为它可能与 [0,0] 边缘有关,但它似乎对解决方案没有影响。

【问题讨论】:

  • 问题应该是独立的。目前没有问题描述。尽管链接对于背景信息很有用,但基本信息应该在您的问题中。

标签: python-3.x algorithm data-structures depth-first-search


【解决方案1】:

问题是您的代码删除了它访问过的顶点,但在回溯时没有恢复它。有可能从0号顶点到刚刚删除的那条路还需要遍历,而且是更短的路。

以下是演示问题的示例输入:

redEdges = [[0,1],[2,3],[0,3]]
blueEdges = [[1,2],[3,4]]

您的代码将正确创建以下邻接列表:

Red = {0: [1, 3], 2: [3]}
Blue = {1: [2], 3: [4]}

使用dfs,路径 0、1、2、3、4 将被访问,在此遍历期间,这些字典中的所有键都将被删除。由于从 0 开始的传出边上的循环仍然处于活动状态,dfs 仍将遵循从 0 到 3 的红色边缘,但在那里它找不到蓝色边缘,因为键 3 不再存在。因此算法看不到从 0 到 4 的最短路径,即 0、3、4。

不是你的问题,但 BFS 更适合寻找最短的路径。我建议您修改算法并改用 BFS。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多