2017-01-16 101 views
-1

我想知道什么是错在下面的C#代码产生通过Hierholzer的算法顶点索引的欧拉,假设所有顶点甚至有度,使旅游可以从任何地方开始:欧拉在C#

(何pt_id是表示由边缘组成的起点和终点索引的整数列表)

ps。下列项目的GraphMatrix包括最初的情况下,它是任何帮助,由于对pt_id缺乏信息:

n y y n y y n n n n n 

y n n n y n n n n n n 

y n n y y y n n n n n 

n n y n n y n y y n n 

y y y n n y n n n n n 

y n y y y n n n n n n 

n n n n n n n y y y y 

n n n y n n y n y n y 

n n n y n n y y n n y 

n n n n n n y n n n y 

n n n n n n y y y y n 

代码:

Stack tempPath = new Stack(); 
ArrayList finalPath = new ArrayList(); 

int total = 11;//total number of nodes 

string[] nodeList = new string [total];//to store the nodes 
string[,] GraphMatrix = new string [total, total];//to store the edge representation of graph 

//node/vertice to nodeList array 
for(int i = 0; i < total; ++i) { 
    nodeList[i] = i.ToString(); 
} 


//edge details in the graph(connectivity boolean matrix) 
//matrix first filled with "n" 
for(int i = 0; i < total; ++i) { 
    for(int j = 0; j < total; ++j) { 
    GraphMatrix[i, j] = "n"; 
    } 
} 
//if connection exists, matrix item is changed to "y" 
for(int i = 0; i < pt_id.Count; ++i) { 
    GraphMatrix[pt_id[i][0], pt_id[i][1]] = "y"; 
    GraphMatrix[pt_id[i][1], pt_id[i][0]] = "y"; 
} 


//start tour 

int s = 0; 
int ind = 0; 
tempPath.Clear(); 

tempPath.Push(nodeList[0]); 

while(tempPath.Count != 0 && s < 100) { 

    int index = 0; 
    while (tempPath.Peek().ToString() != nodeList[index] && s < 100) { 
    index++; 
    s++; 
    } 

    ind = index; 
    for(int i = 0; i < total; ++i) { 
    if(GraphMatrix[ind, i] != "y") { 
     finalPath.Add(tempPath.Pop()); 
    } 
    else{ 
     GraphMatrix[ind, i] = "n"; 
     GraphMatrix[i, ind] = "n"; 
     tempPath.Push(nodeList[i]); 
    } 
    } 
    s++; 
} 

我收到错误说堆栈是空的。

非常感谢你,

+3

那么,你有没有使用调试器来跟踪堆栈?或使用系统输出做同样的事情? – Aziuth

+0

嗨@Aziuth感谢您的回应 - 我目前正在尝试在VisualStudio中,但仍然不太明白。 – tim

+0

然后我建议你找一些关于调试的教程。也许一个视频就是一个例子。系统输出的方法是插入输出以隔离发生错误的部分,跟踪程序(如何处理多少次等等),并在上下文中打印出应该更改的堆栈大小。试图找出错误的来源何时首次发生。你可以做的另一件事是让所有东西都变小,然后添加东西。就像初始化堆栈,然后推入一个元素,然后......直到发生错误或程序运行。 – Aziuth

回答

0

看起来你想通过堆栈的所有元素在该行

while (tempPath.Peek().ToString() != nodeList[index] && s < 100) { 

Peek()只返回之上的元素没有删除它的堆栈。因此,在该行中,您将比较堆栈顶部的元素与nodelist中的元素。

遍历堆栈中的所有元素,你可以做

int index = 0; 
foreach (var element in tempPath) 
{ 
    if (element.ToString() == nodelist[index] && s >= 100) 
    { 
     break; 
    } 
    else 
    { 
     index ++; 
     s++; 
    } 
} 

没有您的代码中的第二个问题。 在致电tempPath.Pop()之前,您需要检查是否有剩余物品,并执行您的算法要求的其他操作,而不是调用Pop()

+0

谢谢你的帮助!但是,我仍然收到堆栈为空的错误。 – tim