Leetcode 207. 课程表
Posted randyniu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 207. 课程表相关的知识,希望对你有一定的参考价值。
class Solution { public: struct GraphNode { int lable; vector<GraphNode*> neighbors; GraphNode(int x):lable(x){} }; bool DFS_graph(GraphNode* node, vector<int>& visit) { //正在访问 visit[node->lable] = 0; for(int i=0; i<node->neighbors.size(); ++i) { if(visit[node->neighbors[i]->lable] == -1) { //在访问的里面已经返回false就直接返回false了 if(DFS_graph(node->neighbors[i], visit) == 0) { return false; } } // 第一个遇到有环的 if(visit[node->neighbors[i]->lable] == 0) { return false; } } //完成了以后 visit[node->lable] = 1; return true; } bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector<GraphNode*> graph; vector<int> visit;//节点状态,-1表示没有访问,0表示正在访问,1表示已经访问 bool flag = true; for(int i=0; i<numCourses; ++i) { graph.push_back(new GraphNode(i)); } visit.resize(numCourses, -1); for(int i=0; i<prerequisites.size(); ++i) { GraphNode* begin = graph[prerequisites[i].second]; GraphNode* end = graph[prerequisites[i].first]; begin->neighbors.push_back(end); } for(int i=0; i<graph.size(); ++i) { if(visit[i] == -1 && !DFS_graph(graph[i], visit)) { flag = false; break; } } for(int i=0; i<numCourses; ++i) { delete graph[i]; } return flag; } };
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { vector<GraphNode*> graph; vector<int> degree; for(int i=0; i<numCourses; ++i) { graph.push_back(new GraphNode(i)); } degree.resize(numCourses, 0); for(int i=0; i<prerequisites.size(); ++i) { GraphNode* begin = graph[prerequisites[i].second]; GraphNode* end = graph[prerequisites[i].first]; begin->neighbors.push_back(end); ++degree[prerequisites[i].first]; } queue<GraphNode*> queue; for(int i=0; i<numCourses; ++i) { if(degree[i] == 0) { queue.push(graph[i]); } } while(!queue.empty()) { auto *node = queue.front(); queue.pop(); for(int i=0; i<node->neighbors.size(); ++i) { --degree[node->neighbors[i]->lable]; if(degree[node->neighbors[i]->lable] == 0) { queue.push(node->neighbors[i]); } } } for(int i=0; i<numCourses; ++i ) delete graph[i]; for(int i=0; i<degree.size(); ++i) { if(degree[i]) return false; } return true; } };
以上是关于Leetcode 207. 课程表的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode207.课程表 | BFS DFS 邻接表 邻接矩阵