Skip to content

Commit 0710a8d

Browse files
authored
Create is-graph-bipartite.cpp
1 parent 49193f8 commit 0710a8d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: C++/is-graph-bipartite.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)