forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0886.cpp
More file actions
executable file
·40 lines (35 loc) · 875 Bytes
/
LC0886.cpp
File metadata and controls
executable file
·40 lines (35 loc) · 875 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
29
30
31
32
33
34
35
36
37
38
39
40
/*
Problem Statement: https://leetcode.com/problems/possible-bipartition/
Time: O(V + E)
Space: O(V + E)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
bool possibleBipartition(int N, vector<vector<int>>& dislikes) {
bool is_bipartite = true;
vector<int> color(N + 1);
vector<bool> visited(N + 1);
vector<vector<int>> adj(N + 1);
// helper function
function<void(int, int)> dfs = [&](int s, int col) {
color[s] = col;
visited[s] = true;
for (int& u: adj[s]) {
if (visited[u])
is_bipartite &= color[u] != color[s];
else
dfs(u, (color[s] + 1) % 2);
}
};
// construct adjacency list
for (auto& edge: dislikes) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
for (int i = 1; i <= N; i++)
if (!visited[i])
dfs(i, 0);
return is_bipartite;
}
};