【Python排序搜尋基本演算法】之拓撲排序

來源:互聯網
上載者:User

        拓撲排序是對有向非循環圖的一種排序,滿足如下兩個條件:

1.每個頂點出現且只出現一次;

2.若A在序列中排在B的前面,則在圖中不存在從B到A的路徑。



如上的無環有向圖,v表示頂點:v=['a','b','c','d','e'],e表示有向邊:e=[('a','b'),('a','d'),('b','c'),('d','c'),('d','e'),('e','c')],代碼如下:

def indegree0(v,e): if v==[]:return Nonetmp=v[:]for i in e:if i[1] in tmp:tmp.remove(i[1])if tmp==[]:return -1for t in tmp:for i in range(len(e)):if t in e[i]:e[i]='toDel' #佔位,之後刪掉if e:eset=set(e)eset.remove('toDel')e[:]=list(eset)if v:for t in tmp:v.remove(t)return tmpdef topoSort(v,e):result=[]while True:nodes=indegree0(v,e)if nodes==None:breakif nodes==-1:print('there\'s a circle.')return Noneresult.extend(nodes)return resultv=['a','b','c','d','e']e=[('a','b'),('a','d'),('b','c'),('d','c'),('d','e'),('e','c')]res=topoSort(v,e)print(res)

indegree0函數返回入度為0的頂點,並在v和e中刪除它和它相鄰的邊,如果v列表中沒有頂點了,就返回None,如果v列表中還有頂點但是找不到入度為0的頂點,說明有向圖中有環,返回-1。topoSort函數不斷取出有向圖中入度為0的頂點,最後就是拓撲排序序列。輸出如下:

['a', 'b', 'd', 'e', 'c']

        考慮一種有環的情況,加上一條c->d的邊,如所示:


輸出如下:

there's a circle.None

轉載請註明:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.