拓扑排序代码实现

本文介绍了一种基于栈实现的拓扑排序算法,并通过具体示例展示了如何计算有向图中各节点的入度,进而完成拓扑排序过程。文章包含完整的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package datastucture;

import java.util.Stack;
/**
 * 实现拓扑排序
 * @author win7
 *
 */
public class TopologicalSort {
	/**
	 * 开始初始化入度为零的节点
	 * @param graph
	 * @param indegree
	 * @param n
	 */
	public static void findIndegree(int [][] graph,int [] indegree,int n){
		for(int i=0;i<n;i++){
			indegree[i]=0;
			for(int j=0;j<n;j++){
				if(graph[j][i]>0){
					indegree[i]++;
				}
			}
		}
	}
	/**
	 * 拓扑排序
	 * 算法思想:(1)在有向图中选择一个没有钱去的顶点且输出。(2)从图中删除该顶点和所有已他为尾的弧。
	 * 重复上面两部,直至所有的顶点均输出,或者当图中不存在无前驱的顶点为止,这时候说明图中有环。
	 * @param graph 矩阵表示的有向图
	 * @param n     有向图中节点个数
	 */
	public static void topologicalSort(int [] [] graph,int n){
		int [] indegree=new int[n];
		findIndegree(graph,indegree,n);
		Stack<Integer> s=new Stack<Integer>();
		for(int i=0;i<n;i++){
			if(indegree[i]==0){
				s.push(i);
			}	
		}
		while(!s.empty()){
			int start= s.pop();
			System.out.println("输出一个0入度节点:"+(start+1));
			for(int i=0;i<n;i++){
				if(graph[start][i]>0){
					indegree[i]--;
					if(indegree[i]==0){
						s.push(i);
					}
				}
			}
		}
		
	}
	
	public static void main(String [] args){
		int [][] graph={
				{-1,1,1,1,-1,-1},
				{-1,-1,-1,-1,-1,-1},
				{-1,1,-1,-1,1,-1},
				{-1,-1,-1,-1,1,-1},
				{-1,-1,-1,-1,-1,-1},
				{-1,-1,-1,1,1,-1}			
		};
		TopologicalSort.topologicalSort(graph, 6);
		
	}

}




在C语言中实现拓扑排序通常涉及到图论的知识,拓扑排序是对有向无环图(DAG)中顶点进行排序的一种方法,它的结果保证了所有依赖关系正确的顺序。下面是一个简单的使用邻接表表示有向图并进行拓扑排序的示例: ```c #include <stdio.h> #include <stdlib.h> // 定义节点结构体 typedef struct Node { int data; struct Node* next; } Node; // 添加边到图 void add_edge(Node** graph, int src, int dest) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = dest; newNode->next = (*graph)[src]; (*graph)[src] = newNode; } // 检查是否为根节点 int is_root(Node** graph, int node) { return !(*graph[node]); } // 找出邻居 int get_neighbors(Node** graph, int node) { Node* temp = *graph[node]; int count = 0; while (temp != NULL) { count++; temp = temp->next; } return count; } // 边数小于等于节点数的递归实现 void topological_sortUtil(Node** graph, int v, int visited[], stack_t* s, int n) { if (visited[v] == true) return; visited[v] = true; printf("%d ", v); for (int i = 0; i < n; i++) { if ((*graph)[v] != NULL && visited[i] == false && is_root(graph, i)) { topological_sortUtil(graph, i, visited, s, n); } } // push the current vertex to stack before visiting its neighbors push(s, v); } // 主函数 void topological_sort(Node** graph, int nodes) { stack_t* s = create_stack(); int visited[nodes]; // 初始化已访问数组 for (int i = 0; i < nodes; i++) visited[i] = false; for (int i = 0; i < nodes; i++) { if (is_root(graph, i)) topological_sortUtil(graph, i, visited, s, nodes); } // 如果存在环,则无法进行拓扑排序,所以此处会出错 if (!isEmpty(s)) { printf("Graph has a cycle\n"); destroy_stack(s); return; } printf("\nTopological Sort of given graph:\n"); print_postorder(s); destroy_stack(s); } // 测代码 int main() { int vertices[] = {5, 4, 3, 2, 1}; Node** graph = (Node**)malloc(sizeof(Node*) * 6); // 创建一个大小为6的动态邻接表 // 添加边 add_edge(&graph[0], 1, 2); add_edge(&graph[0], 2, 3); add_edge(&graph[0], 3, 4); add_edge(&graph[1], 4, 5); int n = sizeof(vertices) / sizeof(vertices[0]); topological_sort(graph, n); return 0; } ``` 在这个例子中,我们首先创建了一个邻接表来存储图,然后通过递归的topological_sortUtil函数进行拓扑排序。如果检测到环,则说明图不是有向无环图,无法进行拓扑排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WitsMakeMen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值