【发布时间】:2015-12-09 21:52:20
【问题描述】:
我应该使用邻接矩阵和距离数组来实现 Dijkstra 算法。这些是通过Graph300 类实现的。该程序输入一个带有加权矩阵的文件,并且它正在进入矩阵。
为用户输出距离数组。但我的 Dijkstras 工作不正常。除了起始顶点(用户指定)之外,我一直为每个顶点获取UINT_MAX:
Input matrix (4x4):
0 5 10 4294967295
4294967295 0 4294967295 3
4294967295 7 0 4294967295
4294967295 4294967295 4 0
My distance array should output:
distance[0]=4294967295 -nopath
distance[1]=0 -startnode
distance[2]=7
distance[3]=3
My output now (that is wrong):
distance[0]=4294967295 -nopath
distance[1]=0 -startnode
distance[2]=4294967295
distance[3]=4294967295
这是我的算法; numberNodes 是顶点的维度。 startNode 是用户指定的。矩阵数组和距离数组的类型为unsigned int:
void Graph300::dijkstra300()
{
int startNode=getStartNode300();
for (int i = 0; i < numberNodes; i++)
distanceArray[i] = UINT_MAX;
distanceArray[startNode] = 0;
for (int count = 0; count < numberNodes-1; count++)
{
unsigned int min = INT_MAX, min_index;
for (int v = 0; v < numberNodes; v++)
if (visitedSet[v] == false && distanceArray[v] <= min)
min = distanceArray[v], min_index = v;
int u = min_index;
visitedSet[u] = true;
for (int v = 0; v < numberNodes; v++)
if (!visitedSet[v] && adjacencyMatrix[u][v] && distanceArray[u] != UINT_MAX
&& distanceArray[u]+adjacencyMatrix[u][v] < distanceArray[v])
distanceArray[v] = distanceArray[u] + adjacencyMatrix[u][v];
}
view300(); // display result
}
【问题讨论】:
-
“工作不正常”不够具体,我们无法提供帮助。请提供可重现的信息:你有什么输入,你得到什么输出,你期望什么输出?
-
'对不起,如果我的代码间距很奇怪。我总是把它复制过来很奇怪'有很多编辑器可以相应地格式化你的代码。作为一个建议,使用它,它会很容易阅读。
-
你能说出 distanceArray[] 和 adjacencyMatrix[][] 的类型吗?
-
好的!现在有了你的测试数据和 unsigned int 的使用,我可以找到问题(查看更新的解决方案)
标签: c++ algorithm graph dijkstra