我将C++
的{{1}}实现转换为Dijkstra's Algorithm
。
当我运行Java
代码时,没有得到预期的输出结果
来自我的Java
代码:
C++
来自Minimum distance for source vertex 0 to reach vertex 0 is 0
Minimum distance for source vertex 0 to reach vertex 1 is 4
Minimum distance for source vertex 0 to reach vertex 2 is 12
Minimum distance for source vertex 0 to reach vertex 3 is 19
Minimum distance for source vertex 0 to reach vertex 4 is 21
Minimum distance for source vertex 0 to reach vertex 5 is 11
Minimum distance for source vertex 0 to reach vertex 6 is 9
Minimum distance for source vertex 0 to reach vertex 7 is 8
Minimum distance for source vertex 0 to reach vertex 8 is 14
代码的实际值:
Java
我试图在Java代码中寻找错误,我仔细检查了是否正确复制了C ++代码,但没有发现任何不同。
我已经花了很多时间调试我的代码。
我不明白出了什么问题!我迫切需要帮助,谢谢!
代码:
Minimum distance for source vertex 0 to reach vertex 0 is 0
Minimum distance for source vertex 0 to reach vertex 1 is 4
Minimum distance for source vertex 0 to reach vertex 2 is 2
Minimum distance for source vertex 0 to reach vertex 3 is 7
Minimum distance for source vertex 0 to reach vertex 4 is 9
Minimum distance for source vertex 0 to reach vertex 5 is 2
Minimum distance for source vertex 0 to reach vertex 6 is 1
Minimum distance for source vertex 0 to reach vertex 7 is 1
Minimum distance for source vertex 0 to reach vertex 8 is 2
答案 0 :(得分:1)
Arrays.fill(adj, new ArrayList<IPair>())
等效于:
List<IPair> list = new ArrayList<>();
Arrays.fill(adj, list)
这意味着您要在所有数组元素中存储相同 List
对象。更改List
的{{1}}对象时,它会更改所有adj[x]
元素的List
对象,因为它是同一对象。
解决方案是在每个adj
元素中存储一个新的List
对象:
adj