我正在努力实现一个分配的弗洛伊德-华尔算法和输出矩阵是不正确的。我把我的算法和其他的在线算法做了两次核对,看上去和其他算法一样。我只是遗漏了什么吗?任何帮助都是非常感谢的。
我的输入文件是:
4
0 2 2 -1
-1 0 2 3
-1 -1 0 2
-1 -1 -1 0结果矩阵应该是:
0 2 2 4
-1 0 2 3
-1 -1 0 2
-1 -1 -1 0路径矩阵应该是:
0 0 0 3
0 0 0 0
0 0 0 0
0 0 0 0 我正在接收作为我的结式矩阵:
-4 -3 -2 -5
-5 -4 -3 -6
-6 -5 -4 -7
-7 -6 -5 -8对于路径矩阵:
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4下面是我的程序的代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
// Forward Declarations
void readFile();
void fillPathWithZeros();
void findFloydsAlgorithmMatrix();
void printGraph(vector< vector<int> >& inVector, string heading);
int size;
vector< vector<int> > M; // Matrix with weights
vector< vector<int> > P; // Path Matrix
int main()
{
readFile();
fillPathWithZeros();
findFloydsAlgorithmMatrix();
cin.get();
return 0;
}
void readFile()
{
int z = 0;
ifstream file("example.txt", fstream::in); // File name is example.txt
if (file.is_open())
{
// read characters by using "file >>"
file >> z;
size = z;
vector< vector<int> > fileGraph(size, vector<int>(size)); // creates a local 2D vector to size stated in file
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
file >> fileGraph[i][j];
}
}
M = fileGraph; // Copies the local vector to a global vector to be used in other functions
printGraph(fileGraph, "Input matrix M: "); // Print out the input Matrix
}
}
// Initialize the Path Vector with all 0's
void fillPathWithZeros()
{
vector< vector<int> > localPathGraph(size, vector<int>(size));
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++) {
localPathGraph[i][j] = 0;
}
}
P = localPathGraph; // set the local Path Vector to the Global Path Vector
}
void findFloydsAlgorithmMatrix()
{
for (int k = 0; k < size; k++) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++){
if ( ( M[i][k] + M[k][j] ) < M[i][j] ) {
M[i][j] = M[i][k] + M[k][j];
P[i][j] = k + 1;
}
}
}
}
printGraph(M, "Resultant matrix M: ");
printGraph(P, "Path matrix P: ");
}
void printGraph(vector< vector<int> >& inVector, string heading){
cout << heading << endl;
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++) {
cout << setw(2) << inVector[i][j] << " ";
}
cout << endl;
}
cout << endl;
}发布于 2014-03-04 10:05:31
矩阵中存在负距离。弗洛伊德-战争不工作负距离或循环。
见此处:algorithm
就您的代码而言,从算法的角度来看,它看起来还不错。有些事情可以在较短的代码量内完成(例如向量的初始化),但除此之外,如果矩阵没有负距离/循环,代码应该可以工作。
https://stackoverflow.com/questions/22165460
复制相似问题