class Solution {
public:
vector<vector<int>> edges;
vector<int> visited;
vector<int> ans;
bool valid = true;
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
visited.resize(numCourses);
edges.resize(numCourses);
for (int i = 0; i < prerequisites.size(); i++)
{
edges[prerequisites[i][1]].push_back(prerequisites[i][0]);
}
for (int i = 0; i < numCourses && valid; i++)
{
if (!visited[i])
{
dfs(i);
}
}
if (!valid)
{
return false;
}
return true;
}
void dfs(int u)
{
visited[u] = 1;
for (int i = 0; i < edges[u].size(); i++)
{
int v = edges[u][i];
if (visited[v] == 0)
{
dfs(v);
if (!valid)
{
return;
}
}
else if (visited[v] == 1)
{
valid = false;
return;
}
else if (visited[v] == 2)
{
}
}
visited[u] = 2;
ans.push_back(u);
}
};
LeetCode207. 课程表
最新推荐文章于 2024-07-05 23:46:45 发布