非递归的深度优先搜索,其行为类似于c#
我正在尝试用c实现非递归DFS算法# 这是我的方法代码非递归的深度优先搜索,其行为类似于c#,c#,depth-first-search,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 Sta
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();
}
}
对于此图,dfs的结果应为0 1 4 5 2 3
但是它们是01 2 3 5 4,这几乎就像图01 2 3 4 5的BFS
有人能告诉我这里出了什么问题吗?首先,在循环之后,弹出最后一个被推送的元素。而是在进入循环之前弹出元素 其次,在从堆栈中取出元素时处理它们,而不是在将它们推到堆栈上时 第三,为了达到您想要的顺序,向后迭代子节点(这样较小的子节点将位于堆栈顶部):
public void dfs(int-vertex)
{
int length=matrix.GetLength(0);
bool[]已访问=新bool[长度];
for(int k=0;k=0;j--)
{
if(矩阵[tempVertex,j]==1&&!已访问[j])
{
顶推(j);
}
}
}
}
}
[代码>谢谢,但为以下的矩阵,该公司的dfs应该是0 1 4 6 5 5 2 7 7 7 3 3 3 3 3 int[,,]矩阵3{{0,1,1,0,1,0,0,0,1,感谢,感谢,感谢,但为以下的矩阵,该公司的dfs应该是0 1 1 4 6 6 6 6 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 7 7 7 7 3 3 3 3 3 3 3的矩阵,5 5,5 5,5,5,5 5 5,5,5,7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 3 3 3 3 3 3 3 3 3,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]3 3 3 3 3 3 0 0 0 0,1,0,1,1,1},};但是它给出了0 1 4 5 2 7 3 6,而这个矩阵的输出是0 1 4 6 5 2 7 3。请注意,我在发布算法后对其进行了轻微更改。
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();
}
}
}
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);
}
}
}
}
}