Lintcode127 Topological Sorting solution 題解

【題目描述】

Given an directed graph, a topological order of the graph nodes is defined as follow:

·For each directed edgeA -> Bin graph, A must before B in the order list.

·The first node in the order can be any node in the graph with no nodes direct to it.

Find any topological order for the given graph.

給定一個有向圖,圖節點的拓撲排序被定義爲:

·對於每條有向邊A--> B,則A必須排在B之前

·拓撲排序的第一個節點可以是任何在圖中沒有其他節點指向它的節點

找到給定圖的任一拓撲排序

【注】:你可以假設圖中至少存在一種拓撲排序

【題目鏈接】

[www.lintcode.com/en/problem/topological-sorting/]()

【題目解析】

1) 計算所有點的入度,用HashMap保存。

2) 將入度爲0的點加入queue中和result中,將queue中節點出隊,將出隊節點所有neighbor的入度減少1。

3) 重複2直到所有點都被加入result中。

需要注意的是,如果有對HashMap做刪除操作,不能再用原來的迭代器繼續迭代,需要從頭用新的迭代器進行迭代。

【參考答案】

[www.jiuzhang.com/solutions/topological-sorting/]()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章