【发布时间】:2010-12-04 00:29:44
【问题描述】:
几个小时以来,我一直试图在网上和这个网站上找到这个问题的答案,但我还没有找到答案。
我了解 .NET 会为应用分配 1MB,最好通过重新编码而不是强制堆栈大小来避免堆栈溢出。
我正在开发一个“最短路径”应用程序,该应用程序在大约 3000 个节点上运行良好,此时它会溢出。以下是导致问题的方法:
public void findShortestPath(int current, int end, int currentCost)
{
if (!weight.ContainsKey(current))
{
weight.Add(current, currentCost);
}
Node currentNode = graph[current];
var sortedEdges = (from entry in currentNode.edges orderby entry.Value ascending select entry);
foreach (KeyValuePair<int, int> nextNode in sortedEdges)
{
if (!visited.ContainsKey(nextNode.Key) || !visited[nextNode.Key])
{
int nextNodeCost = currentCost + nextNode.Value;
if (!weight.ContainsKey(nextNode.Key))
{
weight.Add(nextNode.Key, nextNodeCost);
}
else if (weight[nextNode.Key] > nextNodeCost)
{
weight[nextNode.Key] = nextNodeCost;
}
}
}
visited.Add(current, true);
foreach (KeyValuePair<int, int> nextNode in sortedEdges)
{
if(!visited.ContainsKey(nextNode.Key) || !visited[nextNode.Key]){
findShortestPath(nextNode.Key, end, weight[nextNode.Key]);
}
}
}//findShortestPath
作为参考,Node 类有一个成员:
public Dictionary<int, int> edges = new Dictionary<int, int>();
图[]是:
private Dictionary<int, Node> graph = new Dictonary<int, Node>();
我已尝试优化代码,使其从一次迭代(递归?)到下一次迭代不会携带比所需更多的包袱,而是使用 100K 节点图,每个节点都有 1-9 条边它将很快达到 1MB 的限制。
无论如何,我是 C# 和代码优化的新手,如果有人可以给我一些指点 (not like this),我将不胜感激。
【问题讨论】:
标签: c# stack-overflow