亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用卡恩算法求解 CouseSchedule 的拓撲排序中的 indegrees

用卡恩算法求解 CouseSchedule 的拓撲排序中的 indegrees

慕村225694 2021-12-26 10:12:30
我正在學習解決 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 從考慮這對獲得入度。


查看完整回答
反對 回復 2021-12-26
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號