Java实现有向图的拓扑排序
生活随笔
收集整理的這篇文章主要介紹了
Java实现有向图的拓扑排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.拓撲排序
對一個有向無環圖(Directed Acyclic Graph簡稱DAG)G進行拓撲排序,是將G中所有頂點排成一個線性序列,使得圖中任意一對頂點u和v,若邊<u,v>∈E(G),則u在線性序列中出現在v之前。通常,這樣的線性序列稱為滿足拓撲次序(Topological Order)的序列,簡稱拓撲序列
2.實現方法
利用二維數組保存有向圖,重復邊過濾,有邊的話map[i][j]=1,i到j存在著邊,用一個indegree數組保存每個節點的入度信息,
從度為0的節點開始,入棧,若棧不為空,出棧,當前元素到其他元素若存在邊,去除這條邊,map[i][j]=0,此外,讓邊的末尾節點入度減1,若減為0,則重新入棧,并且將此頂點入度去掉
3.代碼實現
package 有向圖的拓撲排序;import java.util.ArrayList; import java.util.Scanner; import java.util.Stack;/*** @Author:likui* @PacakgeName:test* @Description: 拓撲排序* 3 1 5 21 10 孩子節點* 0 3 3 1 5 父節點* 3 指定節點* @Date:Created in 9:04 2019/9/7*/public class Main {public static void way(int []x,int y[],int pos,int max){int indegree[]=new int[max];//保存每個頂點的入度信息int map[][]=new int[max][max];//保存整個有邊的圖for (int i = 0; i <x.length ; i++) {if (x[i]==0||y[i]==0)//去掉頂點為0的輸入,過濾條件continue;else{if (map[x[i]-1][y[i]-1]==0){//保存邊,重復邊去掉,map[i][j]=1,說明有i到j的有向邊map[x[i]-1][y[i]-1]=1;indegree[y[i]-1]++;}}}System.out.println("拓撲排序結果:");System.out.println(BFS(indegree,map,pos));}private static ArrayList<Integer> BFS(int []indegree,int[][] map,int pos) {ArrayList<Integer> list=new ArrayList<>();//保存拓撲排序Stack<Integer> stack = new Stack<>();//indegree[pos-1]=-1; //從指定位置開始進行拓撲排序for (int i = 0; i <map.length ; i++) {//去掉沒有邊的節點的圖for (int j = 0; j <map.length ; j++) {if (map[i][j]!=0&&indegree[i]==0&&i==pos-1){stack.push(i);//將入度為0的節點入棧indegree[i] = -1;}}}/* for (int i = 0; i < indegree.length; i++) {//整個圖的拓撲排序,包含沒有邊的節點if (indegree[i] == 0) {stack.push(i);indegree[i] = -1;}}*/while (!stack.isEmpty()) {//若棧不為空int p = stack.pop();//出棧// count++;list.add(p+1);//訪問當前元素for (int j = 0; j < indegree.length; j++) {if (map[p][j] == 1) {//當前度為0的節點到其他頂點有邊map[p][j] = 0;//去掉這條邊indegree[j]--;//變得末尾節點入度減1if (indegree[j] == 0) {//如果度減為0,入棧stack.push(j);indegree[j] = -1;//沒有入度信息}}}}return list;}public static void main(String[] args) {Scanner sc=new Scanner(System.in);String s1=sc.nextLine();String s2=sc.nextLine();int pos=Integer.parseInt(sc.nextLine());String str1[]=s1.split(" ");String str2[]=s2.split(" ");int x[]=new int[str1.length];int y[]=new int[str2.length];int max1=Integer.MIN_VALUE;int max2=Integer.MIN_VALUE;for (int i = 0; i <x.length ; i++) {x[i]=Integer.parseInt(str2[i]);y[i]=Integer.parseInt(str1[i]);max1=Math.max(y[i],max1);max2=Math.max(x[i],max2);}max1=Math.max(max1,max2);way(x,y,pos,max1);}}4.輸出測試用例結果,0代表不存在的節點
?
總結
以上是生活随笔為你收集整理的Java实现有向图的拓扑排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用BlockingQueue实现生产者与
- 下一篇: IDEA中Git操作