这是问题(https://leetcode.com/problems/course-schedule-ii/description/)。 我的解决方案来自“算法简介”。 使用DFS算法。并用白色,灰色和黑色为节点着色。
但我通过了大部分案件。但其中一些不是。 任何人都可以帮助我吗?
守则:
class Solution {
public:
enum {WHITE, GRAY, BLACK};
vector<vector<int>> graph;
vector<int> colors;
list<int> topo;
void add_edge(vector<vector<int>>& graph, pair<int, int>& p) {
graph[p.second].push_back(p.first);
}
bool visit(vector<vector<int>>& graph, int i) {
if (colors[i] == WHITE) {
colors[i] = GRAY;
bool ret = true;
for (int j = 0; j < graph[i].size(); j++) {
if (colors[graph[i][j]] == WHITE)
ret = ret && visit(graph, graph[i][j]);
else if (colors[graph[i][j]] == GRAY)
ret = false;
else
ret = false;
}
colors[i] = BLACK;
topo.push_front(i);
return ret;
}
return true;
}
bool dfs(vector<vector<int>>& graph) {
for (int i = 0; i < graph.size(); i++)
if (!visit(graph, i))
return false;
return true;
}
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
graph.resize(numCourses, {});
colors.resize(numCourses, WHITE);
for (auto& pre: prerequisites)
add_edge(graph, pre);
if (!dfs(graph))
return {};
vector<int> ret (topo.begin(),topo.end());
return ret;
}
};
答案 0 :(得分:1)
在
for (int j = 0; j < graph[i].size(); j++) {
if (colors[graph[i][j]] == WHITE)
ret = ret && visit(graph, graph[i][j]);
else if (colors[graph[i][j]] == GRAY)
ret = false;
else
ret = false;
}
最后一个是节点是BLACK,这意味着它已经处理并推送到结果中。因此它不会使图形无效。只需删除最后一个,它将工作。像这样:
for (int j = 0; j < graph[i].size(); j++) {
if (colors[graph[i][j]] == WHITE)
ret = ret && visit(graph, graph[i][j]);
else if (colors[graph[i][j]] == GRAY)
ret = false;
/* else
ret = false; */
}