Skip to content

Commit

Permalink
Merge pull request #132 from yuvaraja99/patch-3
Browse files Browse the repository at this point in the history
Created is-graph-bipartite.cpp
  • Loading branch information
Ayushsinhahaha authored Oct 28, 2022
2 parents 8df73aa + 4c2b761 commit 3a07711
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions is-graph-bipartite.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Check if a graph is bipartite or not
//BFS Solution

class Solution {
public:
bool isBipartite(vector<vector<int>>& graph) {
unordered_map<int, int> color;
for (int node = 0; node < graph.size(); ++node) {
if (color.count(node)) {
continue;
}
vector<int> stack{node};
color[node] = 0;
while (!stack.empty()) {
int curr = stack.back(); stack.pop_back();
for (const auto& neighbor : graph[curr]) {
if (!color.count(neighbor)) {
stack.emplace_back(neighbor);
color[neighbor] = color[curr] ^ 1;
} else if (color[neighbor] == color[curr]) {
return false;
}
}
}
}
return true;
}
};

0 comments on commit 3a07711

Please sign in to comment.