We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 49193f8 commit 0710a8dCopy full SHA for 0710a8d
C++/is-graph-bipartite.cpp
@@ -0,0 +1,28 @@
1
+// Time: O(|V| + |E|)
2
+// Space: O(|V|)
3
+
4
+class Solution {
5
+public:
6
+ bool isBipartite(vector<vector<int>>& graph) {
7
+ unordered_map<int, int> color;
8
+ for (int node = 0; node < graph.size(); ++node) {
9
+ if (color.count(node)) {
10
+ continue;
11
+ }
12
+ vector<int> stack{node};
13
+ color[node] = 0;
14
+ while (!stack.empty()) {
15
+ int curr = stack.back(); stack.pop_back();
16
+ for (const auto& neighbor : graph[curr]) {
17
+ if (!color.count(neighbor)) {
18
+ stack.emplace_back(neighbor);
19
+ color[neighbor] = color[curr] ^ 1;
20
+ } else if (color[neighbor] == color[curr]) {
21
+ return false;
22
23
24
25
26
+ return true;
27
28
+};
0 commit comments