summaryrefslogtreecommitdiffstats
path: root/03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 23:04:26 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 23:04:26 +0100
commita80b82ef6c4214d16b5c6df76c90fb88f23329f7 (patch)
treec1c336c3c0691df3cf2969a5a286e20509833a6f /03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp
parentce845d792479e9c153274c2ad5a199a7f7c17a41 (diff)
downloadcoursera-a80b82ef6c4214d16b5c6df76c90fb88f23329f7.zip
coursera-a80b82ef6c4214d16b5c6df76c90fb88f23329f7.tar.gz
Algorithms : complete 03-algorithms_on_graphs 02-decomposition
Diffstat (limited to '03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp')
-rw-r--r--03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp38
1 files changed, 34 insertions, 4 deletions
diff --git a/03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp b/03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp
index 9cd27e6..24e9371 100644
--- a/03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp
+++ b/03-algorithms_on_graphs/02-decomposition/01-acyclicity/acyclicity.cpp
@@ -1,12 +1,42 @@
#include <iostream>
#include <vector>
+#include <stack>
using std::vector;
-using std::pair;
+using std::stack;
int acyclic(vector<vector<int> > &adj) {
- //write your code here
- return 0;
+ vector<bool> marked(adj.size());
+ vector<bool> visited(adj.size());
+
+ stack<int> st;
+
+ for (int i = 0; i < adj.size(); i++) {
+ if (marked[i])
+ continue;
+ st.push(i);
+ while(!st.empty()) {
+ int v = st.top();
+ visited[v] = true;
+ int s = adj[v].size();
+ for (int j = 0; j < s; j++) {
+ int w = adj[v][j];
+ if (!marked[w]) {
+ if (visited[w])
+ return 1;
+ st.push(w);
+ }
+ }
+
+ if (st.top() == v) {
+ visited[v] = false;
+ marked[v] = true;
+ st.pop();
+ }
+ }
+ }
+
+ return 0;
}
int main() {
@@ -18,5 +48,5 @@ int main() {
std::cin >> x >> y;
adj[x - 1].push_back(y - 1);
}
- std::cout << acyclic(adj);
+ std::cout << acyclic(adj) << '\n';
}