CShap 图的拓扑排序 源代码
时间: 2023-11-03 10:04:28 浏览: 236
下面是C#中实现图的拓扑排序的源代码:
```csharp
using System;
using System.Collections.Generic;
namespace TopologicalSort
{
class Graph
{
private int V; // 顶点的数量
private List<int>[] adj; // 邻接表
public Graph(int v)
{
V = v;
adj = new List<int>[v];
for (int i = 0; i < v; i++)
{
adj[i] = new List<int>();
}
}
// 添加边
public void AddEdge(int v, int w)
{
adj[v].Add(w);
}
// 拓扑排序
public void TopologicalSort()
{
// 统计每个顶点的入度
int[] indegree = new int[V];
for (int i = 0; i < V; i++)
{
List<int> adjList = adj[i];
foreach (int vertex in adjList)
{
indegree[vertex]++;
}
}
// 创建一个队列,用于存储入度为0的顶点
Queue<int> queue = new Queue<int>();
for (int i = 0; i < V; i++)
{
if (indegree[i] == 0)
{
queue.Enqueue(i);
}
}
// 从队列中弹出顶点并输出
int count = 0;
List<int> result = new List<int>();
while (queue.Count > 0)
{
int vertex = queue.Dequeue();
result.Add(vertex);
foreach (int adjVertex in adj[vertex])
{
indegree[adjVertex]--;
if (indegree[adjVertex] == 0)
{
queue.Enqueue(adjVertex);
}
}
count++;
}
// 判断是否存在环
if (count != V)
{
Console.WriteLine("图中存在环!");
}
else
{
// 输出拓扑排序结果
Console.WriteLine("拓扑排序结果:");
foreach (int vertex in result)
{
Console.Write(vertex + " ");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Graph g = new Graph(6);
g.AddEdge(5, 2);
g.AddEdge(5, 0);
g.AddEdge(4, 0);
g.AddEdge(4, 1);
g.AddEdge(2, 3);
g.AddEdge(3, 1);
g.TopologicalSort();
Console.ReadKey();
}
}
}
```
阅读全文