forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathis-graph-bipartite.cpp
More file actions
28 lines (27 loc) · 872 Bytes
/
is-graph-bipartite.cpp
File metadata and controls
28 lines (27 loc) · 872 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Time: O(|V| + |E|)
// Space: O(|V|)
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;
}
};