非递归深度优先搜索行为几乎像c#

时间:2013-12-05 13:23:51

标签: c# depth-first-search

我正在尝试在c#中实现非递归DFS算法   这是我的方法代码

public void dfs(int vertex)
{
   int length = matrix.GetLength(0);
   bool[] visited = new bool[length]; 
   for (int k = 0; k < length; k++)
   {
     visited[k] = false; 
   }
   Stack<int> vertexStack = new Stack<int>();
   vertexStack.Push(vertex);
   visited[vertex] = true;
   Console.Write((vertex) + " ");
   while (vertexStack.Count() != 0)
   {
        int tempVertex = vertexStack.Peek();
        for (int j = 0; j < length; j++)
        {
            if (matrix[tempVertex, j] == 1 && !visited[j])
            {
                Console.Write(j + " ");
                visited[j] = true;
                vertexStack.Push(j);
            }
        }
        vertexStack.Pop();    
   }
}

这是我的图表代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
   {
    static void Main(string[] args)
    {

        int[,] matrix2 = {
        {0,1,1,1,0,0},
        {1,0,0,0,1,1},
        {1,0,0,0,0,1},
        {1,0,0,0,0,0},
        {0,1,0,0,0,0},
        {0,1,1,0,0,0},
                         };
        Graphs g2 = new Graphs(matrix2);
        g2.dfs(0);
       // Console.ReadKey();
     }
   }
}

对于此图,dfs的结果应为0 1 4 5 2 3

但它们是0 1 2 3 5 4,这几乎就像这张图的BFS 0 1 2 3 4 5

谁能告诉我这里有什么问题?

1 个答案:

答案 0 :(得分:1)

首先,在循环之后,弹出已推送的最后一个元素。而是在进入循环之前弹出元素。

其次,在从堆叠中取出元素时处理元素,而不是在将元素推入堆栈时处理元素。

第三,要实现所需的顺序,请向后迭代子节点(因此较小的子节点将位于堆栈顶部):

public void dfs(int vertex)
{
    int length = matrix.GetLength(0);
    bool[] visited = new bool[length];
    for (int k = 0; k < length; k++)
    {
        visited[k] = false;
    }
    Stack<int> vertexStack = new Stack<int>();
    vertexStack.Push(vertex);

    while (vertexStack.Count() != 0)
    {
        int tempVertex = vertexStack.Pop();
        if (!visited[tempVertex])
        {
            visited[tempVertex] = true;
            Console.Write((tempVertex) + " ");
            for (int j = length - 1; j >= 0; j--)
            {
                if (matrix[tempVertex, j] == 1 && !visited[j])
                {
                    vertexStack.Push(j);
                }
            }
        }
    }
}