我正在學(xué)習(xí)解決 leetcode 中的拓?fù)渑判騿栴}您總共需要學(xué)習(xí)n門課程,標(biāo)記為 from0到n-1。有些課程可能有先決條件,例如要參加課程 0,您必須先參加課程 1,這表示為一對: [0,1]鑒于課程總數(shù)和先決條件對列表,您是否有可能完成所有課程?示例 1:Input: 2, [[1,0]] Output: trueExplanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.示例 2:Input: 2, [[1,0],[0,1]]Output: falseExplanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.筆記:輸入先決條件是由邊列表表示的圖,而不是鄰接矩陣。閱讀有關(guān)如何表示圖形的更多信息。您可以假設(shè)輸入先決條件中沒有重復(fù)的邊。我在討論區(qū)閱讀了以下拓?fù)渑判蚪鉀Q方案class Solution5: def canFinish(self,numCourses, prerequirements): """ :type numCourse: int :type prerequirements: List[List[int]] :rtype:bool """ if not prerequirements: return True count = [] in_degrees = defaultdict(int) graph = defaultdict(list) for u, v in prerequirements: graph[v].append(u) in_degrees[u] += 1 #Confused here queue = [u for u in graph if in_degrees[u]==0] while queue: s = queue.pop() count.append(s) for v in graph(s): in_degrees[v] -= 1 if in_degrees[v] ==0: queue.append(v) #check there exist a circle for u in in_degrees: if in_degrees[u]: return False return True 我很困惑 in_degrees[u] += 1for u, v in prerequirements: graph[v].append(u) in_degrees[u] += 1 #Confused here對于有向邊 (u,v) , u -----> v ,節(jié)點(diǎn) u 有一個(gè)出度,而節(jié)點(diǎn) v 有一個(gè)入度。所以我認(rèn)為,in_degrees[u] += 1應(yīng)該改為in_degrees[v] += 1 因?yàn)槿绻嬖?(u,v),那么 v 至少有一個(gè)傳入事件和一個(gè)入度In degree:這僅適用于有向圖。這表示傳入頂點(diǎn)的邊數(shù)。但是,原始解決方案有效。我的理解有什么問題?
1 回答

元芳怎么了
TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊
看上面那一行;graph[v].append(u)
. 邊緣實(shí)際上與您的假設(shè)和輸入格式相反。這是因?yàn)閷τ谕負(fù)渑判?,我們希望沒有依賴關(guān)系/傳入邊的事物最終位于結(jié)果順序的前面,因此我們根據(jù)解釋引導(dǎo)邊,“是一個(gè)要求”而不是“要求”。例如。輸入對 (0,1) 意味著 0 需要 1,因此在圖中我們繪制了一條有向邊 (1,0),以便在我們的排序中 1 可以在 0 之前。因此 0 從考慮這對獲得入度。
添加回答
舉報(bào)
0/150
提交
取消