LintCode 1366.Directed Graph Loop 判斷有向圖是否有環
阿新 • • 發佈:2019-01-03
Description
Please judge whether there is a cycle in the directed graph with n vertices and m edges. The parameter is two int arrays. There is a directed edge from start[i] to end[i].
2 <= n <= 10^5
1 <= m <= 4*10^5
1 <= start[i], end[i] <= n
Have you met this question in a real interview?
Example
Given start = [1],end = [2], return “False”。
Explanation:
There is only one edge 1->2, and do not form a cycle.
思路:構建圖結構,記錄每個頂點的入度,若有後向邊存在(拓撲結構中後出現的點有指向已出現的點的邊),則有環。、
class Solution {
public:
/**
* @param start: The start points set
* @param end: The end points set
* @return: Return if the graph is cyclic
*/
bool isCyclicGraph(vector<int> &start, vector<int> &end) {
int n = 0;
for(int s:start) n = max(n, s);
for(int e:end) n = max(n, e);
vector<int> graph[n+1];
vector<int> d(n+1); // 保留各頂點的入度,判斷拓撲排序後是否有邊存在
for(int i=0; i<start.size(); ++i){
graph[start[i]].push_back(end[i]);
d[end[i]]++;
}
queue <int> que;
for(int i=1; i<=n; ++i)
if(graph[i].size() && !d[i]) que.push(i);
while(!que.empty()){
int v = que.front(); que.pop();
for(int edge:graph[v]){
d[edge]--;
if(d[edge]==0) que.push(edge);
}
}
for(int i=1; i<=n; ++i)
if(d[i]) return true;
return false;
}
};