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; } };
原文地址:https://www.cnblogs.com/randyniu/p/9350307.html
时间: 2024-11-06 07:07:28