【发布时间】: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