[当我尝试使用表示图形的unordered_map<string, vector<string>>
在C ++中实现拓扑排序时,遇到了无法解释的错误(就我而言)。具体来说,当正在访问的“当前节点”在unordered_map
中不作为键存在时(即,它没有传出的边沿),这会<< only>发生。它没有返回“正确”的顺序,而是完全终止了函数调用topSort
,仅返回该顺序的一小部分。 代码返回:ML, AML, DL
相反,可能的正确解决方案可能是:LA, MT, MA, PT, ML, AML, DL
谁能解释为什么会这样吗?
以下是发生问题的小代码段:
// 0 -> white (node has not been visited)
// 1 -> grey (node is currently being visited)
// 2 -> black (node is completely explored)
bool topSortVisit(unordered_map<string, vector<string>>& graph,
unordered_map<string, int>& visited, string node, vector<string>& result){
if(visited[node] == 1) return false;
if(visited[node] == 2) return true;
// Mark current node as being visited.
visited[node] = 1;
// node might not have outgoing edges and therefore not in the
// unordered_map (graph) as a key.
for(auto neighbor : graph[node]){
if(!topSortVisit(graph, visited, neighbor, result)) return false;
}
result.push_back(node);
visited[node] = 2;
return true;
}
vector<string> topSort(unordered_map<string, vector<string>>& graph){
unordered_map<string, int> visited;
vector<string> result;
// Should visit all nodes with outgoing edges in the graph.
for(auto elem : graph){
string node = elem.first;
bool acyclic = topSortVisit(graph, visited, node, result);
if(!acyclic){
cout << "cycle detected\n";
return vector<string>{};
}
}
reverse(result.begin(), result.end());
return result;
}
这是复制所有内容的代码:
#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;
bool topSortVisit(unordered_map<string, vector<string>>& graph,
unordered_map<string, int>& visited, string node, vector<string>& result){
if(visited[node] == 1) return false;
if(visited[node] == 2) return true;
visited[node] = 1;
for(auto neighbor : graph[node]){
if(!topSortVisit(graph, visited, neighbor, result)) return false;
}
result.push_back(node);
visited[node] = 2;
return true;
}
vector<string> topSort(unordered_map<string, vector<string>>& graph){
unordered_map<string, int> visited;
vector<string> result;
for(auto elem : graph){
string node = elem.first;
bool acyclic = topSortVisit(graph, visited, node, result);
if(!acyclic){
cout << "cycle detected\n";
return vector<string>{};
}
}
return result;
}
unordered_map<string, vector<string>> makeGraph(vector<pair<string, string>> courses){
unordered_map<string, vector<string>> graph;
for(auto p : courses){
graph[p.first].push_back(p.second);
}
return graph;
}
int main(){
vector<pair<string, string>> pairs;
pairs.push_back(make_pair("LA", "ML"));
pairs.push_back(make_pair("MT", "ML"));
pairs.push_back(make_pair("MA", "PT"));
pairs.push_back(make_pair("PT", "ML"));
pairs.push_back(make_pair("ML", "DL"));
pairs.push_back(make_pair("ML", "AML"));
auto graph = makeGraph(pairs);
vector<string> result = topSort(graph); // ML, AML, DL
// A possible correct solution could be: LA, MT, MA, PT, ML, AML, DL
for(string s : result){
cout << s << " ";
}
cout << "\n";
}
[当我尝试使用代表图表的unordered_map>在C ++中实现拓扑排序时,我遇到了无法解释的错误(就我而言)。具体来说,...
unordered_map
中的无效