1 Star 0 Fork 0

xiangxiang/LeetCode-NOTES

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
solution.cpp 1.28 KB
一键复制 编辑 原始数据 按行查看 历史
默然 提交于 7年前 . update all algorithms.
class Graph
{
int V;
list<int> *adj;
queue<int> q;
int* indegree;
public:
Graph(int V);
~Graph();
void addEdge(int v, int w);
bool topological_sort();
};
/************************类定义************************/
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
indegree = new int[V];
for(int i=0; i<V; ++i)
indegree[i] = 0;
}
Graph::~Graph()
{
delete [] adj;
delete [] indegree;
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w);
++indegree[w];
}
bool Graph::topological_sort()
{
for(int i=0; i<V; ++i)
if(indegree[i] == 0)
q.push(i);
int count = 0;
while(!q.empty())
{
int v = q.front();
q.pop();
++count;
list<int>::iterator beg = adj[v].begin();
for( ; beg!=adj[v].end(); ++beg)
if(!(--indegree[*beg]))
q.push(*beg);
}
if(count < V)
return false;
else
return true;
}
class Solution
{
public:
bool canFinish(int numCourses, vector<vector<int> >& prerequisites)
{
Graph g(numCourses);
for(int i=0; i<prerequisites.size(); ++i)
g.addEdge(prerequisites[i][1], prerequisites[i][0]);
return g.topological_sort();
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/xiangxiang920/LeetCode-NOTES.git
git@gitee.com:xiangxiang920/LeetCode-NOTES.git
xiangxiang920
LeetCode-NOTES
LeetCode-NOTES
master

搜索帮助