所以這我當前的代碼,我將發佈以下聲明頭...使用Dijkstra算法與unordered_map圖
// 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)。如果兩個節點是同一頂點離接近(「波士頓」,「波士頓」),則該函數將返回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 + 2 + 10 <3 + 18。 – Johan
有一些問題。首先,您的算法並不真正跟蹤所有可到達的節點,因此它只是沿着來自任何給定節點的最短路徑移動,而不考慮總路徑長度。其次,返回值返回總距離,但上面的'正確'結果是路徑中的頂點總數。你要哪個? –
我編輯了我的代碼。該算法需要輸出從頂點v1到頂點v2獲取的最小#個邊。正如你在圖表@Johan中看到的那樣,從特倫頓只需要2次跳轉 - > Philidelphia – Riptyde4