我正在尝试使用C#在Adjacency List
中表示一个图表,如下面的代码所示。
但我想知道在哪里可以找到更好的C#实现。
像这个Java网站:http://algs4.cs.princeton.edu/41undirected/Graph.java.html
为了改进这个实现,我有一些问题:
DFS
,BFS
,Find the Shortest-path
等操作?或者根据要解决的问题,数据结构变化太大了? === EDITED ===
我试图将数据结构实现如下。
OBS :这种方法看起来很简单,但我后来才意识到它不太适合DFS,例如,因为你需要跟踪LinkedList
的第一个元素所有的时间。在我的解决方案中似乎最好使用自定义创建的链接列表,而不是
LinkedList<Vertex>
。
考虑到下面的评论并保持简洁,我做了一些改变。但我不知道这些变化是否会影响进一步的操作,例如BFS
。
为了能够拥有直接和间接的图表,我认为使用接口比使用属性更好。
public interface IGraph
{
void InsertEdge(int edgeAKey, int edgeBKey);
void IsertNewVertex(int vertexKey);
LinkedList<Vertex> FindByKey(int vertexKey);
bool ExistKey(int vertexKey);
}
为了使其尽可能简单,我们可以使用已经实现的数据结构,如Dictionary
和LinkedList
。而不是使用object
作为Dictionary key
,为了简单起见,我们可以在Vertex
key
(或label
)和{{1}中创建},如果您想添加另一个value
中已存在的值。
Vertex
Vertex类不需要任何其他指针,只需要保留public class GraphDirect : IGraph
{
private Dictionary<int,LinkedList<Vertex>> Vertexes { get; set; }
public GraphDirect()
{
Vertexes = new Dictionary<int, LinkedList<Vertex>>();
}
public bool ExistKey(int vertexKey)
{
if (this.FindByKey(vertexKey) == null)
return false;
else
return true;
}
public void IsertNewVertex(int vertexKey)
{
if (!this.ExistKey(vertexKey))
{
Vertex vertex = new Vertex(vertexKey);
LinkedList<Vertex> listVertexes = new LinkedList<Vertex>();
listVertexes.AddFirst(vertex);
this.Vertexes.Add(vertexKey, listVertexes);
}
}
public void InsertEdge(int vertexAKey, int vertexBKey)
{
//Create the vertex A, if it doesn't exist
if (!this.ExistKey(vertexAKey))
{
this.IsertNewVertex(vertexAKey);
}
//Will always insert the vertex B on this edge
this.FindByKey(vertexAKey).AddLast(new Vertex(vertexBKey));
//Create the vertex B, if doesn't exist
if (!this.ExistKey(vertexBKey))
{
this.IsertNewVertex(vertexBKey);
}
}
public LinkedList<Vertex> FindByKey(int vertexKey)
{
if (this.Vertexes.ContainsKey(vertexKey))
return this.Vertexes[vertexKey];
return null;
}
}
和key
。
value