【发布时间】:2013-12-10 19:01:38
【问题描述】:
所以这是我当前的代码,我将在下面发布标题声明...
// Using Dijkstra's
int Graph::closeness(string v1, string v2){
int edgesTaken = 0;
unordered_map<string, bool> visited;
unordered_map<string, int> distances;
string source = v1; // Starting node
while(source != v2 && !visited[source]){
// The node has been visited
visited[source] = 1;
// Set all initial distances to infinity
for(auto i = vertices.begin(); i != vertices.end(); i++){
distances[i->first] = INT_MAX;
}
// Consider all neighbors and calculate distances from the current node
// & store them in the distances map
for(int i = 0; i < vertices[source].edges.size(); i++){
string neighbor = vertices[source].edges[i].name;
distances[neighbor] = vertices[source].edges[i].weight;
}
// Find the neighbor with the least distance
int minDistance = INT_MAX;
string nodeWithMin;
for(auto i = distances.begin(); i != distances.end(); i++){
int currDistance = i->second;
if(currDistance < minDistance){
minDistance = currDistance;
nodeWithMin = i->first;
}
}
// There are no neighbors and the node hasn't been found yet
// then terminate the function and return -1. The nodes aren't connected
if(minDistance == INT_MAX)
return -1;
// Set source to the neighbor that has the shortest distance
source = nodeWithMin;
// Increment edgesTaken
edgesTaken++;
// clear the distances map to prepare for the next iteration
distances.clear();
}
return edgesTaken;
}
声明(这是一个无向图):
class Graph{
private:
// This holds the connected name and the corresponding we
struct EdgeInfo{
std::string name;
int weight;
EdgeInfo() { }
EdgeInfo(std::string n, int w) : name(n), weight(
};
// This will hold the data members of the vertices, inclu
struct VertexInfo{
float value;
std::vector<EdgeInfo> edges;
VertexInfo() { }
VertexInfo(float v) : value(v) { }
};
// A map is used so that the name is used as the index
std::unordered_map<std::string, VertexInfo> vertices;
注意:请不要建议我更改标头声明,我正在为一个已经编写了 8 个其他函数的项目做出贡献,现在返回并更改任何内容肯定为时已晚,因为那时所有其他函数都会必须重写
我目前得到的输出不正确。但是,该函数正确处理 0 距离情况(如果两个顶点未连接,则该函数应返回 -1)。如果两个节点是相同的顶点 ex closeness("Boston", "Boston") 那么函数应该返回一个 0。
左边以下两个顶点的接近度会在右边:
Correct:
Trenton -> Philadelphia: 2
Binghamton -> San Francisco: -1
Boston -> Boston: 0
Palo Alto -> Boston: -1
Output of my function:
Trenton -> Philadelphia: 3
Binghamton -> San Francisco: -1
Boston -> Boston: 0
Palo Alto -> Boston: 3
我试图复制 dijkstra 的确切描述方式,但我得到的读数不正确,我一直试图弄清楚这一点 -> 谁能指出我正确的方向?
【问题讨论】:
-
对我来说特伦顿 - > 费城真的是 3 条边长,因为 3+2+10
-
有很多问题。首先,您的算法并没有真正跟踪所有可达节点,因此它只是沿着任何给定节点的最短路径移动,而不考虑总路径长度。其次,返回是返回总距离,但上面的“正确”结果是路径中的顶点总数。你要哪个?
-
我已经编辑了我的代码。该算法需要输出从顶点 v1 到顶点 v2 所需的最小边数。正如您在图表中所看到的@Johan,从特伦顿 -> 费城只需 2 次跳跃
-
您是否尝试过打印出每个节点的邻居列表以确保数据正确?
-
是的,但是你的边被加权了,你实际上使用这个权重来计算最短路径......
标签: c++ algorithm dictionary graph dijkstra