我有一个图表,想要运行深度优先搜索,我想返回结果如:ABCDEFGHIJKLM,但我只得到了ABCDEHK。算法有什么问题?感谢
class Program
{
static void Main(string[] args)
{
//create graph, adjacent matrix
Graph aGraph = new Graph();
aGraph.AddVertex("A");
aGraph.AddVertex("B");
aGraph.AddVertex("C");
aGraph.AddVertex("D");
aGraph.AddVertex("E");
aGraph.AddVertex("F");
aGraph.AddVertex("G");
aGraph.AddVertex("H");
aGraph.AddVertex("I");
aGraph.AddVertex("J");
aGraph.AddVertex("K");
aGraph.AddVertex("L");
aGraph.AddVertex("M");
aGraph.AddEdge(0,1);
aGraph.AddEdge(1,2);
aGraph.AddEdge(2,3);
aGraph.AddEdge(0,4);
aGraph.AddEdge(4,5);
aGraph.AddEdge(5,6);
aGraph.AddEdge(0,7);
aGraph.AddEdge(7,8);
aGraph.AddEdge(8,9);
aGraph.AddEdge(0,10);
aGraph.AddEdge(10,11);
aGraph.AddEdge(11,12);
}
}
//vertex class
public class Vertex {
public bool wasVisited;
public string label;
public Vertex(string label) {
this.label = label;
wasVisited = false;
}
}
//Graph class
public class Graph {
private const int NUM_VERTICES = 20;
private Vertex[] vertices;
private int[,] adjMatrix;
int numVerts;
private Stack gStack;
public Graph() {
vertices = new Vertex[NUM_VERTICES];
adjMatrix = new int[NUM_VERTICES,NUM_VERTICES];
numVerts = 0;
for (int j = 0; j <= NUM_VERTICES-1; j++)
for (int k = 0; k < NUM_VERTICES - 1; k++)
adjMatrix[j, k] = 0;
gStack = new Stack();
}
public void AddVertex(string label)
{
vertices[numVerts] = new Vertex(label);
numVerts++;
}
public void AddEdge(int start, int eend)
{
adjMatrix[start, eend] = 1;
adjMatrix[eend, start] = 1;
}
public void ShowVertex(int v) {
Console.Write(vertices[v].label+" ");
}
private int GetAdjUnvisitedVertex(int v) {
for (int j = 0; j <= numVerts-1; j++) //NUM_VERTICES or numVerts
if ((adjMatrix[v, j] == 1) && (vertices[j].wasVisited == false))
return j;
return -1;
}
public void DepthFirstSearch()
{
vertices[0].wasVisited = true;
ShowVertex(0);
//Stack gStack = new Stack();
gStack.Push(0);
int v;
while (gStack.Count > 0) {
//v = GetAdjUnvisitedVertex(gStack.Peek());
v = GetAdjUnvisitedVertex(gStack.Count-1);
if (v == -1)
gStack.Pop();
else {
vertices[v].wasVisited = true;
ShowVertex(v);
gStack.Push(v);
}
}
for (int j = 0; j <= numVerts - 1; j++) //NUM_VERTICES or numVerts
vertices[j].wasVisited = false;
}
原始算法有这一行:
//v = GetAdjUnvisitedVertex(gStack.Peek());
但它与函数GetAdjUnvisitedVertex
不匹配,所以我改为行:
v = GetAdjUnvisitedVertex(gStack.Count-1);
答案 0 :(得分:0)
我浏览了你的代码,当我取消注释
时//v = GetAdjUnvisitedVertex(gStack.Peek());
输出“A B C D E F G H I J K L M”也称为正确答案。当你有
v = GetAdjUnvisitedVertex(gStack.Count-1);
当您开始遍历图表中的第二条路径时(A - > E - > F - > G),您没有在正确的顶点上调用该函数。由于gStack在第二条路径下行时只有顶部顶点(A),因此调用GetAdjUnvisitedVertex(0);它将返回下一个相邻的顶点H,并重复返回K。