拓扑排序算法实现

x33g5p2x  于2022-07-19 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(484)

一 拓扑图

二 实现

  1. package graph.topoSort;
  2. import java.util.Scanner;
  3. import java.util.Stack;
  4. public class TopoSort {
  5. static final int maxn = 105;
  6. static int map[][] = new int[maxn][maxn];
  7. static int indegree[] = new int[maxn];
  8. static int topo[] = new int[maxn];
  9. static int n, m;
  10. static Stack<Integer> s = new Stack<>();
  11. static boolean TopoSort() { // 拓扑排序
  12. int cnt = 0;
  13. for (int i = 0; i < n; i++)
  14. if (indegree[i] == 0)
  15. s.push(i);
  16. while (!s.empty()) {
  17. int u = s.peek();
  18. s.pop();
  19. topo[cnt++] = u;
  20. for (int j = 0; j < n; j++)
  21. if (map[u][j] == 1)
  22. if (--indegree[j] == 0)
  23. s.push(j);
  24. }
  25. if (cnt < n) {
  26. return false;
  27. }
  28. return true;
  29. }
  30. public static void main(String[] args) {
  31. Scanner scanner = new Scanner(System.in);
  32. n = scanner.nextInt();
  33. m = scanner.nextInt();
  34. for (int i = 0; i < m; i++) {
  35. int u, v;
  36. u = scanner.nextInt();
  37. v = scanner.nextInt();
  38. map[u][v] = 1;
  39. indegree[v]++;
  40. }
  41. TopoSort();
  42. for (int i = 0; i < n - 1; i++)
  43. System.out.print(topo[i] + " ");
  44. System.out.println(topo[n - 1]);
  45. }
  46. }

三 测试

相关文章