您好,登錄后才能下訂單哦!
本篇內容介紹了“c++怎么實現拓撲排序”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
package com.lifeibigdata.algorithms.google; /** * Created by lifei on 16/5/23. */ import java.util.ArrayList; import java.util.List; /** * 此處的拓撲排序是通過DFS的f[]降序排列。 * 另一種實現方法是不斷拿走入度為0的點 * @author xiazdong * */ public class TopologicalSort_Algorithm { private static final int WHITE = 0; private static final int GRAY = 1; private static final int BLACK = 2; private int color[]; private int size; private int f[]; private int time; private Adjacent_List G; //鄰接表 private List<String> resultList; //存儲拓撲排序的值的序列 public TopologicalSort_Algorithm(Adjacent_List G){ this.G = G; size = G.getSize(); color = new int[size]; f = new int[size]; time = 0; resultList = new ArrayList<String>(); for(int i=0;i<color.length;i++) color[i] = WHITE; } public List<String> getResultList() { return resultList; } public String[] TopologicalSort(){ DFS(); return resultList.toArray(new String[0]); } public void DFS(){ for(int i=0;i<size;i++){ if(color[i]==WHITE){ DFS_VISIT(i); } } } private void DFS_VISIT(int i) { color[i] = GRAY; time++; for(int j=0;j<G.getListByVertexIndex(i).size();j++){ String value = G.getListByVertexIndex(i).get(j); int index = G.getVertexIndex(value); if(color[index]==WHITE){ DFS_VISIT(index); } } time++; f[i] = time; resultList.add(0, G.getVertexValue(i)); //將f[i]值加入到隊列的頭部 color[i] = BLACK; } public static void main(String[] args) throws Exception { Adjacent_List adjacent_list = GraphFactory.getAdjacentListInstance("/Users/lifei/myproject/algorithms/input/topo_input.txt"); TopologicalSort_Algorithm alg = new TopologicalSort_Algorithm(adjacent_list); String[]result = alg.TopologicalSort(); for(String e:result) System.out.print(e+" "); } /** * 3 3 1 2 2 3 1 3 */ }
“c++怎么實現拓撲排序”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。