summaryrefslogtreecommitdiffstats
path: root/03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite
diff options
context:
space:
mode:
authorJérémy Zurcher <jeremy@asynk.ch>2016-11-13 23:06:24 +0100
committerJérémy Zurcher <jeremy@asynk.ch>2016-11-13 23:06:24 +0100
commit0c0188d855ca9f452b7fe44d51f86661850ca892 (patch)
tree08cbe53d273ead45668d49aaeb5094849ce21501 /03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite
parentc498a66df48f4a52b2b73a1ce7ca8001b2cc92bc (diff)
downloadcoursera-0c0188d855ca9f452b7fe44d51f86661850ca892.zip
coursera-0c0188d855ca9f452b7fe44d51f86661850ca892.tar.gz
Algorithms : complete 03-algorithms_on_graphs 03-paths_in_graphs
Diffstat (limited to '03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite')
-rw-r--r--03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite/bipartite.cpp29
1 files changed, 26 insertions, 3 deletions
diff --git a/03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite/bipartite.cpp b/03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite/bipartite.cpp
index f97eca5..dfd74e1 100644
--- a/03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite/bipartite.cpp
+++ b/03-algorithms_on_graphs/03-paths_in_graphs/02-bipartite/bipartite.cpp
@@ -6,8 +6,31 @@ using std::vector;
using std::queue;
int bipartite(vector<vector<int> > &adj) {
- //write your code here
- return -1;
+ vector<int> t(adj.size(), -1);
+
+ queue<int> q;
+ q.push(0);
+ t[0] = 0;
+
+ int tag = 1;
+ while (!q.empty()) {
+ int v = q.front();
+ /* std::cout << " check : " << v << " tag " << tag << std::endl; */
+ q.pop();
+ tag = !t[v];
+ for (int i = 0; i < adj[v].size(); i++) {
+ int w = adj[v][i];
+ /* std::cout << " " << w << " " << t[w] << std::endl; */
+ if (t[w] == -1) {
+ q.push(w);
+ t[w] = tag;
+ } else if (t[w] != tag) {
+ /* std::cout << " wrong " << w << " " << t[w] << std::endl; */
+ return 0;
+ }
+ }
+ }
+ return 1;
}
int main() {
@@ -20,5 +43,5 @@ int main() {
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
- std::cout << bipartite(adj);
+ std::cout << bipartite(adj) << '\n';
}