使用邻接矩阵的Dijkstra算法没有找到从每个节点到每个其他节点的正确距离/路径

时间:2015-11-12 07:33:46

标签: c++ algorithm graph dijkstra adjacency-matrix

我试图编写一个使用Adjacency Matrix构建图形的程序,然后使用Dijkstra算法找到从每个节点到每个其他节点的最短路径。我的程序目前无法每次都找到正确的最短路径。我还需要跟踪路径,但我不确定从哪里开始。

class GraphD
{

public:
    GraphD();
    void buildGraph(ifstream &infile);

    void insertEdge(int from, int to, int distance);

    void findShortestPath();

private:
    static const int MAXNODES = 101;
    static const int infinity = 2147483647;
    struct TableType
    {
         bool visited;
         int dist;
         int path;
    };
    int C[MAXNODES][MAXNODES]; // holds adjacency matrix
    int size;
    TableType T[MAXNODES][MAXNODES]; // for dijkstra's algorithm
};


#include "GraphD.h"

GraphD::GraphD()
{
    size = 0;
    for(int i = 1; i < MAXNODES; i++)
    {
        for(int j = 1; j < MAXNODES; j++)
        {
            C[i][j] = infinity;
            T[i][j].dist = infinity;
            T[i][j].visited = false;
            T[i][j].path = 0;
        }
    }
}

void GraphD::buildGraph(ifstream &infile)
{
    string line;
    if(getline(infile, line))
    {
        size = atoi(line.c_str());
        for(int i = 1; i <= size; i++)
        {
            getline(infile, line);
            data[i] = line;
        }

        int vertex1, vertex2, distance;
        while(getline(infile, line))
        {
            stringstream edge(line);
            edge >> vertex1 >> vertex2 >> distance;
            if(vertex1 == 0)
                break;
            insertEdge(vertex1, vertex2, distance);
        }
        for(int i = 1; i <= size; i++)
        {
            C[i][i] = 0;
        }
    }
}

void GraphD::insertEdge(int from, int to, int distance)
{
    C[from][to] = distance;
} 

void GraphM::findShortestPath()
{
    for(int source = 1; source <= size; source++)
    {
        T[source][source].dist = 0;
        for(int i = 1; i <= size; i++)
        {
            int v = 0;
            int shortestDistance = infinity;
            for(int j = 1; j <= size; j++)
            {
                if((C[source][j] < shortestDistance) && !T[source][j].visited)
                {
                    shortestDistance = C[source][j];
                    v = j;
                }
            }
            T[source][v].visited = true;
            for(int w = 1; w <= size; w++)
            {
                if(!T[v][w].visited)
                {
                    T[v][w].dist = min(T[v][w].dist, T[source][v].dist + C[v][w]);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

设置无穷大值等于1&000; 000&#39; 000&#39; 000(或类似这样的smth),因为当你使用MAX_INT值时,你会得到整数溢出

T[v][w].dist = min(T[v][w].dist, T[source][v].dist + C[v][w]);

此外,我认为您应该替换以下部分代码

if(!T[v][w].visited)
{
    T[v][w].dist = min(T[v][w].dist, T[source][v].dist + C[v][w]);
}

到下一个

if(!T[source][w].visited)
{
    T[source][w].dist = min(T[source][w].dist, T[source][v].dist + C[v][w]);
}

因为您需要找到距顶点源的顶点W的距离,而不是V。