我正在學習解決 leetcode 中的拓撲排序問題您總共需要學習n門課程,標記為 from0到n-1。有些課程可能有先決條件,例如要參加課程 0,您必須先參加課程 1,這表示為一對: [0,1]鑒于課程總數和先決條件對列表,您是否有可能完成所有課程?示例 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.筆記:輸入先決條件是由邊列表表示的圖,而不是鄰接矩陣。閱讀有關如何表示圖形的更多信息。您可以假設輸入先決條件中沒有重復的邊。我在討論區閱讀了以下拓撲排序解決方案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 ,節點 u 有一個出度,而節點 v 有一個入度。所以我認為,in_degrees[u] += 1應該改為in_degrees[v] += 1 因為如果存在 (u,v),那么 v 至少有一個傳入事件和一個入度In degree:這僅適用于有向圖。這表示傳入頂點的邊數。但是,原始解決方案有效。我的理解有什么問題?
1 回答

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