DFS和BFS程序的有用C#类/方法

DFS和BFS程序的有用C#类/方法,c#,data-structures,collections,depth-first-search,breadth-first-search,C#,Data Structures,Collections,Depth First Search,Breadth First Search,我有一个包含节点及其连接的XML文件。比如: <Graph> <Node Name = "A"> <ConnectsTo>B</ConnectsTo> <ConnectsTo>H</ConnectsTo> </Node> <Node Name="B"></Node> <Node Name="C"> <ConnectsTo>E&

我有一个包含节点及其连接的XML文件。比如:

<Graph>
  <Node Name = "A">
    <ConnectsTo>B</ConnectsTo>
    <ConnectsTo>H</ConnectsTo>
  </Node>
  <Node Name="B"></Node>
  <Node Name="C">
    <ConnectsTo>E</ConnectsTo>
  </Node>
  <Node Name="D">
    <ConnectsTo>C</ConnectsTo>
  </Node>
  <Node Name="E"></Node>
  <Node Name="F">
    <ConnectsTo>D</ConnectsTo>
    <ConnectsTo>G</ConnectsTo>
  </Node>
  <Node Name="G">
    <ConnectsTo>E</ConnectsTo>
    <ConnectsTo>I</ConnectsTo>
  </Node>
  <Node name="H">
    <ConnectsTo>C</ConnectsTo>
    <ConnectsTo>J</ConnectsTo>
    <ConnectsTo>G</ConnectsTo>
  </Node>
  <Node name="I">
    <ConnectsTo>E</ConnectsTo>
  </Node>
  <Node name="J">
    <ConnectsTo>A</ConnectsTo>
  </Node>
</Graph>
我是否在重新安排层次结构中的第一个节点的正确轨道上?哪些类对此(重新安排和未来的过程)有用?
图形的子类
LinkedList

是否会生成以下结果:

Choose (1)DFS (2)BFS : 1
Choose Starting Vertex : A

Result :
不可能

A B
A B H
A B H J
A B H J C
A B H J C E
A B H J C E G
A B H J C E G I
??? 也许我已经忘记了如何进行DFS,但我的理解是,您在“树”中尽可能深入,然后仅在当前节点没有更多节点可遍历时返回到前一个节点。在此过程中不应丢失任何节点


答:我可能只是将LinkedList用作堆栈,这应该可以很好地满足您的需要。

但是,根据您的具体要求,您可能不需要为遍历编写任何自定义代码。允许您对XML数据使用熟悉的LINQ方法。这是我的建议,除非您有明确使用DFS或BFS的自定义需求

如果你必须做DFS或BFS,这很容易。据我所知,没有任何内置的方法可以让你做一个或另一个。但它们并不难写。标准数据结构就是您所需要的全部。深度优先遍历通常通过递归完成:

void Dfs(NodeType node)
{
    foreach (var child in node.Children)
    {
        Dfs(child);
    }
    // here, output node information
}
执行宽度优先遍历的最简单方法是使用队列:

void Bfs(NodeType node)
{
    var theQueue = new Queue<NodeType>();
    theQueue.Enqueue(node);
    while (theQueue.Count > 0)
    {
        var n = theQueue.Dequeue();
        // output node data
        // then add each child to the queue
        foreach (var child in n.Children)
        {
            theQueue.Enqueue(child);
        }
    }
}
void Bfs(节点类型节点)
{
var theQueue=新队列();
排队(节点);
while(theQueue.Count>0)
{
var n=theQueue.Dequeue();
//输出节点数据
//然后将每个子级添加到队列中
foreach(n.Children中的var child)
{
队列。排队(子级);
}
}
}

如果您正在搜索,那么您将插入比较代码,而不是“输出节点数据”,如果您希望在找到第一个项目后退出,则可能会提前退出。

如果可以使用
System.Collections.Generic.stack
,为什么要使用链表作为堆栈?因为我不知道有一个!我对C比较陌生#
void Bfs(NodeType node)
{
    var theQueue = new Queue<NodeType>();
    theQueue.Enqueue(node);
    while (theQueue.Count > 0)
    {
        var n = theQueue.Dequeue();
        // output node data
        // then add each child to the queue
        foreach (var child in n.Children)
        {
            theQueue.Enqueue(child);
        }
    }
}